Files
Epicure/apps/web/app/api/v1/billing/checkout/route.ts
T
Arnaud f871f4f588 feat: real Stripe billing -- Checkout, Customer Portal, admin billing dashboard (v0.73.0)
Implements plans/STRIPE_PLAN.md sections 1-9 for solo Pro/Family
billing (family multi-user sharing, section 1a, deliberately deferred
-- flagged in that plan as the most novel/error-prone piece).

Decisions locked in: cancel/downgrade at period end (Stripe Portal
default), no trial period.

- lib/stripe.ts: single client factory reading STRIPE_SECRET_KEY via
  site-settings (DB overrides env, same pattern as every other
  provider key in this codebase).
- Webhook route rewritten on the real `stripe` SDK
  (stripe.webhooks.constructEvent replaces the hand-rolled HMAC
  verifier) and now handles the full event set: checkout.session.completed,
  customer.subscription.{updated,deleted}, invoice.{payment_failed,paid}.
  past_due deliberately never downgrades tier on its own -- Stripe
  retries the card first, recovering via invoice.paid or eventually
  giving up via subscription.deleted. Every handler audit-logs under
  billing.<event>. Dedup via the existing processed_stripe_events
  table, unchanged.
- Schema: tierDefinitions gained stripe{ProductId,PriceIdMonthly,
  PriceIdYearly} (the lookup table mapping a Price back to a tier on
  checkout); users gained stripeSubscriptionId/subscriptionStatus/
  currentPeriodEnd.
- New POST /api/v1/billing/checkout (creates a subscription Checkout
  Session, allow_promotion_codes: true), POST /api/v1/billing/portal
  (Stripe's hosted self-serve cancel/upgrade/card-update), GET
  /api/v1/billing/status.
- /settings/billing: current plan + renewal date, past_due warning,
  usage-vs-limits (reuses the existing UsageQuotaSection), plan
  comparison cards with per-tier Checkout buttons, manage-billing
  button once a Stripe customer exists.
- /admin/billing: connection status (test/live mode detection),
  subscriber counts, past-due list, recent billing audit events, link
  to Stripe Dashboard. Tier Limits page extended with the three Stripe
  price fields per tier (own render branch, not the numeric+Unlimited-
  switch machinery the existing fields use).

Before going live: an admin needs to create real Products/Prices in
Stripe, enter the IDs on Tier Limits, and configure the Stripe-side
webhook endpoint -- all operational steps the plan always called for,
none of it code.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 13:37:14 +02:00

58 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, users, tierDefinitions, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getStripeClient } from "@/lib/stripe";
const Schema = z.object({
tier: z.enum(["pro", "family"]),
interval: z.enum(["month", "year"]),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const limited = await applyRateLimit(`rl:billing:checkout:${session!.user.id}`, 10, 60);
if (limited) return limited;
const parsed = Schema.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const stripe = await getStripeClient();
if (!stripe) {
return NextResponse.json({ error: "Billing is not configured" }, { status: 400 });
}
const tierDef = await db.query.tierDefinitions.findFirst({ where: eq(tierDefinitions.tier, parsed.data.tier) });
const priceId = parsed.data.interval === "year" ? tierDef?.stripePriceIdYearly : tierDef?.stripePriceIdMonthly;
if (!priceId) {
return NextResponse.json({ error: `No ${parsed.data.interval}ly price configured for ${parsed.data.tier}` }, { status: 400 });
}
const [dbUser] = await db.select({ stripeCustomerId: users.stripeCustomerId, email: users.email }).from(users).where(eq(users.id, session!.user.id)).limit(1);
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
customer: dbUser?.stripeCustomerId ?? undefined,
customer_email: dbUser?.stripeCustomerId ? undefined : dbUser?.email,
client_reference_id: session!.user.id,
metadata: { userId: session!.user.id },
line_items: [{ price: priceId, quantity: 1 }],
allow_promotion_codes: true,
success_url: `${baseUrl}/settings/billing?checkout=success`,
cancel_url: `${baseUrl}/settings/billing?checkout=canceled`,
});
if (!checkoutSession.url) {
return NextResponse.json({ error: "Failed to create checkout session" }, { status: 500 });
}
return NextResponse.json({ url: checkoutSession.url });
}