404错误:未找到Nextjs stripe-webhook api端点

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

在听 stripe 时,我一直收到 [404] POST http://localhost:3000/api/stripe-webhook。 我的 stripe-webhook.ts 文件位于路径“app/api/stripe-webhook.ts”

我正在使用 NextJs 版本“14.1.3”。

stripe-webhook.ts 代码如下:-

import { NextApiRequest, NextApiResponse } from "next";
import { buffer } from "micro";
import Stripe from "stripe";
import prisma from "@ /libs/prismadb";

export const config = {
  api: {
    bodyParser: false,
  },
};

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
  apiVersion: "2023-10-16",
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  console.log("accessed handler");
  const buf = await buffer(req);
  const sig = req.headers["stripe-signature"];

  if (!sig) {
    return res.status(400).send("Missing stripe signature");
  }

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(
      buf,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err: any) {
    return res.status(400).send("Webhook error" + err);
  }

  switch (event.type) {
    case "charge.succeeded":
      const charge: any = event.data.object as Stripe.Charge;
      if (typeof charge.payment_intent === "string") {
        console.log("hello");
        await prisma?.order.update({
          where: {
            paymentIntentId: charge.payment_intent,
          },
          data: {
            status: "completed",
            address: charge.shipping?.address,
          },
        });
      }
      break;
    default:
      console.log("Unhandled event type: " + event.type);
  }

  res.json({
    recieved: true,
  });
}

有人可以告诉我我哪里做错了吗

我还尝试将 stripe-webhook.ts 文件的路径更改为新路径,即“pages/api/stripe-webhook.ts”,但仍然出现相同的错误。

reactjs node.js next.js stripe-payments
1个回答
0
投票

当您使用应用程序路由器时,您应该遵循以下文档:https://nextjs.org/docs/app/building-your-application/routing/route-handlers

您的文件名应该类似于“app/api/stripe-webhook/route.ts”

您需要重构您的方法以遵循“应用程序路由器”创建 api 的方式。您将页面路由器语法与应用程序路由器语法混合在一起。

查看应用程序路由器文档,您将准确了解如何创建它。

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