【问题标题】:Why can't I get access to rawBody in my express request为什么我无法在我的明确请求中访问 rawBody
【发布时间】:2021-06-19 00:28:30
【问题描述】:

我正在尝试使用 req.rawBody 来验证我的条带签名,这是我包含在我的主 server.js 文件中的代码...

app.use(bodyParser.json())
app.use(bodyParser.json({
    verify: (req, res, buf) => {
      req.rawBody = buf
    }
}))

然后这是我的 stripePaymentRoutes.js 文件中的代码...

router.post('/billing/invoice-result', (req, res) => {

    let event
    const signature = req.headers['stripe-signature']
    console.log(req.rawBody)

    try {
        event = stripe.webhooks.constructEvent(req.rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET_KEY)
    } catch (err) {
        return res.status(400).send(`Webhook Error: ${err.message}`)
    }
})

当我使用 console.log(req.rawBody) 时,它返回 undefined 并且我的所有 webhook 都转到 catch 块,因为 req.rawBody 未定义,因此未验证签名。任何想法为什么我无法获取 req.rawBody 数据?

【问题讨论】:

  • 这通常是由于 body-parser 正在做的解析。查看this issue 了解一些可能的解决方案。

标签: express stripe-payments body-parser


【解决方案1】:

为了解决这个问题,从页面 taintedzodiac 指出 - 我必须像这样在我的 json 解析器之前添加原始中间件

app.use(<your webhook endpoint>, express.raw({ type: "*/*" })); 
app.use(express.urlencoded({ extended: true }))
app.use(express.json());

然后在您的 webhook 端点中

app.post(<your webhook endpoint>, (request, response) => {
    let event = request.body;

    // Only verify the event if you have an endpoint secret defined.
    // Otherwise use the basic event deserialized with JSON.parse
    if (process.env.STRIPE_WEBHOOK_SECRET) {
      // Get the signature sent by Stripe
      const signature = request.headers['stripe-signature'];
      try {
        event = stripe.webhooks.constructEvent(request.body, signature, process.env.STRIPE_WEBHOOK_SECRET);
      } catch (err) {
        console.log(`⚠️  Webhook signature verification failed.`, err.message);
        return response.sendStatus(400);
      }
    }
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多