Reputation: 23
I have been getting [404] POST http://localhost:3000/api/stripe-webhook when listening on stripe. My stripe-webhook.ts file located at path 'app/api/stripe-webhook.ts'
I am using NextJs version "14.1.3".
stripe-webhook.ts code is given below:-
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,
});
}
Can someone tell me where i might be doing wrong
I also tried changing path of stripe-webhook.ts file to a new path i.e 'pages/api/stripe-webhook.ts' but still having the same error.
Upvotes: 0
Views: 361
Reputation: 943
As you're using App router, you should follow this docs instead: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Your file name should be something like 'app/api/stripe-webhook/route.ts'
You need to refactor your method to follow 'app router' way of creating apis. You're mixing pages router syntax with app router syntax. The handlers method is specific for page router.
Take a look on app router documentation that you're gonna to understand exactly how you need to create it.
Upvotes: 0