|
| 1 | +import { NextResponse } from "next/server"; |
| 2 | +import invariant from "tiny-invariant"; |
| 3 | +import { WebhookVerificationError, validateEvent } from "@polar-sh/sdk/webhooks"; |
| 4 | + |
| 5 | +import { enablePolarBillingFlag } from "@/lib/feature-flags"; |
| 6 | +import { prisma } from "@/lib/prisma"; |
| 7 | +import { requirePolarWebhookSecret } from "@/lib/billing/polar"; |
| 8 | + |
| 9 | +export const runtime = "nodejs"; |
| 10 | + |
| 11 | +type PolarSubscription = { |
| 12 | + id: string; |
| 13 | + status?: string | null; |
| 14 | + customer_id?: string | null; |
| 15 | + checkout_id?: string | null; |
| 16 | + cancel_at_period_end?: boolean | null; |
| 17 | + current_period_end?: string | null; |
| 18 | + ends_at?: string | null; |
| 19 | + customer?: { |
| 20 | + external_id?: string | null; |
| 21 | + email?: string | null; |
| 22 | + } | null; |
| 23 | + metadata?: Record<string, unknown> | null; |
| 24 | +}; |
| 25 | + |
| 26 | +function parseDate(value: string | null | undefined): Date | null { |
| 27 | + if (!value) return null; |
| 28 | + const date = new Date(value); |
| 29 | + return Number.isNaN(date.getTime()) ? null : date; |
| 30 | +} |
| 31 | + |
| 32 | +function deriveTier(params: { |
| 33 | + eventType: string; |
| 34 | + status: string | null; |
| 35 | + cancelAtPeriodEnd: boolean | null; |
| 36 | +}): "free" | "brand" { |
| 37 | + const normalizedType = params.eventType.toLowerCase(); |
| 38 | + if (normalizedType === "subscription.revoked") return "free"; |
| 39 | + if (normalizedType === "subscription.cancelled") return "free"; |
| 40 | + |
| 41 | + switch (params.status) { |
| 42 | + case "active": |
| 43 | + case "trialing": |
| 44 | + case "past_due": |
| 45 | + return "brand"; |
| 46 | + case "canceled": |
| 47 | + return params.cancelAtPeriodEnd ? "brand" : "free"; |
| 48 | + default: |
| 49 | + return "free"; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +async function resolveUserId(subscription: PolarSubscription): Promise<string | null> { |
| 54 | + const externalId = |
| 55 | + subscription.customer?.external_id ?? |
| 56 | + (typeof subscription.metadata?.user_id === "string" ? subscription.metadata.user_id : null); |
| 57 | + if (externalId) return externalId; |
| 58 | + |
| 59 | + const email = subscription.customer?.email; |
| 60 | + if (!email) return null; |
| 61 | + |
| 62 | + const user = await prisma.user.findFirst({ |
| 63 | + where: { email }, |
| 64 | + select: { id: true }, |
| 65 | + }); |
| 66 | + return user?.id ?? null; |
| 67 | +} |
| 68 | + |
| 69 | +export async function POST(request: Request) { |
| 70 | + const enabled = await enablePolarBillingFlag(); |
| 71 | + if (!enabled) { |
| 72 | + return new NextResponse("Not Found", { status: 404 }); |
| 73 | + } |
| 74 | + |
| 75 | + const body = Buffer.from(await request.arrayBuffer()); |
| 76 | + const headers = Object.fromEntries(request.headers.entries()); |
| 77 | + |
| 78 | + try { |
| 79 | + const secret = requirePolarWebhookSecret(); |
| 80 | + const event = validateEvent(body, headers, secret) as { type: string; data: unknown }; |
| 81 | + |
| 82 | + if (!event?.type) { |
| 83 | + return NextResponse.json({ error: "Invalid webhook payload" }, { status: 400 }); |
| 84 | + } |
| 85 | + |
| 86 | + const eventType = String(event.type); |
| 87 | + if (!eventType.toLowerCase().startsWith("subscription.")) { |
| 88 | + return new NextResponse("", { status: 202 }); |
| 89 | + } |
| 90 | + |
| 91 | + const subscription = event.data as PolarSubscription; |
| 92 | + invariant(subscription?.id, "Subscription payload missing id"); |
| 93 | + |
| 94 | + const userId = await resolveUserId(subscription); |
| 95 | + if (!userId) { |
| 96 | + return NextResponse.json({ error: "Unable to resolve user" }, { status: 422 }); |
| 97 | + } |
| 98 | + |
| 99 | + const status = subscription.status ?? null; |
| 100 | + const cancelAtPeriodEnd = subscription.cancel_at_period_end ?? null; |
| 101 | + const tier = deriveTier({ eventType, status, cancelAtPeriodEnd }); |
| 102 | + |
| 103 | + await prisma.userMetadata.upsert({ |
| 104 | + where: { userId }, |
| 105 | + create: { |
| 106 | + userId, |
| 107 | + subscriptionTier: tier, |
| 108 | + subscriptionStatus: status, |
| 109 | + subscriptionCancelAtPeriodEnd: cancelAtPeriodEnd, |
| 110 | + subscriptionCurrentPeriodEnd: parseDate(subscription.current_period_end), |
| 111 | + subscriptionEndsAt: parseDate(subscription.ends_at), |
| 112 | + polarCustomerId: subscription.customer_id ?? null, |
| 113 | + polarSubscriptionId: subscription.id, |
| 114 | + }, |
| 115 | + update: { |
| 116 | + subscriptionTier: tier, |
| 117 | + subscriptionStatus: status, |
| 118 | + subscriptionCancelAtPeriodEnd: cancelAtPeriodEnd, |
| 119 | + subscriptionCurrentPeriodEnd: parseDate(subscription.current_period_end), |
| 120 | + subscriptionEndsAt: parseDate(subscription.ends_at), |
| 121 | + polarCustomerId: subscription.customer_id ?? null, |
| 122 | + polarSubscriptionId: subscription.id, |
| 123 | + }, |
| 124 | + }); |
| 125 | + |
| 126 | + return new NextResponse("", { status: 202 }); |
| 127 | + } catch (error) { |
| 128 | + if (error instanceof WebhookVerificationError) { |
| 129 | + return new NextResponse("", { status: 403 }); |
| 130 | + } |
| 131 | + |
| 132 | + const message = error instanceof Error ? error.message : "Webhook handler failed"; |
| 133 | + return NextResponse.json({ error: message }, { status: 500 }); |
| 134 | + } |
| 135 | +} |
| 136 | + |
0 commit comments