如何在 firebase 函数中检查 Stripe webhook 签名

Posted

技术标签:

【中文标题】如何在 firebase 函数中检查 Stripe webhook 签名【英文标题】:How to check Stripe webhook signatures in firebase functions 【发布时间】:2020-04-12 23:21:12 【问题描述】:

嗨??????????我正在尝试验证 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`)
)

有什么想法吗? ????

【问题讨论】:

【参考方案1】:

在做

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

而不是

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

应该可以解决问题。

根据Express documentation:

req.get(field)

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

【讨论】:

谢谢。我发现我必须写req.rawBody.toString('utf8') Mmmmm.. 在我自己的 Cloud Functions 中,做stripe.webhooks.constructEvent( req.rawBody, sig, stripeWebhookSecret );works。 真的吗?这很奇怪。当您使用req.get('stripe-signature'); 时,它可能适用于缓​​冲区,但不适用于req.headers['stripe-signature'] ?。我很高兴它现在可以工作了。【参考方案2】:

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

【讨论】:

以上是关于如何在 firebase 函数中检查 Stripe webhook 签名的主要内容,如果未能解决你的问题,请参考以下文章

使用 Firebase HTTP 函数(Firebase、Stripe OAuth、React (JSX) 前端)将授权代码返回到 Stripe

Stripe Firebase 云函数 - res.send() 不是函数

对如何在我的网络应用程序中使用 Stripe 作为 Firebase 的扩展感到困惑

Stripe Connect Firebase 功能

从 firebase 下载文件并上传到 Stripe 进行身份验证

Firebase + stripe + react native 通知客户端 firebase 功能已完成