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