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:
@@ -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