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:
Arnaud
2026-07-23 13:37:14 +02:00
parent 8d5787e56e
commit f871f4f588
30 changed files with 6880 additions and 116 deletions
+35 -1
View File
@@ -16,12 +16,21 @@ const FIELDS = [
{ key: "maxPublicRecipes", label: "Max Public Recipes" },
] as const;
const STRIPE_FIELDS = [
{ key: "stripeProductId", label: "Stripe Product ID", placeholder: "prod_..." },
{ key: "stripePriceIdMonthly", label: "Monthly Price ID", placeholder: "price_..." },
{ key: "stripePriceIdYearly", label: "Yearly Price ID", placeholder: "price_... (optional)" },
] as const;
type TierDefinition = {
tier: string;
maxRecipes: number;
aiCallsPerMonth: number;
storageMb: number;
maxPublicRecipes: number;
stripeProductId: string | null;
stripePriceIdMonthly: string | null;
stripePriceIdYearly: string | null;
};
export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinition }) {
@@ -31,6 +40,11 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
storageMb: tierDefinition.storageMb,
maxPublicRecipes: tierDefinition.maxPublicRecipes,
});
const [stripeValues, setStripeValues] = useState<Record<string, string>>({
stripeProductId: tierDefinition.stripeProductId ?? "",
stripePriceIdMonthly: tierDefinition.stripePriceIdMonthly ?? "",
stripePriceIdYearly: tierDefinition.stripePriceIdYearly ?? "",
});
// Remembers the last finite value per field so toggling "Unlimited" off restores it.
const [lastFinite, setLastFinite] = useState<Record<string, number>>({
maxRecipes: tierDefinition.maxRecipes === UNLIMITED ? 0 : tierDefinition.maxRecipes,
@@ -46,7 +60,7 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
const res = await fetch(`/api/v1/admin/tiers/${tierDefinition.tier}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
body: JSON.stringify({ ...values, ...stripeValues }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
@@ -106,6 +120,26 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
})}
</div>
{tierDefinition.tier !== "free" && (
<div className="space-y-3 border-t pt-4">
<p className="text-xs font-medium text-muted-foreground">Stripe (maps a checkout Price back to this tier)</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{STRIPE_FIELDS.map(({ key, label, placeholder }) => (
<div key={key} className="space-y-1.5">
<Label htmlFor={`${tierDefinition.tier}-${key}`} className="text-xs">{label}</Label>
<Input
id={`${tierDefinition.tier}-${key}`}
value={stripeValues[key] ?? ""}
placeholder={placeholder}
onChange={(e) => setStripeValues((prev) => ({ ...prev, [key]: e.target.value }))}
className="font-mono text-sm"
/>
</div>
))}
</div>
</div>
)}
<Button onClick={() => { void handleSave(); }} disabled={saving} size="sm">
{saving ? "Saving…" : "Save"}
</Button>
@@ -0,0 +1,85 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
type Tier = "free" | "pro" | "family";
type PlanCard = {
tier: Tier;
name: string;
monthlyPrice: string;
yearlyPrice: string | null;
features: string[];
purchasable: boolean;
};
export function BillingPlanCards({ currentTier, plans }: { currentTier: Tier; plans: PlanCard[] }) {
const [checkingOut, setCheckingOut] = useState<Tier | null>(null);
async function checkout(tier: "pro" | "family") {
setCheckingOut(tier);
try {
const res = await fetch("/api/v1/billing/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tier, interval: "month" }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error((data as { error?: string }).error ?? "Checkout failed");
}
const { url } = (await res.json()) as { url: string };
window.location.assign(url);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Checkout failed");
setCheckingOut(null);
}
}
return (
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{plans.map((plan) => {
const isCurrent = plan.tier === currentTier;
return (
<Card key={plan.tier} className={cn(isCurrent && "border-primary")}>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{plan.name}</CardTitle>
{isCurrent && <Badge>Current plan</Badge>}
</div>
<p className="text-2xl font-bold">{plan.monthlyPrice}</p>
</CardHeader>
<CardContent className="space-y-3">
<ul className="space-y-1.5 text-sm">
{plan.features.map((f) => (
<li key={f} className="flex items-start gap-2">
<Check className="h-4 w-4 text-primary shrink-0 mt-0.5" />
<span>{f}</span>
</li>
))}
</ul>
{!isCurrent && plan.purchasable && plan.tier !== "free" && (
<Button
className="w-full"
disabled={checkingOut !== null}
onClick={() => { void checkout(plan.tier as "pro" | "family"); }}
>
{checkingOut === plan.tier ? "Redirecting…" : `Switch to ${plan.name}`}
</Button>
)}
{!isCurrent && !plan.purchasable && plan.tier !== "free" && (
<p className="text-xs text-muted-foreground">Not available yet pricing not configured.</p>
)}
</CardContent>
</Card>
);
})}
</div>
);
}
@@ -0,0 +1,28 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
export function ManageBillingButton() {
const [loading, setLoading] = useState(false);
async function openPortal() {
setLoading(true);
try {
const res = await fetch("/api/v1/billing/portal", { method: "POST" });
if (!res.ok) throw new Error();
const { url } = (await res.json()) as { url: string };
window.location.assign(url);
} catch {
toast.error("Couldn't open the billing portal");
setLoading(false);
}
}
return (
<Button variant="outline" disabled={loading} onClick={() => { void openPortal(); }}>
{loading ? "Opening…" : "Manage billing"}
</Button>
);
}
@@ -3,12 +3,13 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal } from "lucide-react";
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal, CreditCard } from "lucide-react";
import { cn } from "@/lib/utils";
const NAV_ITEMS = [
{ href: "/settings", key: "profile", icon: User, exact: true },
{ href: "/settings/security", key: "security", icon: Shield, exact: false },
{ href: "/settings/billing", key: "billing", icon: CreditCard, exact: false },
{ href: "/settings/ai", key: "aiModels", icon: Bot, exact: false },
{ href: "/settings/notifications", key: "notifications", icon: Bell, exact: false },
{ href: "/settings/features", key: "features", icon: SlidersHorizontal, exact: false },