Where does the price come from?
The first mistake is letting the browser say what to charge. AI tools often write a checkout function like this:
// Don't: the browser chooses the amount
const { amount, name } = await req.json()
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{
price_data: { currency: "usd", unit_amount: amount, product_data: { name } },
quantity: 1,
}],
success_url: "https://example.com/success",
})
Anyone can call that function with amount: 100 and pay one dollar for your annual plan. Stripe accepts it, because price_data exists for "dynamic pricing when the amount isn't known ahead of time" (Stripe API). Stripe's own guidance for the session endpoint is blunt: "Don't forward arbitrary client-supplied Session parameters", and protect it with access controls and limits on repeated creation (accept a payment).
Let the browser send a plan name only, and look up the Price ID on the server:
// Do: the server maps a plan name to a Price ID it trusts
const PRICES: Record<string, string> = {
pro_monthly: Deno.env.get("STRIPE_PRICE_PRO_MONTHLY")!,
}
const { data: { user } } = await supabase.auth.getUser() // caller's token
if (!user) return new Response("Sign in first", { status: 401 })
const { plan } = await req.json()
const price = PRICES[plan]
if (!price) return new Response("Unknown plan", { status: 400 })
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [{ price, quantity: 1 }],
client_reference_id: user.id,
success_url: `${SITE_URL}/billing/done?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${SITE_URL}/pricing`,
})
client_reference_id ties the session to the signed-in user, taken from the verified token rather than the request body.
Is the success page proof that someone paid?
No, in both directions. Stripe says you "can't rely on triggering fulfillment only from your checkout landing page, because it's not guaranteed customers visit that page" (fulfill orders). A customer can pay and lose their connection before it loads. And anyone can open the address without paying, as in the story above.
Stripe's recommended pattern is a single server-side fulfillment function, called from the webhook and, optionally, from the landing page with the session ID. It retrieves the Checkout Session from Stripe, checks payment_status, and records that the session was fulfilled. Our rule of thumb is to also confirm that client_reference_id matches the signed-in user before granting anything on the landing page. The browser never writes the plan itself.
Does your webhook check Stripe's signature?
The webhook is where access should be granted, which makes it the endpoint to lock. This is the version to look for and remove:
// Don't: anyone who finds the URL can post this
const event = await req.json()
if (event.type === "checkout.session.completed") {
await grantPro(event.data.object.client_reference_id)
}
Stripe signs every event in the Stripe-Signature header and asks you to verify it with the raw body, warning that "any manipulation to the raw body of the request causes the verification to fail" (webhooks). In a Supabase Edge Function, which runs on Deno, that means req.text() and the async verifier, as in Supabase's own example (Supabase example):
const cryptoProvider = Stripe.createSubtleCryptoProvider()
const signature = req.headers.get("Stripe-Signature")
const body = await req.text() // raw body, before any JSON parsing
let event
try {
event = await stripe.webhooks.constructEventAsync(
body, signature!, Deno.env.get("STRIPE_WEBHOOK_SIGNING_SECRET")!,
undefined, cryptoProvider,
)
} catch (err) {
return new Response("Bad signature", { status: 400 })
}
That example is deployed with JWT verification turned off, because Stripe cannot send a Supabase sign-in token. The signature check is then the only lock on the function. In a Next.js route handler, Stripe's example passes await req.text() to stripe.webhooks.constructEvent and returns 400 on failure (stripe-node example).
Keep the libraries' default five-minute timestamp tolerance; Stripe says a tolerance of 0 "disables the recency check entirely".
What happens when Stripe sends the same event twice?
It will, sooner or later. Stripe says endpoints "might occasionally receive the same event more than once", retries failed deliveries for up to three days in live mode, and does not guarantee event order (webhooks). Its fulfillment guide adds that your function "might be called multiple times, possibly concurrently, for the same Checkout Session".
If a duplicate adds 100 credits twice, that is a free top-up. Record each event ID with a unique key and skip ones you have seen:
create table public.stripe_events (
id text primary key,
type text not null,
received_at timestamptz not null default now()
);
alter table public.stripe_events enable row level security;
-- no policies: only the webhook, using the secret key, writes here
const { error } = await admin
.from("stripe_events")
.insert({ id: event.id, type: event.type })
if (error?.code === "23505") return new Response("Already handled", { status: 200 })
Better still, make the grant itself idempotent: upsert the subscription by its Stripe ID, or store fulfilled session IDs under a unique constraint. Return a 2xx quickly; Stripe counts a timeout as a failed delivery and tries again.
Who can write the plan column?
A perfect webhook does not help if the user can set plan = 'pro' themselves. If entitlements sit in a profiles row with an "update your own row" policy, read can a user make themselves admin? and move them out of the user's reach. Write subscription state only from the webhook, using a secret key that stays on the server.
That key belongs nowhere near the browser. Stripe: "Only publishable keys are safe to expose outside your application's back end" (API keys). Search your live app's scripts for sk_live_, sk_test_ and rk_; if one turns up, follow what to do when a key is exposed. Lovable, for one, stores the key as a backend secret named STRIPE_SECRET_KEY, and its docs say to ask it to set up webhooks if you need them for fulfillment (Lovable docs). For anything that grants access, you do.
The checklist
| Check | Bad sign | Good sign |
|---|---|---|
| Price | Amount or price_data built from the request | Price ID looked up on the server |
| Session endpoint | Works signed out, no limits | Requires sign-in, limits repeat calls |
| Success page | Writes the plan from the browser | Server retrieves the session, or only shows status |
| Webhook signature | req.json() then act | Raw body plus constructEvent or constructEventAsync |
| Duplicates | Credits added per delivery | Event or session ID stored under a unique key |
| Secret key | sk_ or rk_ in browser scripts | Only pk_ in the browser |
| Plan column | User can update it | Only the server writes it |
Test it on your own app in Stripe test mode
Run these against your own endpoint, in test mode or on staging.
- Unsigned request. Send a fake event with no signature:
curl -i -X POST https://YOUR-PROJECT.supabase.co/functions/v1/stripe-webhook \
-H "Content-Type: application/json" \
-d '{"id":"evt_fake","type":"checkout.session.completed","data":{"object":{"id":"cs_fake"}}}'
Expect a 400 and no change in your database. A 200 is the thing to fix today.
- Signed events. Forward real test events with the Stripe CLI:
stripe listen --events checkout.session.completed --forward-to localhost:54321/functions/v1/stripe-webhook, thenstripe trigger checkout.session.completed. Expect a 200. - Duplicates. Open a delivered test event in the Dashboard and click Resend (it works for 15 days after the event). Expect one grant, not two.
- Success URL. Signed in as a free test account, open your success address directly with a made-up session ID. Expect no upgrade.
- Price. In the developer tools, copy your checkout request with Copy as fetch, change the plan or amount, and run it. Expect a 400, or Stripe's page showing your real price.