# Stripe Payments on Vercel + Supabase, Done Safely (free AI agent kit from Bot Pantry)

Canonical page: https://botpantry.com/kits/stripe-supabase-billing
Free download (.zip, no sign-up): https://botpantry.com/api/download?kit=stripe-supabase-billing
For: Vibe coders adding payments to a Next.js + Supabase app
Setup time: 60-120 min (verified by Kit Inspector)
Works with: Cursor; Claude Code; v0; Stripe; Supabase; Vercel; Next.js; Node.js 20+
Published: 2026-11-18

Tested drop-in code, SQL and checks for taking subscriptions and credit-pack payments with Stripe in a Next.js + Supabase app: verified webhooks, no double-granting, users who can't edit their own billing rows, and a test-mode-first path to going live.

## What's inside
- Next.js route templates for the Stripe webhook, Checkout and customer portal, with the signature check, duplicate and out-of-order handling already done
- A Supabase migration for subscriptions and credits with Row Level Security, plus a read-only self-check that flags each unsafe change
- A webhook self-test script that sends six fakes and one real-style signed event to your endpoint
- An env checker that catches live keys in dev, secrets in NEXT_PUBLIC_ variables, mixed test/live keys and committed .env files
- Cursor and Claude Code rules that stop your AI from trusting browser prices or granting access on the success page
- Test-mode-first and go-live checklists

---

The kit's README (included in the .zip) follows.

# Stripe Payments on Vercel + Supabase, Done Safely — Bot Pantry Kit

Add Stripe subscriptions and one-time credit packs to a Next.js + Supabase app without the payment holes AI tools often write: unverified webhooks, prices taken from the browser, access granted on the success page, credits granted twice, and users who can edit their own billing rows.

You get working route templates, a Supabase migration, two scripts that test your setup, rules for your AI tool, and checklists. It all runs in Stripe **test mode** until you choose to go live.

## Contents
| File | What it's for |
|---|---|
| `app/api/stripe/webhook/route.ts` | Stripe webhook: signature check on the raw body, then duplicate-safe, order-safe updates |
| `app/api/stripe/checkout/route.ts` | Starts Checkout from a plan **key**. The price, mode and user come from the server |
| `app/api/stripe/portal/route.ts` | Opens Stripe's customer portal (change card, cancel) for the signed-in user only |
| `lib/billing/*.ts` | `plans.ts` (your prices), `webhook.ts` (the webhook logic), `checkout.ts`, `db.ts`, `entitlements.ts`, Stripe and Supabase clients |
| `supabase/billing.sql` | Tables, RLS, grants and server-only functions. Users can read their own billing rows and nothing else |
| `supabase/billing-selfcheck.sql` | Read-only check you paste into the SQL Editor. Every line should say PASS |
| `scripts/webhook-selftest.mjs` | Sends 6 fake and 1 correctly signed request to your webhook URL and checks the answers |
| `scripts/check-stripe-env.mjs` | Checks your `.env` files for live keys in dev, secrets in `NEXT_PUBLIC_` variables, mixed test/live keys, wrong IDs and committed env files. It never prints a value |
| `rules/stripe-billing.mdc` | Cursor rule (save as `.cursor/rules/stripe-billing.mdc`) |
| `rules/billing-rules.md` | The same rules for Claude Code (`.claude/rules/billing.md`) or to paste into `AGENTS.md` |
| `env.example.txt` | Every variable name, where to find it, and which ones are secret |
| `checklists/use-test-mode.md`, `checklists/go-live.md` | What to click and check before and when you take real money |
| `setup/01-04` | Step-by-step setup: Supabase, Stripe, local testing, Vercel |
| `examples.md` | Buttons, a billing page, spending credits, subscriber-only tables, what duplicate events look like, a prompt for your AI |
| `troubleshooting.md` | Symptom -> cause -> fix |
| `sources.md` | The official docs every rule is based on |

## What you need
- A **Next.js App Router** app (TypeScript) that uses **Supabase Auth**, deployed or deployable on **Vercel**. The kit was tested on Next.js 16.4.6.
- A Stripe account you can use in a sandbox (test mode), and the Stripe CLI for local testing. You create and log in to these yourself.
- Node.js 20+ (stripe-node 23 requires it). The two scripts have no dependencies and also run on Node 18.
- Using Lovable, Bolt or another Vite + Supabase Edge Functions setup? The SQL, self-check, scripts, rules and checklists still apply. The route templates are Next.js-only (see Limits).

## Setup (60–120 minutes the first time, all in test mode)
1. **Supabase** (`setup/01-supabase.md`): run `billing.sql`, then `billing-selfcheck.sql`. All PASS.
2. **Stripe** (`setup/02-stripe.md`): in a sandbox, add a recurring price and, optionally, a one-time price. Copy the keys and Price IDs, turn on the customer portal, and install the CLI.
3. **Code + local test** (`setup/03-test-locally.md`): copy `app/api/stripe/`, `lib/billing/` and `scripts/`, then `npm install stripe @supabase/supabase-js @supabase/ssr server-only`. Fill in `.env.local`, then run `check-stripe-env.mjs` and `webhook-selftest.mjs` (7 PASS; a local `whsec_` is enough — `stripe listen` is only needed for live test events), and a test purchase with card `4242 4242 4242 4242`.
4. **Vercel** (`setup/04-deploy-vercel.md`): add the env vars and a webhook endpoint in Stripe. Check for Deployment Protection and auth redirects, then self-test the deployed URL.
5. Save the rules file for your AI tool. Then go through `checklists/use-test-mode.md`.

Going live is a separate step with its own checklist (`checklists/go-live.md`). It isn't part of the setup time.

## How it works
```
Browser ── {plan:"pro_monthly"} ──> /api/stripe/checkout ── verified user + server price ──> Stripe Checkout
                                                                                                   │ pays
Stripe ── signed event ──> /api/stripe/webhook
   1 verify signature on raw body (400 if bad)        4 fetch LATEST subscription/session from Stripe
   2 ignore other event types (200)                   5 write with upserts / billing_grant_credits (once per session)
   3 skip events already finished (200)               6 mark finished (200); any error -> 500 so Stripe retries
Your pages ── getBillingState() / RLS is_subscriber() ──> Supabase (users read only their own rows)
```
Why fetch from Stripe instead of trusting the event? Stripe says events can arrive late, twice, or out of order, and that `created` can't order them. Fetching the current object makes the newest state win every time. Credits are keyed by the Checkout Session ID, so a payment counts once, whichever event or retry delivers it. The paid line item must also be exactly that plan's price, quantity 1.

## Guardrails
- **Only the webhook grants anything.** The success page shows "processing" until the database says otherwise (`examples.md`, Example 2).
- **The browser sends a plan key, nothing else.** Prices, credit amounts and redirect URLs come from `plans.ts` and `NEXT_PUBLIC_SITE_URL`, never from the request body or Host header.
- **Users can't write billing data.** Grants and RLS give `authenticated` read-only access to its own rows, and `anon` gets nothing. The functions are `security invoker`, so even a wrongly granted `execute` still hits the table grants.
- **Secrets stay server-side.** `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` and `SUPABASE_SECRET_KEY` are never `NEXT_PUBLIC_`. `getStripe()` and the admin client import `server-only`.
- **Fail closed.** No webhook secret means a 500 for every event. A DB or Stripe error means a 500 and a retry. An unknown plan, price mismatch or missing user means nothing is granted.
- **Test mode first.** The env checker fails on live keys unless you run it with `--mode live` on a production file. The AI rules forbid live keys, real charges and Dashboard changes without asking you.
- Nothing in this kit deploys, charges, or contacts Stripe or Supabase for you. You run every command.

## Limits (read before relying on it)
- **Next.js App Router only** for the route templates (tested on Next.js 16.4.6, Node runtime). Pages Router, Remix, Express or Supabase Edge Functions need their own port of `route.ts`. `lib/billing/webhook.ts` is framework-free and can be reused.
- **Snapshot events only.** Stripe now recommends *thin* events for new integrations. This kit verifies snapshot events with `constructEvent` and then fetches the latest object anyway, which gives the same "latest state" result. Choose **Snapshot** when you create the endpoint. Thin events aren't handled.
- **One price per plan, quantity 1, one subscription item.** It doesn't handle multi-item subscriptions, metered billing, seats, quantities, coupons that change the price ID, or proration logic. `price_id` and `current_period_end` come from the first item.
- **Who's subscribed:** only `trialing` and `active` unlock access. `past_due` locks immediately. If you want a grace period, add `past_due` to `is_subscriber()` and `getBillingState()` and decide how long.
- **Not handled:** refunds and disputes (credits aren't clawed back), invoice events (`invoice.paid`, `invoice.payment_failed` emails), trial-ending reminders, taxes, Stripe Connect, and Stripe's own Entitlements feature.
- **Two deliveries at the same moment** for the same subscription both fetch from Stripe. In a very narrow race the older fetch could be written last. The next event for that subscription corrects it. Credits have no such race, because the database unique key decides.
- **Users who already have a subscription** get a 409 from the checkout route. Only `trialing`/`active` count, so a `past_due` user can start a second subscription. Send them to the portal instead.
- **The self-check is positive-proof:** PASS only for the kit's exact grants and policies. Any policy or view it can't prove safe is CHECK, not PASS or FAIL, so read those yourself. It checks only the kit's own tables, not the rest of your database. For that, see Bot Pantry's prelaunch-security kit.
- **The self-test proves the signature gate only.** Its "valid signature" check sends a test event twice, once as compact JSON and once indented (how Stripe's docs show a printed event body), so a handler that rebuilds the body in either layout fails. It doesn't reproduce Stripe's exact bytes. It can't see what your handler does with real events. It also needs the same `whsec_` your server uses.
- **The env checker reads env files** (`.env`, `.env.development`, `.env.local`, `.env.development.local`, or `--file`), by name and prefix. It reports the value that wins, the way Next.js loads them. It doesn't scan source code for pasted keys (use a secret scanner) and can't see Vercel's settings unless you `vercel env pull` them.
- **Not tested against real Stripe or real Supabase.** See below for what was mocked.

## Tested
Everything ran on the Bot Pantry build box on 2026-11-18 with **fake keys only**: no Stripe or Supabase account, no network calls to either.

- **End-to-end, 62 checks, 0 failures.** The kit's routes were copied unchanged into a Next.js 16.4.6 app, built with `next build` (TypeScript strict) and run with `next start`. They used the real stripe-node 23.1.0 and supabase-js 2.119 / @supabase/ssr 0.12.7, talking to a real PostgREST 16.6 in front of real Postgres 17 with `billing.sql` and Supabase-style roles. Only Stripe's API and Supabase Auth's `/user` endpoint were local mocks. Results:
  - **Signatures:** `webhook-selftest.mjs` gave 7/7 PASS against the route, also under `next dev`. With no webhook secret, the route answered 500 and the self-test exited 1. A correctly signed body that was re-serialized got 400. A forged event got 400 with nothing written. Two `v1` signatures during a secret roll got 200.
  - **Subscriptions:** an event saying `active` while Stripe said `past_due` stored `past_due`. A duplicate got 200 `duplicate` with no second fetch. A late `created` event didn't roll the status back. `deleted` stored `canceled`. A sub with no user id stayed unlinked. A Stripe outage gave 500 then a successful retry, and one or two transient errors were retried by stripe-node itself.
  - **Credits:** a paid session gave +100. The same session again, via `async_payment_succeeded`, plus 10 simultaneous copies, stayed at 100. Unpaid stayed 0 until async success. A payload claiming "paid" while the API said "unpaid" gave nothing. Unknown plan, wrong price, quantity 5 and a missing user id each granted nothing. A DB outage gave 500 then a retry that granted once.
  - **Checkout and portal:** no session gave 401, and a forged session cookie gave 401. A fake price, amount, user id, `success_url` and forwarded host in the request never reached Stripe. The server price, Bob's verified id and an idempotency key did. `__proto__`, `constructor`, `toString`, numbers and null as the plan gave 400. An already-subscribed user got 409. The portal used the caller's own customer and the configured return URL.
  - **Browser key via the REST API:** Alice saw exactly her own subscription rows and Bob saw none of hers. Anon was denied. PATCHing her balance, inserting a fake `active` subscription, calling `billing_grant_credits` and reading `stripe_events` were all denied (401/403). `is_subscriber` returned true for her.
  - **Examples 2 and 3** (`examples.md`) compiled and ran. With 3 credits, 8 simultaneous spend requests gave exactly 3 successes and a balance of 0. The billing page showed "Free" plus the processing note after `?checkout=success`.
- **SQL, 37 checks, 0 failures.** On both "old default grants" and "new explicit grants" project setups, `billing-selfcheck.sql` gave 30/30 PASS. That held after running `billing.sql` twice, with an unrelated app table added, and with a subscriber-only table. Behavior blocks ran in both setups: own-rows-only reads, 20 denied anon/user operations, claim/finish semantics, atomic spending, and which of 8 statuses unlock access. 20 parallel grants for one session credited once. 20 parallel spends of 10 from 100 gave 10 successes and a balance of 0. **21 broken setups** were each flagged with only their own line: 15 FAIL (RLS off, user or anon grants, functions callable by users/anon/PUBLIC, a plain view readable by the browser, missing table/function/server grants) and 6 CHECK (extra or changed policies, a policy on a server-only table, a security-invoker view, a view not granted to browser roles, `security definer`). 4 planted holes made the behavior test itself fail, which proves it can't pass silently.
- **`webhook-selftest.mjs` against 15 handlers** built on stripe-node, each judged correctly. 3 correct handlers PASS (raw text, raw Buffer, parse only after verifying). 12 broken or misconfigured ones FAIL with the matching hint: no verification, verifying a compact `JSON.stringify(req.json())` rebuild, verifying a pretty `JSON.stringify(parsed, null, 2)` rebuild, skipping the check when the header is missing, catching the error and carrying on, tolerance 0, a fallback default secret, a login redirect, Deployment Protection 401, a 500 on a bad signature, a missing webhook secret (the kit route's 500, with a hint that agrees — not "return 400"), and the CLI-vs-Dashboard secret mix-up.
- **`check-stripe-env.mjs`, 26 fixture projects.** It gave the expected verdict on each and printed no key value in any of them.

Not verified here: a real Stripe sandbox (Checkout pages, real event payloads, `stripe listen`/`trigger`, the customer portal, Dashboard menu names, restricted-key permission names), a real Supabase project (its SQL Editor, the `sb_secret_`/`sb_publishable_` gateway keys, asymmetric JWT signing), Vercel deployments (env var types, Deployment Protection bypass), and Next.js 15.

## Sources
See `sources.md` (Stripe, Supabase, Next.js, Vercel, Cursor and Claude Code docs, checked 2026-11-18).

---
This kit is free from Bot Pantry: https://botpantry.com/kits/stripe-supabase-billing
Share that link with anyone it would help. New kits added regularly, plus a weekly roundup of the most-downloaded ones: https://botpantry.com/newsletter
