0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Firebase FunctionsでStripeのWebhookを動かす

Posted at

Stripeは、会員登録の状態や決済のオーソリ状態をWebhookで受信して、所有するデータの反映を行う場面が多々あります。

Stripeの開発者ダッシュボードは優れたコード生成支援があり、必要なWebhookのイベントタイプを選択追加するだけで、NodeのExpressを使ったサンプルコードを生成してくれます。

ただし、Firebase FunctionsでWebhookを受信したい場合には、Stripeがコード生成支援しているコードだとrequest.bodyが合わず、stripe.webhooks.constructEventが利用できません。解決方法は、request.bodyではなく、request.rawBodyを参照します。

exports.stripWebhook= functions.region('asia-northeast1').https.onRequest(async (request, response) => {
  const stripe = require('stripe');
  const sig = request.headers['stripe-signature'];
  const endpointSecret = "[あなたのエンドポイントシークレットキー]";
  try {
    event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret);
    console.log("endpointSecret:", "OK!" )
  } catch (err) {
    console.log("error:",err.message )
    response.status(400).send(`Webhook Error: ${err.message}`);
    return;
  }
  // Handle the event
  switch (event.type) {
    case 'payment_intent.amount_capturable_updated':
      var paymentIntent = event.data.object;
      break;
    default:
      console.log(`Unhandled event type ${event.type}`);
  }
  response.send();
  return
)}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?