Short answer
Treat everything about money as server-side. Verify every Stripe webhook against the raw body and your signing secret, process each event only once, let the server pick prices from an allow-list, and keep subscription status in a table that only your webhook can write and that RLS uses to gate paid features. Keep secret and restricted keys in server secrets, never in the frontend, and keep test and live keys apart.
Ask an AI about this page:ChatGPTClaude
On this page
Key takeaways
- Nothing the browser says about money counts. Not the price, not the plan, not “payment succeeded”. Only your server and Stripe decide.
- Verify every webhook with the raw body and the endpoint’s signing secret before you act on it.
- Stripe may deliver an event twice and out of order. Record event IDs and re-read the current state from Stripe.
- Keep billing state in a table only your server can write, and let RLS use it to gate paid data.
- Secret and restricted keys stay in server secrets. Use test keys while building, live keys only in production, and prefer restricted keys.
Where Stripe integrations lose money
Stripe itself is well documented and hard to misuse from the Stripe side. The expensive mistakes happen in the glue code around it, the part an AI builder writes for you in one prompt: a function that creates a checkout, a webhook that marks users as paid, and a column somewhere that says plan = 'pro'.
That glue has to answer three questions, and each one has a typical wrong answer:
| Question | Typical wrong answer | Right answer |
|---|---|---|
| How much does this cost? | The price the browser sent | A price ID your server picks from an allow-list |
| Did the customer pay? | The success page loaded | A verified webhook from Stripe |
| Is this user subscribed? | A field the user can edit, or a check in React | A status only your webhook writes, enforced by RLS |
The rest of this guide goes through the flow in order: keys, checkout, webhooks, subscription state, the paywall and the customer portal. The examples use Supabase Edge Functions, because that is where most Lovable, Bolt and Cursor apps run their server code; the rules are the same anywhere.
Which Stripe keys may go where?
Stripe has three kinds of keys you’ll meet, and the prefix tells you which is which:
| Key | Prefix | Where it belongs |
|---|---|---|
| Publishable key | pk_test_… / pk_live_… | Browser code. It can’t charge anyone or read account data. |
| Secret key | sk_test_… / sk_live_… | Server only. Full access to your Stripe account. |
| Restricted key | rk_test_… / rk_live_… | Server only. Only the permissions you gave it. |
Three rules follow from Stripe’s own guidance:
- Never put a secret or restricted key in frontend code, a
VITE_variable or your repository. Stripe’s docs warn that attackers continuously scan public code for keys. In a Supabase app, set it withsupabase secrets set STRIPE_SECRET_KEY=…and read it withDeno.env.getin a function. - Prefer restricted keys. Stripe now recommends restricted keys for most uses because a leaked one can only do what you allowed. Give your functions only what they use, for example writing Checkout Sessions and portal sessions and reading subscriptions, and test those permissions in a sandbox before you create the live key.
- Keep test and live apart. Test keys work only on sandbox data, live keys only on real data, and each mode has its own webhook secret. A live site with test keys takes no real money; a staging site with live keys charges real cards.
If a secret or restricted key ever ended up in the browser, a log or git history, Stripe’s guidance is to rotate it immediately, even if you aren’t sure anyone saw it. Secrets in git history shows how to find and replace one, and API keys in AI-built apps covers every other key in your stack.
Who sets the price?
The server. Here is the version an AI tool sometimes writes when asked for “a checkout for the selected plan”:
import Stripe from "npm:stripe@23";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
Deno.serve(async (req) => {
const { amount, planName } = await req.json(); // set by the browser
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [{
price_data: { currency: "eur", unit_amount: amount, product_data: { name: planName } },
quantity: 1,
}],
success_url: "https://your-app.example/thanks",
});
return Response.json({ url: session.url });
});The amount comes from the request, so anyone can pay one cent for “Pro”. The function also doesn’t know who is paying, so the payment can’t be tied to an account later.
The safe version takes only a plan name, maps it to a Stripe price ID that lives on the server, and attaches the verified user:
import { withSupabase } from "npm:@supabase/server@1";
import Stripe from "npm:stripe@23";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const APP_URL = Deno.env.get("APP_URL")!; // e.g. https://your-app.example
// The browser sends a plan name. Only the server knows which Stripe price it means.
const PRICES = new Map([
["pro", Deno.env.get("STRIPE_PRICE_PRO")],
["team", Deno.env.get("STRIPE_PRICE_TEAM")],
]);
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const body = await req.json().catch(() => null);
const price = PRICES.get(String(body?.plan));
if (!price) return Response.json({ error: "Unknown plan" }, { status: 400 });
const userId = ctx.userClaims!.id;
const { data: billing } = await ctx.supabase
.from("billing_customers")
.select("stripe_customer_id")
.maybeSingle();
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [{ price, quantity: 1 }],
customer: billing?.stripe_customer_id ?? undefined,
client_reference_id: userId,
subscription_data: { metadata: { user_id: userId } },
success_url: `${APP_URL}/billing?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${APP_URL}/pricing`,
});
return Response.json({ url: session.url });
}),
};What makes it safe:
- The price is an ID from server config. A
Maplookup returns nothing for unknown plans, so there is no way to inject an amount. - The user is the verified caller.
withSupabasechecks the token; the user ID goes intoclient_reference_idand the subscription’s metadata, so the webhook can link the subscription to the right account. How to identify the caller in a function is covered in securing Supabase Edge Functions. - The return URLs are fixed. They come from
APP_URL, not from the request, so nobody can send customers to another site after paying.
When your server retries a Stripe call after a network error, pass an idempotencyKey in the request options. Stripe’s docs describe how a retry with the same key returns the first result instead of creating a second object.
Did the customer really pay?
Not because your success page loaded. Stripe’s fulfillment docs are explicit that you can’t rely on the landing page alone: a customer can pay and lose their connection before it loads, and anyone can open /billing?session_id=… in a browser. The reliable signal is a webhook: Stripe calls your server and signs the request.
Why the signature check is not optional
A webhook endpoint is a public URL that has to accept requests without a user token. In Supabase, that means verify_jwt = false for this function:
[functions.stripe-webhook]
verify_jwt = falseWith the platform check off, the only thing standing between your database and a forged “payment succeeded” request is the signature check. This is what it looks like without one:
import { createClient } from "npm:@supabase/supabase-js@2";
const admin = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
Deno.serve(async (req) => {
const event = await req.json(); // nothing proves this came from Stripe
if (event.type === "checkout.session.completed") {
await admin
.from("profiles")
.update({ plan: "pro" })
.eq("id", event.data.object.client_reference_id);
}
return new Response("ok");
});Anyone who finds the URL can make any account “pro” with one hand-written request. The detailed fix page is Stripe webhook without signature check.
A webhook that verifies, deduplicates and re-reads
Here is the safe pattern. It follows Supabase’s own Stripe example (signature check with constructEventAsync and SubtleCryptoProvider, because Deno has no synchronous Node crypto) and adds the two things that example leaves to you: handling events out of order and processing each event once.
import { withSupabase } from "npm:@supabase/server@1";
import Stripe from "npm:stripe@23";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
// Deno has no synchronous Node crypto: verify with the async API and this provider.
const cryptoProvider = Stripe.createSubtleCryptoProvider();
export default {
fetch: withSupabase({ auth: "none" }, async (req, ctx) => {
const signature = req.headers.get("stripe-signature") ?? "";
const body = await req.text(); // the raw body, byte for byte as Stripe sent it
let event: Stripe.Event;
try {
event = await stripe.webhooks.constructEventAsync(
body,
signature,
Deno.env.get("STRIPE_WEBHOOK_SECRET")!,
undefined,
cryptoProvider,
);
} catch {
return new Response("Invalid signature", { status: 400 });
}
switch (event.type) {
case "customer.subscription.created":
case "customer.subscription.updated":
case "customer.subscription.deleted": {
// Events can arrive late or out of order: read the current state from Stripe.
const sub = await stripe.subscriptions.retrieve(event.data.object.id);
const userId = sub.metadata.user_id; // set by our own checkout function
if (!userId) break;
const { error } = await ctx.supabaseAdmin.from("billing_customers").upsert({
user_id: userId,
stripe_customer_id: typeof sub.customer === "string" ? sub.customer : sub.customer.id,
subscription_status: sub.status,
});
if (error) return new Response("Retry later", { status: 500 });
break;
}
case "invoice.paid": {
const invoice = event.data.object;
if (typeof invoice.customer !== "string") break;
// Adds credits once per event id, see the SQL function below.
const { error } = await ctx.supabaseAdmin.rpc("grant_invoice_credits", {
p_event_id: event.id,
p_event_type: event.type,
p_customer: invoice.customer,
p_credits: 100,
});
if (error) return new Response("Retry later", { status: 500 });
break;
}
}
return Response.json({ received: true });
}),
};The details that matter:
req.text(), notreq.json(). Stripe signs the exact bytes it sent. Stripe’s docs warn that any change to the raw body makes verification fail, so read it as text and verify before parsing anything.auth: "none"plus the signature. Supabase’s docs use exactly this combination for external webhooks: the wrapper does no credential check, and your handler verifies the provider’s signature. The library also checks the timestamp in the signature header; Stripe’s default tolerance is five minutes, which stops old, captured requests from being replayed.- Errors return 500. If the database write fails, Stripe sees a non-2xx status and retries; in live mode it keeps trying for up to three days. Returning 200 after a failed write loses the event.
- Only the events you handle. Subscribe the endpoint to these event types only, as Stripe recommends. Each endpoint in each mode has its own
whsec_secret; set the right one asSTRIPE_WEBHOOK_SECRET. - Fast answers. Stripe expects a quick 2xx. Two small database writes are fine; for slow work (e-mails, PDFs), store the event and process it in a queue.
This sketch assumes one subscription per user. If users can hold several, key your table by subscription ID instead.
What if Stripe sends the same event twice?
It will, sometimes. Stripe’s webhook docs say endpoints “might occasionally receive the same event more than once” and that delivery order is not guaranteed. Retries after a timeout make duplicates more likely.
Whether a duplicate hurts depends on what your handler does:
- Writing the current state is safe to repeat. The subscription branch above re-reads the subscription from Stripe and writes its status. Processing it twice, or late, writes the same truth. That’s why it fetches the subscription instead of trusting the snapshot in the event.
- Adding something is not. Granting 100 credits on
invoice.paid, sending a receipt or extending access by a month must happen once. Process it twice and you give away credits.
The fix is to record each event ID and add the credits in the same database transaction, so either both happen or neither does. These are the billing tables; clients can read their own row and nothing else:
create table public.billing_customers (
user_id uuid primary key references auth.users (id) on delete cascade,
stripe_customer_id text unique,
subscription_status text not null default 'none',
credits integer not null default 0
);
alter table public.billing_customers enable row level security;
revoke all on table public.billing_customers from anon, authenticated;
grant select on table public.billing_customers to authenticated;
create policy "Users can read their own billing row"
on public.billing_customers for select
to authenticated
using ((select auth.uid()) = user_id);
create table public.stripe_events (
id text primary key,
type text not null,
processed_at timestamptz not null default now()
);
alter table public.stripe_events enable row level security;
revoke all on table public.stripe_events from anon, authenticated;And this is the function the webhook calls for invoice.paid:
create or replace function public.grant_invoice_credits(
p_event_id text,
p_event_type text,
p_customer text,
p_credits integer
)
returns boolean
language plpgsql
set search_path = ''
as $$
begin
insert into public.stripe_events (id, type)
values (p_event_id, p_event_type)
on conflict (id) do nothing;
if not found then
return false; -- duplicate delivery: already processed
end if;
update public.billing_customers
set credits = credits + p_credits
where stripe_customer_id = p_customer;
if not found then
raise exception 'unknown Stripe customer %', p_customer;
end if;
return true;
end;
$$;
revoke execute on function public.grant_invoice_credits(text, text, text, integer)
from public, anon, authenticated;
grant execute on function public.grant_invoice_credits(text, text, text, integer)
to service_role;How it behaves:
- The primary key on
stripe_events.idmakes the second insert of the same event do nothing, so the function returnsfalseand no credits are added. - If the customer is unknown (for example because the subscription event hasn’t been processed yet), the function raises an error. The whole transaction rolls back, including the event row, the webhook returns 500, and Stripe’s retry can succeed later. Recording the event first and failing afterwards would have lost it.
- The
revokelines keep users from calling the function themselves. Supabase grants new functions inpublictoanonandauthenticatedby default, and without them anyone signed in could hand themselves credits.
Stripe also notes that in some cases it sends two different events for the same change; for those, compare the object ID in data.object and the event type. The single-page version of this fix is non-idempotent Stripe webhook, and the general idea is explained under idempotency.
Can a user make themselves “pro”?
In many AI-built apps, yes, and without touching Stripe at all. The paid status sits in a column the user can write, and the usual “users can update their own profile” policy covers every column:
create table public.profiles (
id uuid primary key references auth.users (id) on delete cascade,
display_name text,
plan text not null default 'free'
);
alter table public.profiles enable row level security;
create policy "Users can read their own profile"
on public.profiles for select
to authenticated
using ((select auth.uid()) = id);
create policy "Users can update their own profile"
on public.profiles for update
to authenticated
using ((select auth.uid()) = id)
with check ((select auth.uid()) = id);The policy is correct about which row: you can only update your own profile. It says nothing about which columns. A signed-in user can send update profiles set plan = 'pro' for their own row through the Data API with the public key, and it succeeds. RLS works on rows; column rights are a separate setting. Remove the general update right and grant it back only for the columns users may change:
revoke update on table public.profiles from anon, authenticated;
grant update (display_name) on table public.profiles to authenticated;After this, updating plan fails with “permission denied for table profiles”, while renaming still works, and only on your own row. The cleaner long-term design is the one above: billing fields in their own table that clients can only read.
The same mistake on insert came up in one of our test apps, a small shop. Its order policy let customers insert any order:
create policy "Customers can place orders"
on public.orders for insert
to authenticated
with check (true);With that policy, a signed-in customer can insert an order with payment_status = 'paid', any total and even another customer’s user_id; the comment in the migration said the payment webhook would set the status later, but nothing stopped the client from setting it first. In our latest benchmark run (3 December 2026), ShipRely’s audit reported this policy as high, naming the client-set payment status, total and owner. When orders are created by your checkout function anyway, the fix is to take client inserts away completely:
drop policy "Customers can place orders" on public.orders;
revoke insert on table public.orders from authenticated;More on this family of bugs: credits, paid status or prices set by the client and RLS policy USING (true).
Put the paywall in the database
Hiding the “Download report” button from free users is good UX. It is not protection: the data behind the button can still be requested directly. See subscription check only in the frontend.
The protection belongs where the data is. With the billing table above, a policy can say “only active or trialing subscribers may read reports”:
create table public.reports (
id bigint generated always as identity primary key,
title text not null,
body text not null
);
alter table public.reports enable row level security;
revoke all on table public.reports from anon;
create policy "Subscribers can read reports"
on public.reports for select
to authenticated
using (
exists (
select 1 from public.billing_customers b
where b.user_id = (select auth.uid())
and b.subscription_status in ('active', 'trialing')
)
);Which statuses count as paid is your decision. Stripe’s subscription docs say trialing and active are safe to provision, that you should ask the customer to update their payment details on past_due, and that you should revoke access on canceled or unpaid. Because the webhook writes the status, a cancellation in the customer portal takes the reports away as soon as the event is processed, without any change to your frontend. Stripe also describes an alternative: store an access expiry date and compare it on each visit.
The same check works in an Edge Function before an expensive action, read with the caller-scoped client so the user can’t swap in someone else’s row. For the many other ways people get around paywalls, see how users bypass paywalls.
Is the customer portal safe?
Stripe’s hosted customer portal lets customers change plans, update cards and cancel, without you building any of it. The security rule from Stripe’s integration guide is short: authenticate the customer on your site before you create a portal session for them. The session URL is short-lived and opens that customer’s billing, so whoever gets it can manage their subscription.
import { withSupabase } from "npm:@supabase/server@1";
import Stripe from "npm:stripe@23";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const APP_URL = Deno.env.get("APP_URL")!;
export default {
fetch: withSupabase({ auth: "user" }, async (_req, ctx) => {
// RLS returns only the caller's own row: the customer id never comes from the request.
const { data: billing } = await ctx.supabase
.from("billing_customers")
.select("stripe_customer_id")
.maybeSingle();
if (!billing?.stripe_customer_id) {
return Response.json({ error: "No billing account yet" }, { status: 404 });
}
const session = await stripe.billingPortal.sessions.create({
customer: billing.stripe_customer_id,
return_url: `${APP_URL}/account`,
});
return Response.json({ url: session.url });
}),
};The mistake to avoid is a portal function that takes customerId from the request body. A customer ID is an identifier, not a secret; with such a function, anyone who learns one can open that customer’s billing. Look it up from the verified user instead, exactly like above.
Changes made in the portal reach your app through the same customer.subscription.updated and customer.subscription.deleted webhooks, so the paywall stays correct without extra code.
A fix prompt for your AI builder
Paste this into Lovable, Cursor, Claude Code or Bolt, and review the changes before you deploy. Test everything with Stripe test keys first.
Review the Stripe integration in this project and fix it so that:
- No Stripe secret or restricted key appears in frontend code, VITE_ variables or the repository. They are read with Deno.env.get in Supabase Edge Functions only.
- The checkout function accepts only a plan name, maps it to a Stripe price ID from server config, verifies the user from the token and sets client_reference_id and subscription_data.metadata.user_id to that verified user ID. It never accepts an amount, price or user ID from the request.
- The webhook function reads the raw body with req.text(), verifies it with stripe.webhooks.constructEventAsync and Stripe.createSubtleCryptoProvider(), and returns 400 on failure. verify_jwt is false only for this function.
- Subscription events re-read the subscription from Stripe and write its status to a billing table. Events that add credits or access record the Stripe event ID in a table with a primary key, in the same transaction, and skip duplicates. Any failed database write returns a 500 so Stripe retries.
- Subscription status, plan and credits are not writable by clients: no update or insert grants or policies for anon or authenticated on those columns. Paid data is protected by RLS policies that check the status.
- The customer portal function looks up the Stripe customer ID from the database for the verified user and never takes it from the request.
Show me every changed file and list any table where a client can still write a plan, status, price or credit column.
Checklist before you take real money
Stripe launch checklist
0/11 done
Your progress is saved in this browser only.
Frequently asked questions
Is the Stripe publishable key a secret?
No. Keys starting with pk_ are made for browser code and can’t create charges or read account data, according to Stripe’s docs. Secret keys (sk_) and restricted keys (rk_) are different: they belong on your server only, for example in Supabase secrets.
Why does my Stripe webhook signature check fail?
Almost always because the body was changed before verification, for example parsed as JSON and turned back into a string, or because the signing secret belongs to a different endpoint or mode. Read the body as raw text, verify it first, and use the whsec_ secret of exactly this endpoint in this mode. On Deno, use constructEventAsync with Stripe’s SubtleCryptoProvider.
Can I check whether a user is subscribed in the frontend?
Only for display. Hiding a button is fine, but the data and actions behind it must be protected on the server: in RLS policies or in the Edge Function that does the work, based on a status your webhook wrote.
Do I need to handle duplicate webhook events?
Yes. Stripe’s docs say an endpoint might receive the same event more than once and that events don’t arrive in a guaranteed order. Writing the current subscription state is safe to repeat; adding credits or sending a receipt is not, so record the event ID and skip events you already processed.
Does ShipRely check my Stripe integration?
Payments is not a live ShipRely audit area. The Security and Database audits cover the database side that payment flows depend on, for example a table or policy that lets a user set their own paid status, plan or credits.
Sources
- 1.Receive Stripe events in your webhook endpoint — Stripe Docs
- 2.Using webhooks with subscriptions — Stripe Docs
- 3.Fulfill orders — Stripe Docs
- 4.API keys — Stripe Docs
- 5.Best practices for managing secret API keys — Stripe Docs
- 6.Integrate the customer portal — Stripe Docs
- 7.Idempotent requests — Stripe API Reference
- 8.Securing Edge Functions — Supabase Docs