LoginSignup
33
34

More than 5 years have passed since last update.

決済API StripeをNode.jsとExpressで動かしてみた。

Posted at

概要

決済APIであるStripeを用いて、カスタマーの登録、カスタマーのカード登録、都度決済の実行を行います。
この際、Expressを用いたNode.jsサーバにより、それぞれの処理を実行します。
システムとしては、サーバでプログラムを回し続けて、そこにAPIを投げる形で各処理を実行します。

このページを読んでできること

・Expressを用いた簡単なNode.jsサーバの立ち上げ
・Stripeによるカスタマーの登録、カスタマーのカードの登録、都度決済

参考にしたページ

node.js + expressでPOSTを受け取る & POSTパラメータをJSONで取得する
https://qiita.com/ktanaka117/items/596febd96a63ae1431f8
[nodejs][stripe] stripe を node で使う(customer 情報の登録)
https://qiita.com/wokamoto/items/0be8471d38044ada9209
[nodejs][stripe] stripe を node で使う(単発の支払い)
https://qiita.com/wokamoto/items/74bf257473e98f623025

Node.jsとは

Node.js
https://nodejs.org/ja/
Node.js® は、Chrome の V8 JavaScript エンジン で動作する JavaScript 環境です。 Node.js は、軽量で効率的に動作する非同期型のイベント駆動モデルを採用しています。 Node.js のパッケージ管理マネージャである npm は、世界で最も大きなオープンソースのライブラリエコシステムです。

Expressとは

Express.js
http://expressjs.com/ja/
Express は、Web アプリケーションとモバイル・アプリケーション向けの一連の堅固な機能を提供する最小限で柔軟な Node.js Web アプリケーション・フレームワークです。

Stripeとは

Stripe API Reference
https://stripe.com/docs/api
ウェブアプリなどでの決済に用いることができるAPIです。

手順

任意のディレクトリを作りましょう。
ここではstripe-node-expressとします。
$ mkdir stripe-node-express
ディレクトリへ移動しましょう。
$ cd stripe-node-express
node.jsを用いるためにnpmをinitします。
$ npm init
Expressをインストールします。
$ npm install express --save
Stripeをインストールします。
$ npm install stripe --save
環境変数を格納するためにdotenvをインストールします。
$ npm install dotenv --save

プログラムを記述

stripe-express.js
//config express
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

var export_func = require("./stripe-exports");

// urlencodedとjsonは別々に初期化する
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

app.listen(3000);
console.log('Server is online.');

app.post('/stripe-create-customer', function(req, res) {
  export_func.stripe_create_customer(req.body.email);
  res.send('Created a customer.\n');
  console.log('Created a customer.');
})
app.post('/stripe-create-card', function(req, res) {
  export_func.stripe_create_card(req.body.customer_id, req.body.card_num, req.body.card_month, req.body.card_year, req.body.card_cvc);
  res.send('Created a card.\n');
  console.log('Created a card.');
})
app.post('/stripe-charge', function(req, res) {
  export_func.stripe_charge(req.body.price, req.body.description, req.body.customer_id);
  res.send('Created a charge.\n');
  console.log('Created a charge.');
})

stripe-exports.js
//config environment
require("dotenv").config();
//config stripe
var stripe = require('stripe')(process.env.token)
//console.log(process.env.token);

//customer_email:顧客のメールアドレス
exports.stripe_create_customer = function(customer_email) {
  stripe.customers.create({
    email: customer_email
  }, function(err, customer) {
    // asynchronously called
    console.log(customer);
  });

}

//id:顧客のID
//num:カード番号, month:カードの有効期限, year:カードの有効期限, cvc:カードのセキュリティ番号
exports.stripe_create_card = function (id,num,month,year,cvc){
  console.log(id,num,month,year,cvc);
  stripe.tokens.create({
    card: {
      "number": num,
      "exp_month": month,
      "exp_year": year,
      "cvc": cvc
    }
  }, function(err, token) {
    // asynchronously called
    var params = {
      source: token.id
    };
    stripe.customers.createSource(id, params, function(err, card) {
      console.log(card);
    });
  });
}

//price:請求価格, description:説明, customer_id:顧客のID
exports.stripe_charge = function(price, description, customer_id) {
  var charge = stripe.charges.create({
    amount: price,
    currency: "jpy",
    description: description,
    customer: customer_id
  })
}

プログラムを実行

$ node stripe-express.js
でnode.jsサーバを立ち上げます。
別のコンソールにおいて下記のコマンドを実行します。

カスタマー作成

$ curl -X POST http://localhost:3000/stripe-create-customer -H "Accept: application/json" -H "Content-type: application/json" -d '{ "email" : "CUSTOMER_EMAIL" }'

カスタマーのカード登録

$ curl -X POST http://localhost:3000/stripe-create-card -H "Accept: application/json" -H "Content-type: application/json" -d '{ "customer_id" : "CUSTOMER_ID", "card_month":"12", "card_year":"2019" ,"card_num":"4242424242424242", "card_cvc":"123" }'

都度決済

$ curl -X POST http://localhost:3000/stripe-charge -H "Accept: application/json" -H "Content-type: application/json" -d '{ "price" : 3000, "description":"DESCRIPTION", "customer_id":"CUSTOMER_ID" }'

33
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
34