Stripe Webhook
Hono で API を作成して、Stripe Webhook のイベントを受け取る方法を紹介します。
準備
まず、Stripe の公式 SDK をインストールしてください。
bash
npm install stripe次に、.dev.vars ファイルに次の値を追加して、Stripe API キーを設定します。
STRIPE_API_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxxStripe API キーについては、次のドキュメントを参照してください。
- シークレットキー:https://docs.stripe.com/keys
- Webhook シークレット:https://docs.stripe.com/webhooks
Stripe Webhook イベントを受け取る API の保護
Webhook イベントを処理する API は公開されています。そのため、悪意のある第三者が Stripe の Webhook イベントオブジェクトを偽装してリクエストを送信するなどの攻撃から保護する仕組みが必要です。Stripe では、Webhook シークレットを発行し、各リクエストを検証することで API を保護できます。
詳細:https://docs.stripe.com/webhooks?lang=node#verify-official-libraries
ホスティング環境やフレームワークに応じた Webhook API の実装
Stripe で署名を検証するには、生のリクエストボディが必要です。 フレームワークを使う場合は、元のボディが変更されないようにしてください。生のリクエストボディに何らかの変更が加わると、検証に失敗します。
Hono では、context.req.text() メソッドで生のリクエストボディを取得できます。そのため、次の例のように Webhook API を作成できます。
ts
import Stripe from 'stripe'
import { Hono } from 'hono'
import { env } from 'hono/adapter'
const app = new Hono()
app.post('/webhook', async (context) => {
const { STRIPE_SECRET_API_KEY, STRIPE_WEBHOOK_SECRET } =
env(context)
const stripe = new Stripe(STRIPE_SECRET_API_KEY)
const signature = context.req.header('stripe-signature')
try {
if (!signature) {
return context.text('', 400)
}
const body = await context.req.text()
const event = await stripe.webhooks.constructEventAsync(
body,
signature,
STRIPE_WEBHOOK_SECRET
)
switch (event.type) {
case 'payment_intent.created': {
console.log(event.data.object)
break
}
default:
break
}
return context.text('', 200)
} catch (err) {
const errorMessage = `⚠️ Webhook signature verification failed. ${
err instanceof Error ? err.message : 'Internal server error'
}`
console.log(errorMessage)
return context.text(errorMessage, 400)
}
})
export default app関連情報
- Stripe Webhook の詳細: https://docs.stripe.com/webhooks
- 決済処理の実装: https://docs.stripe.com/payments/handling-payment-events
- サブスクリプション処理の実装: https://docs.stripe.com/billing/subscriptions/webhooks
- Stripe が送信する Webhook イベントの一覧: https://docs.stripe.com/api/events
- Cloudflare 向けのサンプルテンプレート: https://github.com/stripe-samples/stripe-node-cloudflare-worker-template/