**const express = require("express");
**const app = express();
app.set("port", process.env.PORT);
app.post(
"/webhook",
express.raw({ type: "application/json" }),
(request, response) => {
const sig = request.headers["stripe-signature"];
// console.log('endpointSecret', process.env.END_POINT_SECRET)
// console.log('sig', sig)
console.log("request.body", request.body);
let event;
try {
event = stripe.webhooks.constructEvent(
request.body,
sig,
process.env.END_POINT_SECRET
);
} catch (err) {
console.log(`Webhook Error: ${err.message}`);
return response.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the event
let resData = "";
switch (event.type) {
case "payment_intent.succeeded":
const paymentIntent = event.data.object;
resData = `PaymentIntent for ${paymentIntent.amount} was successful!`;
break;
case "payment_method.attached":
resData = event.data.object;
// Then define and call a method to handle the successful attachment of a PaymentMethod.
// handlePaymentMethodAttached(paymentMethod);
break;
case "customer.created":
resData = event.data.object;
break;
case "customer.deleted":
resData = event.data.object;
break;
case "customer.updated":
resData = event.data.object;
break;
case "customer.subscription.created":
resData = event.data.object;
break;
case "customer.subscription.trial_will_end":
resData = event.data.object;
break;
case "payment_intent.succeeded":
resData = event.data.object;
break;
case "customer.subscription.deleted":
resData = event.data.object;
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
console.log(resData);
return response.status(200).send(resData);
}
);
// Start server
app.listen(app.get("port"), () => {
console.log("Server listening on : ", app.get("port"));
});
我尝试在成功创建订阅时触发事件,但在传递缓冲区数据时出现主体数据错误,然后出现如下错误:- 未找到与有效负载的预期签名匹配的签名。您是否正在传递从 Stripe 收到的原始请求正文?当我传递 json 数据时,会出现错误,例如 ebhook 负载必须以字符串或 Buffer (https://nodejs.org/api/buffer.html) 实例的形式提供,表示 raw 请求正文。提供了 Payload作为解析的 JavaScript 对象。 如果无法访问原始签名材料,则无法进行签名验证。
process.env.END_POINT_SECRET 密钥中存在问题。
已经解决了。