1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| // Node.js / Express
import Stripe from 'stripe'
import express from 'express'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)
const app = express()
// ⚠️ 重要: JSON parseの前にraw bodyが必要
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
async (req, res) => {
const sig = req.headers['stripe-signature']!
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!
let event: Stripe.Event
try {
event = stripe.webhooks.constructEvent(
req.body, // raw body
sig,
webhookSecret
)
} catch (err) {
console.error('Webhook signature verification failed:', err)
return res.status(400).send(`Webhook Error: ${err.message}`)
}
// イベントを処理
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object
console.log('Payment succeeded:', paymentIntent.id)
break
case 'checkout.session.completed':
const session = event.data.object
await handleCheckoutComplete(session)
break
}
res.json({ received: true })
}
)
|