Add Stripe payments to an AI-built app safely: checkout, webhooks and test mode

Disclaimer: Die Inhalte, die du auf dieser Seite siehst, wurden mit Hilfe von KI übersetzt. Wenn du Feedback zur Übersetzung hast, kontaktiere uns bitte.

Key takeaways:

  1. Create the Checkout Session on the server from a price you control. The browser only says what the customer picked, never how much it costs.

  2. Fulfill orders from a signature-verified webhook (checkout.session.completed and checkout.session.async_payment_succeeded), not from the success redirect alone.

  3. Verify the Stripe-Signature header against the raw request body, and make fulfillment safe to run twice for the same Checkout Session.

  4. Build and test in a Stripe sandbox with test keys and the Stripe CLI, then switch to live keys and the live webhook signing secret.

To add Stripe payments to an app built with Lovable, Bolt, Cursor or Claude Code, keep three things on the server: your secret key, the creation of the Checkout Session, and order fulfillment. The browser only tells your server what the customer wants to buy. A server function (for example a Supabase Edge Function) sets the price, and a signature-verified Stripe webhook decides when an order is paid. This guide shows that setup in TypeScript, how to test it in a Stripe sandbox, and where AI-generated payment code usually goes wrong.

It is written for founders and for the coding agent working on their behalf. Every API detail below comes from Stripe's official documentation as of November 2026. Where Stripe's docs are the better source, we link to them.

What runs in the browser, and what must run on the server?

Most AI-built apps are a React frontend with Supabase behind it. The frontend is public: anyone can read its code and change what it sends. So the split is simple.

Browser (React)Server (Edge Function or serverless function)
Shows prices for display onlyHolds the Stripe secret or restricted key
Sends the chosen plan or product key, for example "pro"Maps that key to a Stripe Price ID and creates the Checkout Session
Redirects the customer to the Checkout URLReceives and verifies webhooks
Shows the order status it reads from your databaseMarks orders as paid, grants access, issues refunds

If your app sends an amount, a price or a "paid: true" flag from the browser, it can be changed by the customer. Stripe says it directly in its Checkout quickstart: keep sensitive product information such as price and availability on your server so customers can't manipulate it.

Checkout Sessions, Payment Links or Payment Intents: which one should you use?

  • Checkout Sessions (Stripe Checkout) is what Stripe recommends for most integrations. You create a session on your server, redirect to a Stripe-hosted page (or embed the form), and Stripe handles card entry, 3D Secure, many payment methods, tax, discounts and subscriptions. Use this when your app needs to know which signed-in user paid. See Stripe's comparison of the two APIs.
  • Payment Links are no-code links to a Stripe payment page. They are fine for selling a few fixed products from a landing page or an email. They use Checkout under the hood, so the same webhook fulfillment rules apply. They are a weaker fit when you must tie a payment to a user account in your app.
  • Payment Intents is the lower-level API. Stripe describes it as requiring significantly more code and maintenance: you calculate the final amount yourself and rebuild discounts, tax and subscriptions. Choose it only if you need to own every part of checkout.

The rest of this guide uses Checkout Sessions with a Stripe-hosted page. It is the shortest path to something safe.

Step 1: Which keys go where?

  • Sandbox keys start with pk_test_, rk_test_ and sk_test_. Live keys start with pk_live_, rk_live_ and sk_live_. Objects created in a sandbox (products, prices, customers) do not exist in live mode.
  • Only the publishable key (pk_) is safe in frontend code. With hosted Checkout you may not need it at all.
  • Stripe now recommends restricted API keys (rk_) over unrestricted secret keys, so a leaked key can do less damage.
  • The webhook signing secret (whsec_) is not an API key. Each endpoint has its own, and the sandbox and live secrets are different.

Store server keys as function secrets, never in a VITE_ variable or anything the frontend bundle can read:

supabase secrets set STRIPE_SECRET_KEY=rk_test_...
supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_...

Step 2: Where do orders live?

Keep your own record of every order. The webhook updates it, and the frontend reads it. With Supabase, row level security lets users read their own orders while only server code can write.

create table public.orders (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id),
  plan text not null,
  stripe_session_id text unique not null,
  status text not null default 'pending', -- pending | paid
  amount_total bigint,
  currency text,
  created_at timestamptz not null default now()
);

alter table public.orders enable row level security;

create policy "read own orders" on public.orders
  for select using (auth.uid() = user_id);
-- No insert/update policies: only server code with the service role key writes here.

Step 3: How do you create the Checkout Session safely?

The browser sends a plan key. The function checks who the user is, looks up the Stripe Price ID on the server, creates the session and stores a pending order.

// supabase/functions/create-checkout-session/index.ts
import Stripe from 'npm:stripe@^23';
import { createClient } from 'npm:@supabase/supabase-js@2';

const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY')!);
const admin = createClient(
  Deno.env.get('SUPABASE_URL')!,
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!, // server only, bypasses RLS
);

// The server decides what each plan costs. The browser never sends an amount.
const PRICE_IDS: Record<string, string> = {
  starter: 'price_...',
  pro: 'price_...',
};

const cors = {
  'Access-Control-Allow-Origin': 'https://yourapp.com',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: cors });

  // Who is asking? Validate the user's Supabase JWT.
  const jwt = req.headers.get('Authorization')?.replace('Bearer ', '') ?? '';
  const { data: { user } } = await admin.auth.getUser(jwt);
  if (!user) return new Response('Unauthorized', { status: 401, headers: cors });

  const { plan } = await req.json();
  const price = PRICE_IDS[plan];
  if (!price) return new Response('Unknown plan', { status: 400, headers: cors });

  const session = await stripe.checkout.sessions.create({
    mode: 'payment', // 'subscription' for recurring prices
    line_items: [{ price, quantity: 1 }],
    client_reference_id: user.id,
    customer_email: user.email,
    metadata: { user_id: user.id, plan },
    success_url: 'https://yourapp.com/thanks?session_id={CHECKOUT_SESSION_ID}',
    cancel_url: 'https://yourapp.com/pricing',
  });

  await admin.from('orders').insert({
    user_id: user.id,
    plan,
    stripe_session_id: session.id,
  });

  return Response.json({ url: session.url }, { headers: cors });
});

In the React app, call it and redirect:

const { data, error } = await supabase.functions.invoke('create-checkout-session', {
  body: { plan: 'pro' },
});
if (!error) window.location.href = data.url;

Note: Supabase now also offers new-style keys (SUPABASE_SECRET_KEYS, SUPABASE_PUBLISHABLE_KEYS) alongside the legacy SUPABASE_SERVICE_ROLE_KEY. Both bypass row level security on the secret side, so either one stays in server code only. See Supabase's secrets docs.

Step 4: How do you receive and verify Stripe webhooks?

Stripe sends events to a public HTTPS URL and signs each one in the Stripe-Signature header. You verify that signature with the raw request body and the endpoint's whsec_ secret. If the body is parsed or changed first, verification fails. On Deno (Supabase Edge Functions), use the async variant with a Web Crypto provider:

// supabase/functions/stripe-webhook/index.ts
import Stripe from 'npm:stripe@^23';
import { createClient } from 'npm:@supabase/supabase-js@2';

const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY')!);
const cryptoProvider = Stripe.createSubtleCryptoProvider();
const admin = createClient(
  Deno.env.get('SUPABASE_URL')!,
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
);

Deno.serve(async (req) => {
  const signature = req.headers.get('Stripe-Signature') ?? '';
  const body = await req.text(); // raw body: do not JSON.parse before verifying

  let event: Stripe.Event;
  try {
    event = await stripe.webhooks.constructEventAsync(
      body,
      signature,
      Deno.env.get('STRIPE_WEBHOOK_SECRET')!,
      undefined,
      cryptoProvider,
    );
  } catch (err) {
    return new Response(`Signature check failed: ${(err as Error).message}`, { status: 400 });
  }

  try {
    switch (event.type) {
      case 'checkout.session.completed':
      case 'checkout.session.async_payment_succeeded':
        await fulfillCheckout(event.data.object.id);
        break;
      case 'checkout.session.async_payment_failed':
        // Tell the customer their bank payment did not go through.
        break;
    }
  } catch (err) {
    console.error(err);
    return new Response('Processing failed', { status: 500 }); // Stripe will retry
  }

  return new Response('ok', { status: 200 });
});

Stripe calls your endpoint without a Supabase user token, so turn off JWT verification for this one function. Supabase's docs name Stripe webhooks as the typical case, and warn that anyone can then call the function. That is fine here, because the signature check is the authentication.

# supabase/config.toml
[functions.stripe-webhook]
verify_jwt = false

Then register the endpoint in the Stripe Dashboard: Workbench → Webhooks → Create an event destination. Choose your account, the Snapshot payload (the Checkout fulfillment guide is written around snapshot events), and only the events you handle: checkout.session.completed, checkout.session.async_payment_succeeded, checkout.session.async_payment_failed. The URL is your function URL, for example https://<project-ref>.supabase.co/functions/v1/stripe-webhook. Copy the whsec_ secret it shows into your function secrets.

Step 5: How do you avoid fulfilling the same order twice?

Stripe is clear about three behaviours you must design for (webhooks docs):

  • The same event can arrive more than once.
  • Events are not guaranteed to arrive in the order they were created.
  • Your fulfillment function may be called several times, even at the same time, for the same Checkout Session (from the webhook and from your success page).

Stripe's fulfillment guide describes the function: take the Checkout Session ID, retrieve the session with line_items expanded, check payment_status, fulfill, and record that you did. The key is an atomic "claim" so only one call can win:

async function fulfillCheckout(sessionId: string) {
  const session = await stripe.checkout.sessions.retrieve(sessionId, {
    expand: ['line_items'],
  });

  // Delayed methods (bank debits) complete Checkout before the money arrives.
  if (session.payment_status === 'unpaid') return;

  // Atomic claim: only one call can move this order from 'pending' to 'paid'.
  const { data: claimed, error } = await admin
    .from('orders')
    .update({
      status: 'paid',
      amount_total: session.amount_total,
      currency: session.currency,
    })
    .eq('stripe_session_id', sessionId)
    .eq('status', 'pending')
    .select('id, user_id, plan');

  if (error) throw error;
  if (!claimed || claimed.length === 0) return; // already fulfilled, or not our session

  // Grant access, send the receipt email, update stock, and so on.
  // Use the amounts from Stripe (session.amount_total), never from the browser.
}

If you also want an audit trail, store each event.id you process in a table with a unique constraint. Stripe recommends tracking event IDs to spot duplicate deliveries, and warns against using the created timestamp to decide order or duplicates.

Step 6: What should the success page do?

A redirect to your success URL is not proof of payment. A customer can pay and lose their connection before the page loads, and with bank debits the money arrives later. So:

  • The success page reads the order's status from your database (via RLS) and shows "processing" until it is paid.
  • Optionally, the page can call a small server function that runs the same fulfillCheckout(session_id). Stripe recommends this so the customer gets access immediately even if the webhook is late. Because the function is idempotent, this is safe.
  • When you set a success_url and have a webhook listening for checkout.session.completed, Checkout waits up to 10 seconds for your webhook to respond before redirecting. Keep that handler fast.

How do you test all of this in Stripe's sandbox?

  1. Use sandbox keys (sk_test_ or rk_test_) and create your test products and prices in the sandbox.
  2. Install the Stripe CLI and run stripe login.
  3. Run your function locally: supabase functions serve stripe-webhook --no-verify-jwt. It listens on http://localhost:54321/functions/v1/stripe-webhook.
  4. Forward events: stripe listen --forward-to localhost:54321/functions/v1/stripe-webhook. The CLI prints a whsec_ secret. Use that value locally; it is not the same as the Dashboard endpoint's secret.
  5. Go through Checkout as a customer with test cards: 4242 4242 4242 4242 (succeeds), 4000 0025 0000 3155 (needs 3D Secure), 4000 0000 0000 9995 (declined, insufficient funds). Any future expiry date and any CVC work.
  6. Check that the order row moved to paid exactly once. Then resend the same event to prove your idempotency: in the Dashboard click Resend on the event, or run stripe events resend <event_id> --webhook-endpoint=<endpoint_id>.

stripe trigger payment_intent.succeeded is useful for checking that signature verification works, but triggered events use fixture data that does not match an order in your database. The real test is a full Checkout run.

Retries also differ between environments: in live mode Stripe retries failed deliveries for up to three days with exponential back-off, while in a sandbox it retries three times over a few hours.

Refunds and subscriptions: what changes?

Refunds. Issue them from the Dashboard or from server code that only admins can trigger. Pass an idempotency key so a retried request cannot refund twice. Partial refunds take an amount in the smallest currency unit.

await stripe.refunds.create(
  { payment_intent: paymentIntentId, amount: 1000 }, // omit amount for a full refund
  { idempotencyKey: `refund-${orderId}` },
);

Refunds can stay pending and can fail later (for example to a closed account). Listen for at least refund.created, plus refund.failed, and update your own records from those events. See Stripe's refunds guide.

Subscriptions. Use mode: 'subscription' with a recurring price. Most subscription activity happens later, without the customer present, so webhooks are required. Stripe's subscription webhooks guide suggests: on invoice.paid, retrieve the subscription and extend access only if its status is active; on invoice.payment_failed or status past_due, ask the customer to update their card; on customer.subscription.deleted or status canceled/unpaid, revoke access. Store an access-until date in your database rather than asking Stripe on every page load.

What are the most common mistakes in AI-generated Stripe code?

  • Secret key in the frontend. A VITE_STRIPE_SECRET_KEY ends up in the public bundle. Rotate the key in the Dashboard immediately if this happened.
  • Amount sent from the browser. Any price_data or amount built from request data the user controls.
  • Fulfillment on the success page only. Paid customers without access, or access without payment if the page trusts a URL parameter.
  • Signature verification fails. Usually the body was parsed before verification, or the wrong secret is used (CLI secret vs Dashboard secret, sandbox vs live).
  • 401 from Supabase on the webhook. JWT verification is still on for the webhook function.
  • Redirects. Stripe treats a 3xx response as a failed delivery. Register the final URL.
  • Slow handlers and timeouts. Return 2xx quickly. Stripe recommends a queue for heavy work.
  • API version drift. Since stripe-node v12, the SDK pins the API version that was current when that SDK version was released. Webhook payloads use the version set on the endpoint, or your account default. Keep them aligned (the current version at the time of writing is 2026-11-18.endive; see versioning).
  • Going live without switching everything. Live keys, live prices, a live webhook endpoint and its new signing secret.

Brief for your AI coding tool

Paste this into Lovable, Claude Code or Cursor, and adjust the plan names and URLs:

Add Stripe Checkout (Checkout Sessions API, Stripe-hosted page) to this app.

Architecture:
- Supabase Edge Function "create-checkout-session": requires a signed-in user (validate the
  Supabase JWT), accepts only { plan } from the client, maps plan -> Stripe Price ID in a
  server-side constant, creates the session with client_reference_id = user.id and
  success_url containing {CHECKOUT_SESSION_ID}, inserts a 'pending' row in public.orders
  (unique stripe_session_id), returns { url }.
- Supabase Edge Function "stripe-webhook": verify_jwt = false in config.toml. Read the raw
  body with req.text(), verify with stripe.webhooks.constructEventAsync and
  Stripe.createSubtleCryptoProvider(), return 400 on failure. Handle only
  checkout.session.completed, checkout.session.async_payment_succeeded and
  checkout.session.async_payment_failed. Return 500 on processing errors so Stripe retries.
- fulfillCheckout(sessionId): retrieve the session with expand ['line_items'], skip if
  payment_status === 'unpaid', then atomically update orders set status='paid' where
  stripe_session_id = id AND status = 'pending'; only grant access if a row was updated.
- Frontend: success page reads order status from the database; shows "processing" until paid.

Safety rules:
- Never put sk_/rk_ keys or whsec_ secrets in frontend code or VITE_ variables.
- Never accept amounts, prices or paid flags from the client.
- Never fulfill from the redirect alone.
- Enable RLS on orders: users can select their own rows; no client insert/update.
- Use stripe@^23 via npm: specifier. Use sandbox keys until I confirm go-live.
- Write a short test plan: Stripe CLI forwarding, test cards 4242 4242 4242 4242 and
  4000 0000 0000 9995, and resending the same event to prove no double fulfillment.

When should you bring in a developer?

The setup above covers one-off payments and simple subscriptions well. Get an experienced developer to build or review it when:

  • Money moves between more than two parties (marketplaces, payouts to sellers, Stripe Connect).
  • Billing gets complex: trials, upgrades with proration, usage-based pricing, coupons that must sync elsewhere.
  • Payments must reach your accounting system or ERP automatically, with VAT handled correctly.
  • You can't say what happens when a webhook fails for three days, or how you would find and replay missed events.
  • Real customers are about to pay and nobody has reviewed the code that grants access after payment.

We take over exactly this kind of work: connecting vibe-coded apps to real systems, and a code audit before go-live if you want an independent check first. Read more about how we work with Stripe, and about our integration services. Rocksoft is a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.

Related guides

FAQ

Can I call the Stripe API directly from my React app?

Only with the publishable key, which cannot create charges or read account data. Anything that creates sessions, refunds or reads customers must run on a server, such as a Supabase Edge Function.

Do I need webhooks if I only sell one-time products?

Yes. Stripe states that you can't rely on the landing page for fulfillment because customers are not guaranteed to reach it. Webhooks are also required for subscriptions and for payment methods where the money arrives later.

Should I choose thin or snapshot events?

Stripe's Dashboard suggests thin events for new destinations. This guide uses snapshot events because Stripe's Checkout fulfillment guide is built on them, and the handler re-fetches the Checkout Session anyway. Thin events use a different SDK method (parseEventNotification), so don't mix the two in one handler.

Why does signature verification fail locally but work in production (or the other way round)?

The Stripe CLI, the sandbox endpoint and the live endpoint each have their own whsec_ secret. Make sure the running function uses the secret for the place the event came from.

How do I stop the same order from being fulfilled twice?

Make fulfillment idempotent per Checkout Session: one atomic database update from pending to paid, and only the call that changed the row grants access.

Is Payment Links enough for a SaaS app?

For a first version with a few fixed prices, it can be. As soon as you need to link payments to user accounts, apply plans in your app or handle upgrades, create Checkout Sessions from your server instead.

What is the current Stripe API version?

At the time of writing, Stripe's versioning page lists 2026-11-18.endive. Stripe releases monthly versions without breaking changes and two major releases a year that may contain them.