56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { stripeClient } from "../../../../lib/stripeClient";
|
|
import { prisma } from "../../../../lib/prisma";
|
|
|
|
export const runtime = "nodejs";
|
|
|
|
export async function POST(req: Request) {
|
|
const webhookSecret = process.env.STRIPE_CHECKOUT_WEBHOOK_SECRET;
|
|
if (!webhookSecret) {
|
|
return NextResponse.json(
|
|
{ error: "Missing STRIPE_CHECKOUT_WEBHOOK_SECRET." },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
const signature = req.headers.get("stripe-signature");
|
|
if (!signature) {
|
|
return NextResponse.json({ error: "Missing Stripe signature." }, { status: 400 });
|
|
}
|
|
|
|
const rawBody = Buffer.from(await req.arrayBuffer());
|
|
|
|
try {
|
|
const event = stripeClient.webhooks.constructEvent(
|
|
rawBody,
|
|
signature,
|
|
webhookSecret
|
|
);
|
|
|
|
if (event.type === "checkout.session.completed") {
|
|
const session = event.data.object as any;
|
|
const checkoutId = session.id as string;
|
|
|
|
const order = await prisma.order.findUnique({
|
|
where: { stripeCheckoutSessionId: checkoutId },
|
|
});
|
|
|
|
if (order) {
|
|
await prisma.order.update({
|
|
where: { id: order.id },
|
|
data: {
|
|
status: "paid",
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ received: true });
|
|
} catch (err: any) {
|
|
return NextResponse.json(
|
|
{ error: err?.message || "Webhook handler failed." },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
}
|