[英]Stripe webhook error: No signatures found matching the expected signature for payload
I am using the code provide by Stripe to test a webhook.我正在使用 Stripe 提供的代码来测试 webhook。 The Stripe secret and the endpoint secret have been triple checked.
Stripe 密码和端点密码已经过三重检查。
Stripe version: 6.19 Body-Parser: 1.19条纹版本:6.19 正文解析器:1.19
When I test webhook on the Stripe dashboard I get the result: (Test webhook error: 400) No signatures found matching the expected signature for payload.当我在 Stripe 仪表板上测试 webhook 时,我得到了结果:(测试 webhook 错误:400)没有找到与有效负载的预期签名匹配的签名。 Are you passing the raw request body you received from Stripe?
您是否传递了从 Stripe 收到的原始请求正文?
Any help would be appreciated.任何帮助,将不胜感激。
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});
});
Usually this is due to something on your side parsing or modifying the raw request string before the signature is checked(so the signature is computed against a modified string, not the exact one Stripe sent).通常这是由于您在检查签名之前解析或修改了原始请求字符串(因此签名是根据修改后的字符串计算的,而不是确切的 Stripe 发送)。 In this case it looks like the JSON bodyParser middleware is doing that:
app.use(bodyParser.json());
在这种情况下,看起来 JSON bodyParser 中间件正在这样做:
app.use(bodyParser.json());
. .
Stripe has an example of using a raw bodyParser middleware on the webhook endpoint instead so that your code gets the raw string that's required : Stripe 有一个在 webhook 端点上使用原始 bodyParser 中间件的示例,以便您的代码获取所需的原始字符串:
// Stripe requires the raw body to construct the event
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
// raw body ^^^^^^^^^^^^^^
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
// body of request, already raw ^^^^^^^^
} 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});
});
One liner plus no deprecated bodyParser.一个班轮加上没有弃用的 bodyParser。 Make sure to define your endpoint's parser before the generic one, aka express.json().
确保在通用解析器之前定义端点的解析器,也就是express.json()。
app.use('/stripe/webhook', express.raw({type: "*/*"}))
app.use(express.json())
How to get both parsed body and raw body in Express:如何在 Express 中同时获取已解析的正文和原始正文:
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))
Thanks to: https://flaviocopes.com/express-get-raw-body/感谢: https : //flaviocopes.com/express-get-raw-body/
For those working with NextJS.对于那些使用 NextJS 的人。 Here is a solution I bumped on Reddit by one @ u/SiMFiCysed https://www.reddit.com/user/SiMFiCysed/
这是我在 Reddit 上遇到的一个解决方案 @ u/SiMFiCysed https://www.reddit.com/user/SiMFiCysed/
One other thing that could be going wrong (which was giving me the error) is that the production webhook key is being used with a test request, or vice versa.可能出错的另一件事(这给了我错误)是生产 webhook 密钥正在与测试请求一起使用,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.