/ship-pipeline:stripe-billingfrom ship-pipeline
Implement or review Stripe subscription billing in a Next.js App Router app — Checkout Sessions, customer portal, signed and idempotent webhook handler, plan changes and proration, trials, and dunning. Use when asked to "add subscriptions", "add a paywall", "review our billing code", or when a user "paid but is still on free", or a webhook, proration, or trial bug is reported.
Ships in ship-pipeline. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Stripe is the system of record for prices, plans, and trials. The app's own database is the source of truth for access, and only the webhook handler writes to it. Never grant access from the Checkout success redirect: the classic bug is "I paid but I'm still on free" because the app trusted the redirect instead of waiting for the webhook.
Covers subscriptions. One-off payments and Elements forms are out of scope unless the product also sells subscriptions.
Data model first. Minimum Prisma shape:
model Customer {
id String @id @default(cuid())
userId String @unique
stripeCustomerId String @unique
user User @relation(fields: [userId], references: [id])
}
model Subscription {
id String @id @default(cuid())
customerId String
stripeSubscriptionId String @unique
status String // mirrors Stripe's status enum verbatim
priceId String
currentPeriodEnd DateTime
cancelAtPeriodEnd Boolean @default(false)
updatedAt DateTime @updatedAt
customer Customer @relation(fields: [customerId], references: [id])
}
Store Stripe's status string as-is: incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid, paused. Do not invent a parallel enum.
On API version 2025-03-31.basil or later, current_period_end is no longer on the Subscription; read it from subscription.items.data[i].current_period_end. Pin the API version in the Stripe client so a dashboard upgrade cannot silently turn it into undefined.
Checkout Session route (app/api/billing/checkout/route.ts): mode: 'subscription', client_reference_id = internal user id, and subscription_data.metadata.userId so subscription events can find the user without a second lookup. Reuse the stored stripeCustomerId as customer when one exists, so each user has one Stripe customer.
Customer portal route (app/api/billing/portal/route.ts): read stripeCustomerId from the database for the signed-in user; never accept it from the client. Configure allowed actions (switch plan, cancel, update card) in the Dashboard portal settings.
Webhook handler (app/api/webhooks/stripe/route.ts), in this order:
req.text(), not req.json():
const sig = req.headers.get('stripe-signature')!;
const rawBody = await req.text();
const event = stripe.webhooks.constructEvent(rawBody, sig, process.env.STRIPE_WEBHOOK_SECRET!);
On the Edge runtime use await stripe.webhooks.constructEventAsync(...). Return 400 if verification throws.stripe.subscriptions.retrieve(id) now, before opening the database transaction. Stripe does not guarantee event order, so write the subscription's current state rather than applying each event's payload as a delta. Keep the network call out of the transaction: a Prisma 7 interactive transaction times out after 5 seconds by default (timeout in Prisma's transaction options), and in any version a slow Stripe call holds the transaction and its row locks open.event.id into a WebhookEvent table with a unique constraint, then apply the state change. If the insert hits the unique constraint, return 200 and stop. Recording the id outside the transaction loses events: a failed write marks the event as seen, and Stripe's retry is skipped.200 only after commit; return 5xx on any failure so Stripe retries.checkout.session.completed, customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, invoice.paid, invoice.payment_failed.Plan changes and proration. Call stripe.subscriptions.update on the existing subscription item with the new price. proration_behavior: 'create_prorations' (the default) adds prorations to the next invoice; 'always_invoice' bills them now; 'none' skips them. Let Stripe compute proration.
Trials. Set subscription_data.trial_period_days on the Checkout Session, or trial_end on the subscription. Handle customer.subscription.trial_will_end (sent three days before the trial ends) to trigger a reminder.
Dunning. Turn on Smart Retries in the Dashboard. The app shows past_due (banner, soft-lock) and then whatever final state the Dashboard setting chooses after retries fail (canceled, unpaid, or still past_due). Do not build a custom retry scheduler.
stripe listen --forward-to localhost:3000/api/webhooks/stripe running; its whsec_ secret set as STRIPE_WEBHOOK_SECRETstripe trigger checkout.session.completed creates the subscription rowstripe trigger customer.subscription.updated updates status and pricestripe trigger invoice.payment_failed shows the past-due statestripe events resend <id> on an already-processed event writes nothing newtrial_will_end then invoice.paid or invoice.payment_failed arrive and the row matches StripecancelAtPeriodEnd becomes true and access lasts until currentPeriodEndsubscription.current_period_end on a basil-or-later API version.updated overwrites a newer state.metadata on the Checkout Session, where subscription events cannot see it.stripe listen prints.Which events are handled (and which are deliberately not), the idempotency mechanism, and the CLI output showing each handled event landing in the database (row before/after). For a review, flag every place that trusts client-supplied Stripe IDs or writes subscription state outside the webhook handler.
STRIPE_WEBHOOK_SECRET for the environment under test: stop; do not fake signature verification.sk_live_) in a test run: stop immediately; real money is at risk.What SKILL.md sets; muted values are Claude Code's defaults
16 skills in this plugin
/analytics-instrumentationPostHog event taxonomy and instrumentation review - object_verb naming, flat property schemas, identify/reset/group calls, PII exclusion, LLM usage events, a starter dashboard set (activation, retention, feature funnel), and a per-feature checklist. Use when instrumenting a new feature, auditing existing PostHog events, or setting up analytics for a new product, e.g. "add tracking", "what events should we fire", "review our PostHog events", "is there PII in analytics"./api-designREST conventions for Next.js App Router route handlers — resource naming, versioning, cursor pagination, one error envelope, Zod request/response validation, status-code rules, OpenAPI generated from Zod, and response scrubbing (no secrets, hashes, or other users' data). Use when asked to "design an API route", "add a new endpoint", "review this route handler", "fix our error responses", or "generate API docs"./backup-verifyConfirm database backups exist AND actually restore, by enumerating Neon branch snapshots / Supabase scheduled backups / pg_dump artifacts, restoring into a scratch branch, running smoke queries, and recording timestamped evidence. Use before any risky migration or production mutation, and on a monthly cadence regardless.npx claudepluginhub stylusnexus/agent-plugins --plugin ship-pipeline