Created
November 14, 2023 12:29
-
-
Save sojinsamuel/988617fb95d7a26075b6056db6fc2534 to your computer and use it in GitHub Desktop.
Stripe webhook Nextjs api route code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Stripe from "stripe"; | |
import { headers } from "next/headers"; | |
import { NextResponse } from "next/server"; | |
import { db } from "@/db"; | |
export async function POST(req: Request) { | |
const body = await req.text(); | |
const signature = headers().get("Stripe-Signature") as string; | |
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!); | |
let event: Stripe.Event; | |
try { | |
event = stripe.webhooks.constructEvent( | |
body, | |
signature, | |
process.env.STRIPE_WEBHOOK_SECRET! | |
); | |
} catch (error: any) { | |
console.error(error); | |
return new NextResponse(`Webhook Error: ${error.message}`, { status: 400 }); | |
} | |
const session = event.data.object as Stripe.Checkout.Session; | |
const subscription = await stripe.subscriptions.retrieve( | |
session.subscription as string | |
); | |
if (event.type === "charge.succeeded") { | |
console.log("===================================="); | |
console.log("Charge succeeded"); | |
console.log("===================================="); | |
} | |
if (event.type === "checkout.session.completed") { | |
const subscription = await stripe.subscriptions.retrieve( | |
session.subscription as string | |
); | |
await db.user.update({ | |
where: { | |
id: session.client_reference_id as string, | |
}, | |
data: { | |
credits: { | |
increment: 5, | |
}, | |
}, | |
}); | |
} | |
if (event.type === "payment_intent.payment_failed") { | |
console.log("===================================="); | |
console.log("Payment failed"); | |
console.log("===================================="); | |
} | |
if (event.type === "payment_intent.succeeded") { | |
console.log("===================================="); | |
console.log("Payment succeeded"); | |
console.log("===================================="); | |
} | |
if (event.type === "payment_intent.created") { | |
console.log("===================================="); | |
console.log("Payment created"); | |
console.log("===================================="); | |
} | |
if (event.type === "customer.created") { | |
console.log("===================================="); | |
console.log("Customer created"); | |
console.log("===================================="); | |
} | |
if (event.type === "invoice.payment_succeeded") { | |
const subscription = await stripe.subscriptions.retrieve( | |
session.subscription as string | |
); | |
} | |
return new NextResponse(null, { status: 200 }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment