使用 Nextjs 接收 Stripe 的 webhook

前言

在預設的情況下,Nextjs 會先對 Request 進行格式轉換,但與 Stripe 套件的格式不相容,需要先停止此功能,並將資料格式轉為 stream,才能讓 Stripe 的套件進行處理。

範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// pages/api/webhook.ts

import { buffer } from 'micro';

export const config = {
api: {
bodyParser: false,
},
}

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const rawBody = await buffer(req)

const endpointSecret = STRIPE.endpointSecret
const signature = req.headers['stripe-signature']!

const stripe = new Stripe(STRIPE_CONFIG.apiKey, {
apiVersion: '2022-08-01',
})

const event = stripe.webhooks.constructEvent(rawBody, signature, endpointSecret)

// logic...
}

Reference