Stripeで決済をするには、まずカスタマーの登録が必要です。
Node.jsのSDKでは、こんな感じで簡単にStripeにカスタマーを追加できます。
const stripe = require("stripe")(
"sk_test_XXXXX"
);
stripe.customers.create({
description: 'Customer for natalie.johnson@example.com',
source: "tok_XXXXX" // obtained with Stripe.js
}, function(err, customer) {
// asynchronously called
});
via:https://stripe.com/docs/api/node#create_customer
空のカスタマーも作れる
第一引数は空のオブジェクトでもいけるので、こんな感じで情報なしのカスタマーも作れます。
const stripe = require("stripe")(
"sk_test_XXXXX"
);
stripe.customers.create(
{},
function(err, customer) {
if(err) {
console.log(err)
}
console.log(customer)
}
);
メタデータを登録する
metadata
にオブジェクトを入れると、Stripeのカスタマーにメタデータを登録できます。
タグ付けとかをしたい場合に便利そうです。
const stripe = require("stripe")(
"sk_test_XXXXX"
);
const customers = {
'email': 'customer1@example.com',
'description': 'This is example customer',
'metadata': {
'sampleKey': 'sampleValue',
'sampleKey001': 'sampleValue001'
}
}
stripe.customers.create(
customers,
function(err, customer) {
if(err) {
console.log(err)
}
console.log(customer)
}
);
環境変数でテスト・本番を切り替えれるようにする
Lambdaとかでいろんな環境から実行したい時は、環境変数使うといいと思います。
console.log(process.env.STRIPE_ENV)
let stripe_secret = "sk_test_XXXXX"
if (process.env.STRIPE_ENV === undefined){
console.log('process.env.STRIPE_ENV not defined')
return
} else if (process.env.STRIPE_ENV == 'prod') {
stripe_secret = "sk_live_XXXXX"
}
const stripe = require("stripe")(
stripe_secret
);
const customers = {
'email': 'customer1@example.com',
'description': 'This is example customer',
'metadata': {
'sampleKey': 'sampleValue',
'sampleKey001': 'sampleValue001'
}
}
stripe.customers.create(
customers,
function(err, customer) {
if(err) {
console.log(err)
}
console.log(customer)
}
);