LoginSignup
44
22

More than 3 years have passed since last update.

stripeをfirebaseで使うときidempotency_keyをつけよう

Posted at

先日firebase functionsとstripeのサンプルコードを公開したときに、

てな感じで、noriさんにアドバイスを頂きました。その話をまとめます。

Cloud Functionsは複数回呼び出される可能性がある

なので、stripeで決済処理をする際、複数回叩かれて2重決済になったりしないように、対策が必要なわけです。

stripe.jsのidempotency_key

順当にstripeのドキュメントを見ていくと、idempotency_keyの実装については触れずに進んでいってしまうのですが、github.com/stripe/stripe-nodePassing-Optionsに書いてありました。

idempotentはべき等という意味で、べき等とは、ある操作を1回行っても複数回行っても結果が同じであることをいう概念です。つまりidempotency_keyをつければ、そのkeyがついたリクエストを複数行ったとしても1回だけの処理にしてくれるということです。

これをつけたコードがこちら。

exports.createStripeCharge = functions.https.onCall((data, context) => {
    const customer = data.customerId;
    const source = data.sourceId;
    const amount = data.amount;
    const idempotencyKey = data.idempotencyKey;

    return stripe.charges.create({
        customer: customer,
        source: source,
        amount: amount,
        currency: "jpy",
        { idempotency_key: idempotencyKey } // これ!
    })
});

すべてのstripe.jsのメソッドに対して、追加の引数として渡すとべき等にしてくれます。決済などの重複してはいけない処理にはつけた方が良さそうですね。

関連記事

44
22
1

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
44
22