当我在 cmd stripe 中运行以下命令时触发 payment_intent.succeeded 我在这里收到以下错误是 myhandleStripeWebhook
async function handleStripeWebhook(req, res) {
const sig = req.headers['stripe-signature'];
// const rawBody = JSON.stringify(req.rawBody);
try {
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
if (!webhookSecret) {
console.log("STRIPE_WEBHOOK_SECRET is not set")
throw new Error('STRIPE_WEBHOOK_SECRET is not set');
}
// console.log("Received Stripe webhook:", rawBody);
// Construct the event using the raw body and signature
event = stripe.webhooks.constructEvent(req.rawBody, sig, webhookSecret);
console.log('✅ Webhook signature verified');
} catch (err) {
console.error('⚠️ Webhook signature verification failed.', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
console.log('✅ Checkout session completed event received');
console.log('Session metadata:', session.metadata);
// Process the backend logic
await processBackendLogic(session.metadata);
}
res.json({ received: true });
}
这是我的路线:
router.post('/webhook', handleStripeWebhook , bodyParser.json({ verify: function (req, res, buf) { req.rawBody = buf.toString() } }));
我收到以下错误
⚠️ Webhook signature verification failed. No webhook payload was provided.
我确实通过更改handleStripeWebhook控制器解决了这个错误
async function handleStripeWebhook(req, res) {
const sig = req.headers['stripe-signature'];
const rawBody = req.rawBody;
let event;
try {
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
if (!webhookSecret) {
console.log("STRIPE_WEBHOOK_SECRET is not set");
throw new Error('STRIPE_WEBHOOK_SECRET is not set');
}
// Construct the event using the raw body and signature
event = stripe.webhooks.constructEvent(rawBody, sig, webhookSecret);
console.log('✅ Webhook signature verified');
} catch (err) {
console.error('⚠️ Webhook signature verification failed.', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
console.log('✅ Checkout session completed event received');
console.log('Session metadata:', session.metadata);
// Process the backend logic
await processBackendLogic(session.metadata);
}
res.json({ received: true });
}
并确保 /webhook 路由使用原始格式
app.use(express.json({
verify: (req, res, buf) => {
if (req.originalUrl.startsWith('/api/webhook')) {
req.rawBody = buf.toString();
}
},
}));
而不是使用
app.use(express.json())