【问题标题】:Verifying Stripe webhook in SvelteKit endpoint: how to get the raw body of a RequestEvent?在 SvelteKit 端点中验证 Stripe webhook:如何获取 RequestEvent 的原始正文?
【发布时间】:2022-02-08 21:58:55
【问题描述】:

类似于this question,使用更新版本的 SvelteKit。

上下文:SvelteKit PR #3384 开始将标准 Request 对象传递给端点并删除 rawBody

上面链接的问题对于如何使用rawBody 调用Stripe 的constructEvent 来验证传入webhook 请求的签名有一个很好的答案,但是现在未修改的主体不再暴露(据我所知)告诉),我想知道如何更新我的 webhook 处理程序。

我尝试调用constructEvent,结果为request.text()request.json()request.arrayBuffer()(转换为字符串)、request.blob().text(),以及普通的request.body 转换为字符串,但没有他们工作。它总是抛出同样的错误:

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

【问题讨论】:

  • 查看Request API,您应该可以使用来自SvelteKit RequestEventrequest.bodyhere 有一个例子。
  • request.body: ReadableStreamstripe.webhooks.constructEvent 的第一个参数的类型不匹配,即string | Buffer。我尝试将流连接成一个字符串和一个缓冲区,两者都导致了与问题中相同的错误

标签: stripe-payments sveltekit


【解决方案1】:

所以我查看了 node-fetch 源代码,因为这是 svelte-kit 用来填充开发服务器以及所有不支持 Fetch 的环境的方法,并且有一种方法是标准的 Request类没有,那是Request.buffer()。使用这种方法,我能够解决该问题。这仅适用于不支持原生获取的节点或无服务器环境(几乎所有环境,除了 cloudflare)。

export async function post({ request }: RequestEvent) {
    try {
        const body = await request.buffer();
        const sig = request.headers.get('stripe-signature') as string;
        const e = stripe.webhooks.constructEvent(body, sig, secret);
        console.log(e.type);
    } catch (_e) {
        console.error(_e);
    }
}

结果:

charge.succeeded
payment_intent.succeeded
payment_intent.created

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2021-01-14
    • 2021-09-18
    • 2022-12-21
    • 2019-08-14
    • 2019-06-18
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多