我正在从Zeit Now上的Express迁移到无服务器功能。
Stripe webhook docs要求原始请求,使用Express时,我可以通过bodyParser来获取它,但是它如何在无服务器功能上工作?我如何以字符串格式接收正文以验证条纹签名?
支持团队将我重定向到了此documentation link,据我所知,我很困惑,我必须将text/plain
传递到请求标头中,但自Stripe以来我无法控制它是发送Webhook的人。
export default async (req, res) => {
let sig = req.headers["stripe-signature"];
let rawBody = req.body;
let event = stripe.webhooks.constructEvent(rawBody, sig, process.env.STRIPE_SIGNING_SECRET);
...
}
在我的函数中,我收到req.body
作为对象,如何解决此问题?
答案 0 :(得分:4)
以下代码段对我有用(从source修改而来):
const endpointSecret = process.env.STRIPE_SIGNING_SECRET;
export default async (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
let bodyChunks = [];
req
.on('data', chunk => bodyChunks.push(chunk))
.on('end', async () => {
const rawBody = Buffer.concat(bodyChunks).toString('utf8');
try {
event = stripe.webhooks.constructEvent(rawBody, sig, endpointSecret);
} catch (err) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle event here
...
// Return a response to acknowledge receipt of the event
res.json({ received: true });
});
};
export const config = {
api: {
bodyParser: false,
},
};