【问题标题】:Stripe webhook with Google Cloud Functions keeps giving Webhook Error: No signatures found matching the expected signature for payload带有 Google Cloud Functions 的 Stripe webhook 不断给出 Webhook 错误:未找到与有效负载的预期签名匹配的签名
【发布时间】:2021-03-14 20:07:28
【问题描述】:

我知道以前有人问过这个问题,但是如果我在其他问题中实施解决方案,我仍然会收到错误。

情况是:

我尝试将我的 Stripe webhook 测试到 Node.js/Express/Google Cloud Functions 后端。如果我只实现文档中的代码,则会收到错误消息:未找到与有效负载的预期签名匹配的签名。您是否传递了从 Stripe 收到的原始请求正文?

当我在 StackOverflow (Stripe Error: No signatures found matching the expected signature for payload) 上搜索此错误时,我读到:

Cloud Functions 自动解析已知类型的正文内容。如果 您正在获取 JSON,然后它已经被解析并可供您使用 请求正文。您不需要添加其他正文解析中间件。

如果你需要处理原始数据,你应该使用req.rawBody,但我 不要认为你需要在这里这样做。

这是包含 Stripe 文档中的代码的代码:

const functions = require('firebase-functions');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
const stripe = require('stripe')('sk_test_****');
const cron = require('node-cron');

// Stripe
const endpointSecret = "whsec_****"

const fulfillOrder = (session) => {
    // TODO: fill me in
    console.log("Fulfilling order", session);
  }
  
 app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
    const payload = request.body;
    const sig = request.headers['stripe-signature'];
  
    let event;
  
    try {
      event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
    } catch (err) {
      return response.status(400).send(`Webhook Error: ${err.message}`);
    }
  
    // Handle the checkout.session.completed event
    if (event.type === 'checkout.session.completed') {
      const session = event.data.object;
  
      // Fulfill the purchase...
      fulfillOrder(session);
    }
  
    response.status(200);
  });

这给出了众所周知的错误:Webhook 错误:未找到与有效负载的预期签名匹配的签名。您是否传递了从 Stripe 收到的原始请求正文? https://github.com/stripe/stripe-node#webhook-signing

所以我理解的方式是使用谷歌云功能时我需要使用:

const payload = request.rawBody;

这给出了同样的错误。要么是这个错误,要么是超时错误。

我试过了:

app.post('/webhook', bodyParser.raw({type: "*/*"}), (request, response) => {
    const payload = request.rawBody

这会导致超时错误。

我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    Node 框架和中间件通常会修改主体(甚至是原始主体),导致 Stripe 签名验证失败。不幸的是,没有一个单一的、防弹的修复程序,但我建议您查看这个 GitHub 问题中的几种方法和解决方法:https://github.com/stripe/stripe-node/issues/341

    希望其中一项修复对您有用。一般来说,主要的事情是尽快将原始正文从请求中取出,然后再进行任何修改。

    【讨论】:

    • 感谢贾斯汀迈克尔。我会看看回购。
    猜你喜欢
    • 2019-11-10
    • 2022-12-12
    • 2021-02-19
    • 2019-05-22
    • 2020-07-07
    • 2019-09-04
    • 2020-04-25
    • 2021-07-26
    • 2022-11-19
    相关资源
    最近更新 更多