我的 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这个功能 https://github.com/sveltejs/kit/blob/ad09981723b6daa536e68967583aa3a2e1554709/packages/kit/src/core/http/get_body/index.js#L4甚至之前SvelteKit 挂钩 https://kit.svelte.dev/docs#hooks被调用,这意味着没有办法直接获取原始主体,所以我决定最好的选择是尝试重建原始主体:
event = stripe.webhooks.constructEvent(
JSON.stringify(body),
headers["stripe-signature"],
WH_SECRET
);
我不太确定why这不起作用,因为在挖掘之后Stripe库中的相关代码 https://github.com/stripe/stripe-node/blob/master/lib/Webhooks.js,它似乎可以很好地处理字符串。我最好的猜测是,在某些时候编码会变得混乱。
对此的任何帮助将不胜感激,因为我真的很想避免放弃 SvelteKit,因为我实际上已经用它完成了我的项目(回想起来,这不是一个好主意)。