Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | import { NextResponse, type NextRequest } from 'next/server' import type Stripe from 'stripe' import { getStripe, STRIPE_WEBHOOK_SECRET } from '@/lib/stripe' import { eq } from 'drizzle-orm' import { db, schema } from '@/db' import { syncCheckoutSession } from '@/lib/billing-sync' /** * POST /api/billing/webhook * * Stripe webhook handler. Processes subscription lifecycle events * to keep the local subscriptions table in sync. * * This route does NOT use withAuth — Stripe signs the request itself. */ export async function POST(request: NextRequest) { const body = await request.text() const signature = request.headers.get('stripe-signature') if (!signature || !STRIPE_WEBHOOK_SECRET) { return NextResponse.json({ error: 'Missing signature or webhook secret' }, { status: 400 }) } let event: Stripe.Event try { event = getStripe().webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET) } catch (err) { console.error('[stripe webhook] Signature verification failed:', err) return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) } try { switch (event.type) { case 'checkout.session.completed': await handleCheckoutCompleted(event.data.object as Stripe.Checkout.Session) break case 'customer.subscription.updated': await handleSubscriptionUpdated(event.data.object as Stripe.Subscription) break case 'customer.subscription.deleted': await handleSubscriptionDeleted(event.data.object as Stripe.Subscription) break case 'invoice.payment_failed': await handlePaymentFailed(event.data.object as Stripe.Invoice) break default: // Ignore unhandled event types break } } catch (err) { console.error(`[stripe webhook] Error handling ${event.type}:`, err) return NextResponse.json({ error: 'Webhook handler failed' }, { status: 500 }) } return NextResponse.json({ received: true }) } /** * New checkout completed — create or update subscription record. */ async function handleCheckoutCompleted(session: Stripe.Checkout.Session) { await syncCheckoutSession(session.id) } /** * Subscription updated — sync status, plan, period end, cancel flag. */ async function handleSubscriptionUpdated(sub: Stripe.Subscription) { const stripeSubscriptionId = sub.id const existing = await db .select({ id: schema.subscriptions.id }) .from(schema.subscriptions) .where(eq(schema.subscriptions.stripeSubscriptionId, stripeSubscriptionId)) .get() if (!existing) { console.warn(`[stripe webhook] subscription.updated for unknown sub: ${stripeSubscriptionId}`) return } const status = mapStripeStatus(sub.status) await db .update(schema.subscriptions) .set({ status, currentPeriodEnd: sub.items.data[0]?.current_period_end ? new Date(sub.items.data[0].current_period_end * 1000) : new Date(), cancelAtPeriodEnd: sub.cancel_at_period_end, updatedAt: new Date(), }) .where(eq(schema.subscriptions.stripeSubscriptionId, stripeSubscriptionId)) console.log(`[stripe webhook] subscription.updated: sub=${stripeSubscriptionId} status=${status}`) } /** * Subscription deleted — mark as canceled. */ async function handleSubscriptionDeleted(sub: Stripe.Subscription) { await db .update(schema.subscriptions) .set({ status: 'canceled', updatedAt: new Date(), }) .where(eq(schema.subscriptions.stripeSubscriptionId, sub.id)) console.log(`[stripe webhook] subscription.deleted: sub=${sub.id}`) } /** * Payment failed — mark as past_due (7-day grace, don't lock out). */ async function handlePaymentFailed(invoice: Stripe.Invoice) { const subDetails = invoice.parent?.subscription_details if (!subDetails) return const stripeSubscriptionId = typeof subDetails.subscription === 'string' ? subDetails.subscription : subDetails.subscription.id await db .update(schema.subscriptions) .set({ status: 'past_due', updatedAt: new Date(), }) .where(eq(schema.subscriptions.stripeSubscriptionId, stripeSubscriptionId)) console.log(`[stripe webhook] invoice.payment_failed: sub=${stripeSubscriptionId}`) } /** Map Stripe subscription status to our simplified status set. */ function mapStripeStatus(status: string): 'active' | 'past_due' | 'canceled' | 'trialing' { switch (status) { case 'active': return 'active' case 'trialing': return 'trialing' case 'past_due': return 'past_due' case 'canceled': case 'unpaid': case 'incomplete_expired': return 'canceled' default: return 'active' } } |