如何在Firebase函数中检查Stripe Webhook签名

时间:2019-12-20 12:33:50

标签: node.js firebase google-cloud-functions stripe-payments

您好??我正在尝试验证Firebase函数中的Stripe签名。但是当我尝试stripe.webhooks.constructEvent时,它会收到一条错误消息:

No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing?

我已经注销了原始尸体,看起来还不错?

<Buffer 7b 0a 20 20 22 69 64 22 3a 20 22 65 76 74 5f 31 46 72 6b 4d 73 41 55 73 34 77 79 52 42 49 73 63 6d 66 72 43 39 7a 37 22 2c 0a 20 20 22 6f 62 6a 65 63 ... >

以下是相关代码:

  // A webhook called by stripe
  const sig = req.headers['stripe-signature']
  let event
  // 1. construct event and validate
  try {
    event = stripe.webhooks.constructEvent(req.rawBody, sig, functions.config().stripe.mytestkey)
    assert(event)
  } catch (err) {
    console.log(`Error when constructing Stripe event: ${err} - ${req.body}`)
    res.status(400).send({ error: `Stripe webhook error: ${err}` })
    return
  }

  // 2. Handle webhook
  res.status(200).send(`successfully handled webhook ${hook}`)
})

有什么想法吗? ?

2 个答案:

答案 0 :(得分:1)

let sig = req.get('stripe-signature');

代替

const sig = req.headers['stripe-signature']

应该可以解决问题。

根据Express documentation

  

req.get(field)

     

返回指定的HTTP请求标头字段(不区分大小写)   匹配)。

答案 1 :(得分:1)

最后,我发现必须写req.rawBody.toString('utf8')。 来源:https://github.com/stripe/stripe-node/issues/341