获取对SvelteKit端点的请求的原始正文 [英] Getting the raw body of a request to a SvelteKit endpoint
问题描述
我的SvelteKit应用程序中有一个端点,它处理来自Strip的WebHook请求。每个请求都经过签名,以便可以验证其是否来自条纹。
我必须验证事件是否来自条纹的代码如下所示:
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
}
但当它接收到来自条纹的事件时,我收到以下错误:
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
调研后发现,Body在调用SvelteKit hooks之前就被this function解析成JSON,这意味着无法直接获取原始Body,所以我觉得最好的选择就是尝试重构原始Body:
event = stripe.webhooks.constructEvent(
JSON.stringify(body),
headers["stripe-signature"],
WH_SECRET
);
我不完全确定为什么这不起作用,因为在the relevant code in the Stripe library中搜索之后,它似乎可以很好地处理字符串。我最好的猜测是,在某个时候编码会被搞乱。
这方面的任何帮助都将不胜感激,因为我真的希望避免转而使用SvelteKit,因为我实际上已经用它完成了我的项目(回想起来,这不是一个好主意)。
推荐答案
stripe.webhooks.constructEvent(payload, signature, secret)
接受的负载类型必须为string | Buffer
,但SvelteKit请求中接收的rawBody类型为Uint8Array
。
将Uint8Array rawBody或JSON.stringify‘d rawBody作为有效负载传递会导致下面来自Strip的错误。参考:https://github.com/stripe/stripe-node#webhook-signing
错误
message: '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'
我们需要在不更改内容的情况下将rawBody转换为string
或Buffer
。为此,我们可以使用:Buffer.from(rawBody)
。
因此您的终结点应该类似于:
...
const stripeWebhookSecret = process.env['STRIPE_WEBHOOK_SECRET'];
export const post: RequestHandler = async (request) => {
const rawBody = Buffer.from(request.rawBody);
const signature = request.headers['stripe-signature'];
try {
event = stripe.webhooks.constructEvent(
rawBody,
signature,
stripeWebhookSecret
);
...
这篇关于获取对SvelteKit端点的请求的原始正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!