【问题标题】:How to get the RAW Body using serverless functions?如何使用无服务器功能获取 RAW Body?
【发布时间】:2020-01-02 15:51:04
【问题描述】:

我正在 Zeit Now 上从 Express 迁移到无服务器功能。

Stripe webhook docs 请求原始正文请求,当使用 Express 时,我可以通过 bodyParser 获取它,但它如何在无服务器功能上工作?如何以字符串格式接收正文以验证条带签名?

支持团队将我重定向到此documentation link,我很困惑,据我了解,我必须将text/plain 传递到请求标头中,但我无法控制它,因为 Stripe 是发送的网络钩子。

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 作为对象,我该如何解决这个问题?

【问题讨论】:

    标签: node.js serverless vercel


    【解决方案1】:

    以下代码 sn-p 为我工作(修改自 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,
      },
    };
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 2021-10-31
      • 2018-11-25
      • 2021-08-18
      • 2019-08-31
      相关资源
      最近更新 更多