
本文旨在解决 Stripe Webhook 签名验证失败的问题,重点分析 No signatures found matching the expected signature for payload 错误,并提供相应的代码示例和修改建议,帮助开发者正确配置和验证 Stripe Webhook,确保支付流程的安全性和可靠性。
在使用 Stripe Webhook 的过程中,签名验证是至关重要的一步,它能确保接收到的请求确实来自 Stripe,而非恶意伪造。当出现 No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? 错误时,通常意味着你的代码在处理请求体或签名时出现了问题。以下将详细分析可能的原因并提供解决方案。
常见错误原因及解决方案
请求体解析方式不正确
Stripe Webhook 需要接收原始的请求体(raw request body)用于签名验证。如果使用了错误的中间件或配置,导致请求体被解析成 JSON 对象或其他格式,签名验证就会失败。
解决方案:
使用 express.raw 中间件,并指定正确的 type。通常,application/json 是一个更合适的选择,因为它确保只处理 JSON 类型的请求,而不是所有类型的请求(*/*)。
app.post("/webhook", express.raw({ type: 'application/json' }), async (request, response) => {
// ...
});注意事项:
constructEvent 函数参数错误
stripe.webhooks.constructEvent 函数用于验证签名并构建事件对象。该函数需要接收原始的请求体字符串,签名信息以及 Webhook Secret。
解决方案:
确保将原始请求体直接传递给 constructEvent 函数,而不是 JSON 字符串化后的对象。
const payload = request.body;
const sig = request.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
payload, // 使用原始请求体
sig,
process.env.WEBHOOK_SECRET
);
} catch (err) {
return response.status(400).send(`Webhook Error: ${err.message}`);
}注意事项:
完整示例代码
以下是一个完整的示例代码,展示了如何正确处理 Stripe Webhook 并进行签名验证:
const express = require('express');
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY'); // 替换为你的 Stripe Secret Key
const app = express();
app.post("/webhook", express.raw({ type: 'application/json' }), async (request, response) => {
const payload = request.body;
const sig = request.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
payload,
sig,
process.env.WEBHOOK_SECRET
);
} catch (err) {
return response.status(400).send(`Webhook Error: ${err.message}`);
}
// 处理不同的事件类型
switch (event.type) {
case 'checkout.session.completed':
const session = event.data.object;
// 处理订单完成事件
console.log("Payment successed")
break;
// 可以添加其他事件类型的处理逻辑
default:
console.log(`Unhandled event type ${event.type}`);
}
response.status(200).end();
});
app.listen(4242, () => console.log('Running on port 4242'));总结
解决 No signatures found matching the expected signature for payload 错误的关键在于:
通过以上步骤,可以有效地解决 Stripe Webhook 签名验证失败的问题,保障支付流程的安全性和可靠性。在实际开发中,建议仔细阅读 Stripe 官方文档,了解更多关于 Webhook 的细节和最佳实践。
以上就是Stripe Webhook 签名验证失败问题排查与解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号