如何使用无服务器功能获取RAW主体?

我正在从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作为对象,如何解决此问题?

owensun0306 回答:如何使用无服务器功能获取RAW主体?

以下代码段对我有用(从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,},};
本文链接:https://www.f2er.com/2829501.html

大家都在问