我直接联系了Stripe,他们建议“应该是一个或另一个,而不是两个。”
因此,如果您有Webhook签名设置,那么您应该将签名身份验证从
if/else
阻塞,从而使
如果/否则
没用,所以也把它去掉。
以下是更新版本:
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = require('stripe')('API_KEY_GOES_HERE');
app.post("/webhook", async (req, res) => {
// Check if webhook signing is configured.
const webhookSecret = {{'STRIPE_WEBHOOK_SECRET'}}
// Retrieve the event by verifying the signature using the raw body and secret.
let event;
let signature = req.headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
webhookSecret
);
} catch (err) {
console.log(`â ï¸ Webhook signature verification failed.`);
return res.sendStatus(400);
}
// Extract the object from the event.
let data = event.data;
let eventType = event.type;
switch (eventType) {
case 'checkout.session.completed':
// Payment is successful and the subscription is created.
// You should provision the subscription and save the customer ID to your database.
break;
case 'invoice.paid':
// Continue to provision the subscription as payments continue to be made.
// Store the status in your database and check when a user accesses your service.
// This approach helps you avoid hitting rate limits.
break;
case 'invoice.payment_failed':
// The payment failed or the customer does not have a valid payment method.
// The subscription becomes past_due. Notify your customer and send them to the
// customer portal to update their payment information.
break;
default:
// Unhandled event type
}
res.sendStatus(200);
});