在 Next.js 中从 Stripe Webhook 向后端发送元数据时收到“Status 401”错误

问题描述 投票:0回答:1

我正在使用 Stripe 开发 Next.js 应用程序来进行支付处理,并且我的 Stripe webhook 实现遇到了问题。具体来说,我正在处理

checkout.session.completed
事件来处理结帐会话并将元数据转发到我的后端。此设置在我的本地环境中完美运行,但是当部署到云时,我在将带有元数据的 POST 请求发送到后端时收到“状态 401”错误。

这是我的 webhook 函数的相关部分:

import { NextResponse } from "next/server";
import Stripe from "stripe";

const secret = process.env.STRIPE_WEBHOOK_SECRET;
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;

const stripe = new Stripe(stripeSecretKey as string, {
  apiVersion: "2023-08-16",
});

async function handleCheckoutSession(session: any) {
  // Attempting to retrieve the session and send metadata to the backend
}

export async function POST(req: Request) {
  // Code to handle POST request and verify Stripe signature
}

Upon receiving a checkout.session.completed event, I try to retrieve the session and send metadata to my backend using fetch(). However, I'm faced with a Status 401 error, indicating unauthorized access, despite the fact that this error does not occur during local testing.

Here's the error screenshot for reference:
enter image description here

我已经仔细检查了我的环境变量设置和代码结构,但无法查明问题所在。有人可以深入了解可能导致本地和云环境之间存在差异的原因,或者建议解决此

Status 401
错误吗?

我尝试过的:

  1. 验证的环境变量:我仔细检查了所有环境变量(

    STRIPE_WEBHOOK_SECRET
    STRIPE_SECRET_KEY
    )以确保它们在本地和云环境中都正确设置。

  2. 本地与云测试:我确认Webhook和元数据转发在我的本地开发环境中正常运行,并从我的后端收到了成功的响应。

  3. 授权标头:我检查了请求标头,以确保在云环境中发送正确的授权令牌,就像在本地环境中一样。

  4. 错误日志:我检查了 Stripe 和我的云提供商的日志,以查找可能指向

    Status 401
    错误原因的任何其他错误消息或线索。

我的期望:

鉴于 webhook 在本地按预期工作,我预计在云环境中也会出现相同的行为:webhook 将成功接收来自 Stripe 的

checkout.session.completed
事件,检索会话详细信息,并将所需的元数据发送到我的后端,而不会遇到授权问题。
Status 401
错误表明存在身份验证问题,考虑到我的环境变量和跨环境的请求标头的一致性,这令人费解。

next.js stripe-payments cloud webhooks
1个回答
0
投票

我们在与 Stripe 集成时遇到了类似的问题,因此我们专门创建了一个 AI 代理来解决 Stripe API 的问题。也许适合您,这里是链接:https://app.codegpt.co/en/marketplace/agents/agent-285472f6,希望适合您!

© www.soinside.com 2019 - 2024. All rights reserved.