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>
This commit is contained in:
@@ -27,6 +27,9 @@ const ALLOWED_KEYS: SiteSettingKey[] = [
|
||||
"GITEA_REPO",
|
||||
"GITEA_WEBHOOK_SECRET",
|
||||
"USDA_API_KEY",
|
||||
"STRIPE_SECRET_KEY",
|
||||
"STRIPE_PUBLISHABLE_KEY",
|
||||
"STRIPE_WEBHOOK_SECRET",
|
||||
];
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
|
||||
@@ -11,6 +11,9 @@ interface RouteContext {
|
||||
const NUMERIC_FIELDS = ["maxRecipes", "aiCallsPerMonth", "storageMb", "maxPublicRecipes"] as const;
|
||||
type NumericField = (typeof NUMERIC_FIELDS)[number];
|
||||
|
||||
const STRIPE_FIELDS = ["stripeProductId", "stripePriceIdMonthly", "stripePriceIdYearly"] as const;
|
||||
type StripeField = (typeof STRIPE_FIELDS)[number];
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
@@ -20,8 +23,8 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = (await req.json()) as Partial<Record<NumericField, number>>;
|
||||
const updateData: Partial<Record<NumericField, number>> = {};
|
||||
const body = (await req.json()) as Partial<Record<NumericField, number>> & Partial<Record<StripeField, string | null>>;
|
||||
const updateData: Partial<Record<NumericField, number>> & Partial<Record<StripeField, string | null>> = {};
|
||||
|
||||
for (const field of NUMERIC_FIELDS) {
|
||||
const value = body[field];
|
||||
@@ -32,6 +35,15 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
updateData[field] = value;
|
||||
}
|
||||
|
||||
for (const field of STRIPE_FIELDS) {
|
||||
const value = body[field];
|
||||
if (value === undefined) continue;
|
||||
if (value !== null && typeof value !== "string") {
|
||||
return NextResponse.json({ error: `Invalid value for ${field}` }, { status: 400 });
|
||||
}
|
||||
updateData[field] = value?.trim() || null;
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(tierDefinitions)
|
||||
.set(updateData)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
|
||||
export async function POST() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const limited = await applyRateLimit(`rl:billing:portal:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const stripe = await getStripeClient();
|
||||
if (!stripe) {
|
||||
return NextResponse.json({ error: "Billing is not configured" }, { status: 400 });
|
||||
}
|
||||
|
||||
const [dbUser] = await db.select({ stripeCustomerId: users.stripeCustomerId }).from(users).where(eq(users.id, session!.user.id)).limit(1);
|
||||
if (!dbUser?.stripeCustomerId) {
|
||||
return NextResponse.json({ error: "No billing account yet — subscribe first" }, { status: 400 });
|
||||
}
|
||||
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: dbUser.stripeCustomerId,
|
||||
return_url: `${baseUrl}/settings/billing`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: portalSession.url });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const [dbUser] = await db
|
||||
.select({
|
||||
tier: users.tier,
|
||||
subscriptionStatus: users.subscriptionStatus,
|
||||
currentPeriodEnd: users.currentPeriodEnd,
|
||||
stripeCustomerId: users.stripeCustomerId,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, session!.user.id))
|
||||
.limit(1);
|
||||
|
||||
return NextResponse.json({
|
||||
tier: dbUser?.tier ?? "free",
|
||||
subscriptionStatus: dbUser?.subscriptionStatus ?? null,
|
||||
currentPeriodEnd: dbUser?.currentPeriodEnd?.toISOString() ?? null,
|
||||
hasStripeCustomer: !!dbUser?.stripeCustomerId,
|
||||
});
|
||||
}
|
||||
@@ -1,117 +1,171 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { db, users, processedStripeEvents, eq } from "@epicure/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import type Stripe from "stripe";
|
||||
import { db, users, tierDefinitions, processedStripeEvents, auditLogs, eq, or } from "@epicure/db";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
import { getSiteSetting } from "@/lib/site-settings";
|
||||
|
||||
// Stripe webhook handler — verifies stripe-signature header using HMAC-SHA256.
|
||||
// Handles:
|
||||
// - checkout.session.completed → upgrade user to pro
|
||||
// - customer.subscription.deleted → downgrade user to free
|
||||
type SubscriptionStatus = "active" | "trialing" | "past_due" | "canceled" | "incomplete";
|
||||
|
||||
const STRIPE_TOLERANCE_SECONDS = 300; // 5 minutes
|
||||
|
||||
function verifyStripeSignature(
|
||||
rawBody: string,
|
||||
sigHeader: string,
|
||||
secret: string
|
||||
): { valid: boolean; payload: string | null } {
|
||||
// sigHeader format: "t=<timestamp>,v1=<hmac>[,v1=<hmac>...]"
|
||||
const parts = sigHeader.split(",");
|
||||
const tPart = parts.find((p) => p.startsWith("t="));
|
||||
const v1Parts = parts.filter((p) => p.startsWith("v1="));
|
||||
|
||||
if (!tPart || v1Parts.length === 0) {
|
||||
return { valid: false, payload: null };
|
||||
}
|
||||
|
||||
const timestamp = tPart.slice(2);
|
||||
const tsNum = parseInt(timestamp, 10);
|
||||
if (isNaN(tsNum)) return { valid: false, payload: null };
|
||||
|
||||
// Reject stale webhooks
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
if (Math.abs(nowSec - tsNum) > STRIPE_TOLERANCE_SECONDS) {
|
||||
return { valid: false, payload: null };
|
||||
}
|
||||
|
||||
const signedPayload = `${timestamp}.${rawBody}`;
|
||||
const expected = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(signedPayload, "utf8")
|
||||
.digest();
|
||||
|
||||
const matched = v1Parts.some((v1Part) => {
|
||||
const provided = v1Part.slice(3); // strip "v1="
|
||||
let providedBuf: Buffer;
|
||||
try {
|
||||
providedBuf = Buffer.from(provided, "hex");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (providedBuf.length !== expected.length) return false;
|
||||
return crypto.timingSafeEqual(expected, providedBuf);
|
||||
async function resolveTierFromPriceId(priceId: string | null | undefined): Promise<"pro" | "family" | null> {
|
||||
if (!priceId) return null;
|
||||
const row = await db.query.tierDefinitions.findFirst({
|
||||
where: or(eq(tierDefinitions.stripePriceIdMonthly, priceId), eq(tierDefinitions.stripePriceIdYearly, priceId)),
|
||||
});
|
||||
return row?.tier === "pro" || row?.tier === "family" ? row.tier : null;
|
||||
}
|
||||
|
||||
return { valid: matched, payload: matched ? rawBody : null };
|
||||
function mapStripeStatus(status: Stripe.Subscription.Status): SubscriptionStatus {
|
||||
switch (status) {
|
||||
case "trialing": return "trialing";
|
||||
case "past_due": return "past_due";
|
||||
case "canceled":
|
||||
case "unpaid": return "canceled";
|
||||
case "incomplete":
|
||||
case "incomplete_expired": return "incomplete";
|
||||
default: return "active";
|
||||
}
|
||||
}
|
||||
|
||||
// The billing-period fields moved from the Subscription object onto its
|
||||
// items in a 2025 Stripe API revision — read the item first, fall back to
|
||||
// the top-level field for older API versions. Verify against whichever
|
||||
// API version the configured account is actually pinned to before
|
||||
// switching on real (non-test) keys, per the plan's Stripe-CLI test note.
|
||||
function currentPeriodEnd(subscription: Stripe.Subscription): Date | null {
|
||||
const itemPeriodEnd = subscription.items.data[0]?.current_period_end;
|
||||
const legacyPeriodEnd = (subscription as unknown as { current_period_end?: number }).current_period_end;
|
||||
const unix = itemPeriodEnd ?? legacyPeriodEnd;
|
||||
return unix ? new Date(unix * 1000) : null;
|
||||
}
|
||||
|
||||
async function logBillingEvent(userId: string, action: string, metadata: unknown): Promise<void> {
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
action: `billing.${action}`,
|
||||
targetType: "user",
|
||||
targetId: userId,
|
||||
metadata: JSON.stringify(metadata),
|
||||
createdAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
async function findUserByCustomerId(customerId: string) {
|
||||
const [user] = await db.select({ id: users.id, subscriptionStatus: users.subscriptionStatus }).from(users).where(eq(users.stripeCustomerId, customerId));
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.text();
|
||||
const sig = req.headers.get("stripe-signature");
|
||||
const webhookSecret = process.env["STRIPE_WEBHOOK_SECRET"];
|
||||
|
||||
if (!sig || !webhookSecret) {
|
||||
const stripe = await getStripeClient();
|
||||
const webhookSecret = await getSiteSetting("STRIPE_WEBHOOK_SECRET");
|
||||
if (!stripe || !webhookSecret) {
|
||||
return NextResponse.json({ error: "Stripe not configured" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { valid } = verifyStripeSignature(body, sig, webhookSecret);
|
||||
if (!valid) {
|
||||
const rawBody = await req.text();
|
||||
const signature = req.headers.get("stripe-signature");
|
||||
if (!signature) {
|
||||
return NextResponse.json({ error: "Missing signature" }, { status: 400 });
|
||||
}
|
||||
|
||||
let event: Stripe.Event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
|
||||
}
|
||||
|
||||
let event: { id: string; type: string; data: { object: Record<string, unknown> } };
|
||||
try {
|
||||
event = JSON.parse(body) as typeof event;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!event.id) {
|
||||
return NextResponse.json({ error: "Missing event id" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Dedup: Stripe may redeliver the same event within its retry/tolerance
|
||||
// window. Record the event id before processing; if it's already been
|
||||
// recorded, skip processing (but still ack with 200 so Stripe stops
|
||||
// retrying).
|
||||
// Dedup: Stripe may redeliver the same event within its retry window.
|
||||
const [inserted] = await db
|
||||
.insert(processedStripeEvents)
|
||||
.values({ id: event.id, type: event.type })
|
||||
.onConflictDoNothing()
|
||||
.returning({ id: processedStripeEvents.id });
|
||||
|
||||
if (!inserted) {
|
||||
return NextResponse.json({ received: true, duplicate: true });
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed": {
|
||||
// client_reference_id is set to our internal userId when the Checkout Session is created.
|
||||
const userId = event.data.object["client_reference_id"];
|
||||
const customerId = event.data.object["customer"];
|
||||
if (typeof userId === "string" && typeof customerId === "string") {
|
||||
await db.update(users).set({ tier: "pro", stripeCustomerId: customerId }).where(eq(users.id, userId));
|
||||
}
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
const userId = session.client_reference_id ?? (session.metadata?.["userId"] ?? null);
|
||||
const customerId = typeof session.customer === "string" ? session.customer : session.customer?.id;
|
||||
const subscriptionId = typeof session.subscription === "string" ? session.subscription : session.subscription?.id;
|
||||
if (!userId || !customerId || !subscriptionId) break;
|
||||
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const tier = await resolveTierFromPriceId(subscription.items.data[0]?.price.id);
|
||||
if (!tier) break;
|
||||
|
||||
await db.update(users).set({
|
||||
tier,
|
||||
stripeCustomerId: customerId,
|
||||
stripeSubscriptionId: subscriptionId,
|
||||
subscriptionStatus: mapStripeStatus(subscription.status),
|
||||
currentPeriodEnd: currentPeriodEnd(subscription),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(users.id, userId));
|
||||
await logBillingEvent(userId, "checkout_completed", { tier, subscriptionId });
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.subscription.updated": {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const customerId = typeof subscription.customer === "string" ? subscription.customer : subscription.customer.id;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
const tier = await resolveTierFromPriceId(subscription.items.data[0]?.price.id);
|
||||
await db.update(users).set({
|
||||
...(tier ? { tier } : {}),
|
||||
subscriptionStatus: mapStripeStatus(subscription.status),
|
||||
currentPeriodEnd: currentPeriodEnd(subscription),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "subscription_updated", { tier, status: subscription.status });
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.subscription.deleted": {
|
||||
const customerId = event.data.object["customer"];
|
||||
if (typeof customerId === "string") {
|
||||
await db.update(users).set({ tier: "free" }).where(eq(users.stripeCustomerId, customerId));
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const customerId = typeof subscription.customer === "string" ? subscription.customer : subscription.customer.id;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
await db.update(users).set({ tier: "free", subscriptionStatus: "canceled", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "subscription_deleted", {});
|
||||
break;
|
||||
}
|
||||
|
||||
case "invoice.payment_failed": {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const customerId = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
|
||||
if (!customerId) break;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
// Deliberately does NOT downgrade tier — Stripe retries the card
|
||||
// automatically, recovering via invoice.paid or eventually giving up
|
||||
// via customer.subscription.deleted.
|
||||
await db.update(users).set({ subscriptionStatus: "past_due", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "payment_failed", {});
|
||||
break;
|
||||
}
|
||||
|
||||
case "invoice.paid": {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const customerId = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
|
||||
if (!customerId) break;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (user?.subscriptionStatus === "past_due") {
|
||||
await db.update(users).set({ subscriptionStatus: "active", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "payment_recovered", {});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// ignore unhandled event types
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user