条带Web挂钩错误:找不到与有效负载的预期签名匹配的签名 [英] Stripe webhook error: No signatures found matching the expected signature for payload
本文介绍了条带Web挂钩错误:找不到与有效负载的预期签名匹配的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Strike提供的代码来测试WebHook。条带密码和终结点密码已经过三重检查。
条带版本:6.19 正文-解析器:1.19当我在条纹仪表板上测试WebHook时,我得到的结果是:(测试WebHook错误:400)找不到与有效负载的预期签名匹配的签名。您是否正在传递从条纹收到的原始请求正文?
如有任何帮助,我们将不胜感激。
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});
});
推荐答案
通常这是由于您方在检查签名之前解析或修改原始请求字符串造成的(因此签名是根据修改后的字符串计算的,而不是根据发送的确切字符串计算的)。在本例中,看起来JSON express中间件正在执行此操作:
app.use(express.json());
。
STRIPEan example必须在WebHook终结点上使用原始bodyParser中间件,以便您的代码获得所需的原始字符串:
// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
express.json()(req, res, next);
}
});
// Stripe requires the raw body to construct the event
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Successfully constructed event
console.log('✅ Success:', event.id);
// Return a response to acknowledge receipt of the event
res.json({received: true});
});
这篇关于条带Web挂钩错误:找不到与有效负载的预期签名匹配的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文