【发布时间】: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