我在SvelteKit应用程序中有一个端点,处理来自Stripe的Webhook请求。每个请求都进行了签名,以便可以验证其来自Stripe。
我用于验证事件是否来自Stripe的代码大致如下:
import Stripe from "stripe";
const WEBHOOK_SECRET = process.env["STRIPE_WH_SECRET"];
const stripe = new Stripe(process.env["STRIPE_SECRET"], {
apiVersion: "2020-08-27",
});
export async function post({ headers, body }) {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
headers["stripe-signature"],
WEBHOOK_SECRET
);
} catch (err) {
return {
status: 400,
body: err,
};
}
// Do stuff with the event
}
但是当它从Stripe接收到事件时,我会得到这个错误:
No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
经过一些研究,我发现在调用 该函数 将请求体解析成JSON之前,甚至在调用 SvelteKit钩子函数 之前,就已经完成了解析。这意味着无法直接获取原始请求体,因此我的最佳选择是尝试重构原始请求体。
event = stripe.webhooks.constructEvent(
JSON.stringify(body),
headers["stripe-signature"],
WH_SECRET
);
我不是完全确定为什么会出现问题,因为在深入研究Stripe库中相关代码时,它似乎可以很好地处理字符串。我最好的猜测是某个地方的编码出了问题。
如果能提供任何帮助,将不胜感激,因为我真的希望避免放弃SvelteKit,毕竟我已经基本完成了项目(回想起来并不是一个好主意)。
WEBHOOK_SECRET
错误,它会给你同样的错误提示。 - Madacol