LoginSignup
3
2

More than 5 years have passed since last update.

Node.jsでStripeのカスタマーを追加する

Last updated at Posted at 2017-03-17

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)
  }
);

3
2
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
3
2