我正在使用Stripe提供的代码来测试Webhook。 Stripe机密和端点机密已被三重检查。
条带版本:6.19 正文解析器:1.19
当我在Stripe仪表板上测试Webhook时,得到以下结果:(测试Webhook错误:400)找不到与有效负载的预期签名匹配的签名。您是否正在传递从Stripe收到的原始请求正文?
任何帮助将不胜感激。
var bodyParser - require('body-parser);
// Using Express
const app = require('express')();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_VPw...');
// Find your endpoint's secret in your Dashboard's webhook settings
const endpointSecret = 'whsec_...';
// Use body-parser to retrieve the raw body as a buffer
const bodyParser = require('body-parser');
// Match the raw body to content type application/json
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret); //NOT WORKING!
} 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...
handleCheckoutSession(session);
}
// Return a response to acknowledge receipt of the event
response.json({received: true});
});
答案 0 :(得分:1)
如何在 Express 中同时获取已解析的正文和原始正文:
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))
答案 1 :(得分:1)
对于那些使用 NextJS 的人。这是我在 Reddit 上遇到的一个解决方案@ u/SiMFiCysed https://www.reddit.com/user/SiMFiCysed/
答案 2 :(得分:0)
通常这是由于您一方在检查签名之前解析或修改了原始请求字符串(因此,签名是根据修改后的字符串而不是发送的确切的Stripe计算的)。在这种情况下,JSON bodyParser中间件似乎正在执行此操作:
app.use(bodyParser.json());
Stripe提供了一个示例,该示例在Webhook端点上使用原始的bodyParser中间件,以便您的代码获取所需的原始字符串:https://github.com/stripe/stripe-node/blob/master/examples/webhook-signing/express.js
答案 3 :(得分:0)
一个班轮,对我来说就像一个魅力
app.use('/stripe/webhook', express.raw({type: "*/*"}))
app.use(express.json())