LoginSignup
13
11

More than 5 years have passed since last update.

Stripeのカスタマーを作成するときはStripeIDを必ず控えておく

Posted at

Stripeのカスタマーはメールアドレスで一意性をとっているというわけではなく、同じメールアドレスでもstripe.customers.create()を複数回実行するとその度にカスタマーが作成される。

スクリーンショット 2017-03-17 14.23.28.png

カスタマーとメールアドレスを一意に保つには、Stripe IDで参照できるようにしておく必要がある。Stripe IDはstripe.customers.create()の戻り値のidに入っている。

カスタマー作成後にStripe IDを取得するサンプル

const stripe = require("stripe")(
  "sk_test_XXXXXX"
);

const customers = {
  'email': 'customer1@example.com'
}

stripe.customers.create(
  customers,
  function(err, customer) {
    if(err) {
      console.log(err)
    }
    console.log(customer.id)
  }
);

このStripe IDでstripe.customers.retrieve()することでカスタマーの存在を確認できる。

カスタマーが存在しない場合のみ、カスタマーを作成するサンプル

Stripe IDが存在しない場合、stripe.customers.retrieve()のエラーにmessage: 'No such customer: STRIPE_ID'という値が入っているので、それを見てカスタマーの有無を確認できる。

const stripe = require("stripe")(
  "sk_test_XXXXXX"
);
var customers = {
  'stripeId': 'cus_XXXXXX',
  'params': {
    'email': 'customer1@example.com',
    'description': 'This is example customer',
    'metadata': {
      'sampleKey': 'sampleValue',
      'sampleKey001': 'sampleValue001'
    }
  }
}

stripe.customers.retrieve(
  customers.stripeId,
  function(err, customer) {
    if (err) {
      if (err.message == 'No such customer: ' + customers.stripeId) {
        // カスタマーを新規に作成する
        stripe.customers.create(
          customers.params,
          function(err, customer) {
            if(err) {
              console.log(err)
            }
            console.log(customer)
          }
        )
      } else {
         // ここはカスタマーが存在しない場合以外で出たエラー
        console.log(err)
      }
    } else {
      // カスタマーを更新する
      stripe.customers.update(
        customers.stripeId,
        customers.params,
        function(err, customer) {
          if(err) {
            console.log(err)
          }
          console.log(customer)
        }
      )
    }
  }
)

多分Promiseとか使っていい感じにラップしてやったほうがわかりやすい。

13
11
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
13
11