-
Notifications
You must be signed in to change notification settings - Fork 220
/
route.ts
71 lines (61 loc) · 1.96 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { headers } from "next/headers"
import Stripe from "stripe"
import { env } from "@/env.mjs"
import { prisma } from "@/lib/db"
import { stripe } from "@/lib/stripe"
export async function POST(req: Request) {
const body = await req.text()
const signature = headers().get("Stripe-Signature") as string
let event: Stripe.Event
try {
event = stripe.webhooks.constructEvent(
body,
signature,
env.STRIPE_WEBHOOK_SECRET
)
} catch (error) {
return new Response(`Webhook Error: ${error.message}`, { status: 400 })
}
const session = event.data.object as Stripe.Checkout.Session
if (event.type === "checkout.session.completed") {
// Retrieve the subscription details from Stripe.
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
)
// Update the user stripe into in our database.
// Since this is the initial subscription, we need to update
// the subscription id and customer id.
await prisma.user.update({
where: {
id: session?.metadata?.userId,
},
data: {
stripeSubscriptionId: subscription.id,
stripeCustomerId: subscription.customer as string,
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
})
}
if (event.type === "invoice.payment_succeeded") {
// Retrieve the subscription details from Stripe.
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string
)
// Update the price id and set the new period end.
await prisma.user.update({
where: {
stripeSubscriptionId: subscription.id,
},
data: {
stripePriceId: subscription.items.data[0].price.id,
stripeCurrentPeriodEnd: new Date(
subscription.current_period_end * 1000
),
},
})
}
return new Response(null, { status: 200 })
}