# Agent file: take payments with Stripe Checkout and webhooks

This file is written for an AI coding agent working in a repository with its owner present. Follow the steps in order and run the check at the end of each step before starting the next. It is complete without the guide it accompanies.

Every fact about Stripe here was checked against the pages under Sources on October 10, 2026. Commands, flags and dashboard labels change. If one fails, read the linked page before trying again. Do not guess.

The TypeScript below is trimmed from working code and type-checks against version 23 of the `stripe` Node package, whose API version is `2026-09-30.endive`. On another major version, check each call against the installed types before copying it, and set `STRIPE_API_VERSION` to the version that package was built for.

## Goal

A buyer pays on a Stripe-hosted Checkout page. A signed webhook tells the server what happened, and that webhook is the only code that records who has paid. Customers manage their own billing in the Stripe customer portal. Everything is built and tested in a sandbox.

## Preconditions

Check each one in the repository before changing anything.

- Find where a user or account is stored, and which fields would hold the Stripe customer id, the plan and the subscription status. Report them and wait for confirmation before adding columns or a migration.
- Find how the app authenticates a request. Checkout and the billing portal must act for the signed-in customer only.
- Find any auth middleware. The webhook route has to sit outside it.
- Check whether a JSON body parser runs globally (Express). The webhook needs the raw body.
- Confirm the keys available to you are sandbox keys. Their names are below. If a value starts with `sk_live_` or `rk_live_`, stop.

## Environment variables

Names only.

| Name | Notes |
| --- | --- |
| `STRIPE_SECRET_KEY` | Secret. Server only. Sandbox keys start with `sk_test_` or `rk_test_`. Stripe recommends a restricted key (`rk_`) with only the permissions the server needs. |
| `STRIPE_WEBHOOK_SECRET` | Secret. Starts with `whsec_`. Locally it comes from `stripe listen`. On a server it comes from the registered endpoint. Each endpoint and each mode has its own. |

A publishable key (`pk_`) is the only Stripe key that may appear in browser code. The flow in this file does not need one.

## Stop and ask the human

- Any secret value. Ask for the variable to be set by the human. Never print, log, commit or echo a secret, and never ask for one to be pasted into the conversation.
- Any sign-in, account creation, plan choice or payment method.
- Anything that deletes data or cannot be undone.
- Anything in live mode: live keys, live prices, the live webhook endpoint, the live customer portal configuration. Stripe states that real card details must not be used for testing.
- Prices and amounts. Use the numbers the human gives you. Never invent one.
- Registering the webhook endpoint in the Dashboard and copying its signing secret.
- Adding columns or running a migration.
- Refunds, cancellations or any change to an existing customer or subscription.

## Steps

### 1. Read the keys once, and degrade when they are missing

```ts
import 'server-only';
import Stripe from 'stripe';

/** The API version every request is sent with. The type accepts only the installed package's own version. */
export const STRIPE_API_VERSION = '2026-09-30.endive' satisfies Stripe.LatestApiVersion;

/** The Stripe client, or undefined when STRIPE_SECRET_KEY is unset. */
export const stripe: Stripe | undefined = (() => {
  const key = process.env.STRIPE_SECRET_KEY;
  return key ? new Stripe(key, { apiVersion: STRIPE_API_VERSION }) : undefined;
})();

/** The webhook signing secret, or undefined when unset (the webhook then answers 503). */
export const stripeWebhookSecret: string | undefined = process.env.STRIPE_WEBHOOK_SECRET;
```

Pass `apiVersion` explicitly. Stripe documents that the Node library otherwise sends the version that was latest when the library was released, so naming it keeps a library upgrade from changing the version unnoticed.

Without the keys the app must still start. Payment routes answer 503 or send the visitor somewhere useful.

Check: the app boots with both variables unset.

### 2. Decide where prices live

Either create products and prices in the Dashboard Product catalog and refer to them by id or lookup key, or pass amounts inline as `price_data`. Stripe documents that inline prices cannot be updated or reused. A lookup key lets code ask for a price by a stable name, and `transfer_lookup_key` moves that name to a new price.

Whichever you choose, amounts and price ids come from server code. Never from the request.

### 3. Build the Checkout Session parameters

Use `mode: "payment"` for a one-time charge and `mode: "subscription"` when at least one item recurs. In subscription mode a one-time price is charged on the first invoice only. Put `{CHECKOUT_SESSION_ID}` in `success_url` and Stripe replaces it with the session id. Set `client_reference_id` and `metadata` to your own identifier so the webhook can find the buyer.

```ts
// Pure, so the exact charge is unit-tested without Stripe.
// PLAN holds the amounts in cents, in one file in the repository.
export function buildCheckoutParams(buyer: Buyer, origin: string): Stripe.Checkout.SessionCreateParams {
  const metadata = { buyer: buyer.id };
  return {
    mode: 'subscription',
    client_reference_id: buyer.id,
    line_items: [
      // A one-time price in subscription mode lands on the first invoice only.
      { quantity: 1, price_data: { currency: 'usd', unit_amount: PLAN.setupCents, product_data: { name: 'Setup' } } },
      {
        quantity: 1,
        price_data: {
          currency: 'usd',
          unit_amount: PLAN.monthlyCents,
          recurring: { interval: 'month' },
          product_data: { name: 'Monthly plan' },
        },
      },
    ],
    metadata,
    subscription_data: { metadata },
    success_url: `${origin}/welcome?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${origin}/pricing`,
  };
}
```

Check: a unit test asserts the exact amounts, mode and URLs this function returns.

### 4. Add the route that starts checkout

```ts
// app/api/checkout/route.ts
export async function POST(request: NextRequest): Promise<NextResponse> {
  // findBuyer is yours: resolve the buyer from your own records, never from a posted price.
  const buyer = await findBuyer(request);
  if (buyer === undefined) return NextResponse.json({ error: 'Unknown buyer' }, { status: 404 });

  // No key (local or preview): send the visitor somewhere useful instead of failing.
  if (stripe === undefined) return NextResponse.redirect(new URL('/contact', SITE_URL), 303);

  const session = await stripe.checkout.sessions.create(buildCheckoutParams(buyer, SITE_URL));
  if (session.url === null) throw new Error('Stripe returned a session without a URL');
  return NextResponse.redirect(session.url, 303);
}
```

Check: posting to the route in a sandbox redirects to a `checkout.stripe.com` URL.

### 5. Receive the webhook

The route must be reachable without a session. Verify the signature with the Stripe library, using the raw body, the `Stripe-Signature` header and the signing secret. Answer 400 on a bad signature. Answer 200 for event types you do not handle. Return quickly.

A Next.js route handler for a one-time purchase:

```ts
// app/api/stripe/webhook/route.ts
export async function POST(request: NextRequest): Promise<NextResponse> {
  if (stripe === undefined || stripeWebhookSecret === undefined) {
    return NextResponse.json({ error: 'Stripe is not configured' }, { status: 503 });
  }

  const signature = request.headers.get('stripe-signature');
  if (signature === null) return NextResponse.json({ error: 'Missing signature' }, { status: 400 });

  let event: Stripe.Event;
  try {
    // request.text() is the raw body. Parsing it as JSON first breaks the signature.
    event = stripe.webhooks.constructEvent(await request.text(), signature, stripeWebhookSecret);
  } catch {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  if (event.type !== 'checkout.session.completed') return NextResponse.json({ received: true });

  // fulfill is yours. It must be safe to run twice for the same session.
  await fulfill(event.data.object);
  return NextResponse.json({ received: true });
}
```

If you accept bank debits or other delayed methods, also handle `checkout.session.async_payment_succeeded`.

In Express, mount the raw body parser on the webhook path before `express.json()`:

```ts
// Mount BEFORE express.json(): signature checks need the exact bytes that
// were sent, so the webhook handlers must receive req.body as a Buffer.
app.use('/api/webhooks/clerk', express.raw({ type: 'application/json', limit: '1mb' }));
app.use('/api/webhooks/stripe', express.raw({ type: 'application/json', limit: '1mb' }));
```

An Express handler for subscriptions:

```ts
// Mounted at /api/webhooks/stripe, above the auth guard, after the raw body parser.
router.post('/', async (req: Request, res: Response) => {
  const signature = req.headers['stripe-signature'];
  if (typeof signature !== 'string' || !Buffer.isBuffer(req.body)) {
    res.status(400).json({ error: 'Missing signature or raw body' });
    return;
  }

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(req.body, signature, webhookSecret);
  } catch {
    res.status(400).json({ error: 'Invalid signature' });
    return;
  }

  switch (event.type) {
    case 'customer.subscription.created':
    case 'customer.subscription.updated':
    case 'customer.subscription.deleted': {
      const sub = event.data.object;
      const customerId = typeof sub.customer === 'string' ? sub.customer : sub.customer.id;
      await applySubscriptionStatus(customerId, sub.status, sub.items.data[0]?.price.lookup_key);
      break;
    }
    default:
      break; // Not ours. Still answer 200 so Stripe does not retry it.
  }

  res.json({ received: true });
});
```

Stripe retries a failed delivery for up to three days in live mode, can deliver the same event more than once, and does not guarantee order. The handler must be idempotent.

Check: a request with a wrong signature gets 400, and replaying a valid event leaves the database unchanged.

### 6. Let only the webhook write payment state

The plan and the subscription status are written in exactly one function, called only from the webhook. Grant the paid plan when the status is `active` or `trialing`. Fall back to the free plan for every other status. Stripe says to revoke access when a subscription becomes `canceled` or `unpaid`.

```ts
async function applySubscriptionStatus(customerId: string, status: string, plan?: string | null) {
  const org = await prisma.organization.findFirst({ where: { stripeCustomerId: customerId } });
  if (!org) return;

  const active = status === 'active' || status === 'trialing';

  // Sets the state to what the event says, so a repeat delivery changes nothing.
  await prisma.organization.update({
    where: { id: org.id },
    data: { subscriptionStatus: status, planSlug: active ? (plan ?? org.planSlug) : 'free' },
  });
}
```

Check: add a test that fails if any route other than the webhook changes the plan or status fields.

### 7. Confirm the session on the success page, without writing

Stripe documents that customers are not guaranteed to reach the success page, so it must not be what marks an account as paid. It may read. Retrieve the session from Stripe on the server and check that it is complete, not unpaid, and belongs to this buyer.

```ts
export function isPaidSession(session: Stripe.Checkout.Session, buyerId: string): boolean {
  return (
    session.status === 'complete' &&
    session.payment_status !== 'unpaid' &&
    // A valid session id for one buyer must not open another buyer's page.
    session.client_reference_id === buyerId
  );
}

// On the success page: ask Stripe. Never trust the query string alone.
const session = await stripe.checkout.sessions.retrieve(sessionId);
if (!isPaidSession(session, buyer.id)) notFound();
```

Check: a session id that belongs to another buyer does not open the page.

### 8. Add the billing portal

Authenticate the customer first. Create the session for their own Stripe customer id and redirect to its `url`. The human configures what the portal allows in the Dashboard customer portal settings. Changes made there reach the app through the same subscription webhook.

```ts
// customerId comes from the signed-in user's own record, never from the request.
const session = await stripe.billingPortal.sessions.create({
  customer: customerId,
  return_url: returnUrl,
});
res.json({ url: session.url });
```

Check: a signed-out request cannot create a portal session, and no request can name another customer id.

### 9. Test in the sandbox

```bash
npm install -g @stripe/cli
stripe login
# Prints a whsec_ signing secret for local use. Use your own port and path.
stripe listen --forward-to localhost:3000/api/stripe/webhook
```

The human runs `stripe login`. Put the printed signing secret in the local environment. Go through checkout with the test card `4242 4242 4242 4242`, any future expiry date and any three-digit CVC. The card `4000 0000 0000 0002` is declined.

Check: the terminal running `stripe listen` shows `checkout.session.completed` forwarded with a 200, and the database changed once.

### 10. Hand over the go-live list

Do not do these. Give them to the human:

- Read the Stripe go-live checklist.
- Recreate the prices in live mode. The product page has a Copy to live mode button.
- Register the webhook endpoint in live mode in Workbench under Webhooks, choosing Create an event destination. The handlers above read the full object from the event, which is the Snapshot payload format. Select only the event types the code handles. Store the new signing secret.
- Configure the customer portal in live mode. Stripe keeps a separate configuration per mode.
- Replace the sandbox keys with live keys in the host variables and redeploy.

## Done when

- A sandbox purchase updates the database through the webhook, with the success page closed before it loads.
- Replaying the same event changes nothing.
- Canceling the subscription in the Dashboard drops the plan.
- No route other than the webhook writes the plan or status.
- No key or signing secret appears in git or in your output.
- The human has the go-live list and the exact event types to select.

## Sources

- [API keys](https://docs.stripe.com/keys)
- [Set a Stripe API version](https://docs.stripe.com/sdks/set-version)
- [Manage products and prices](https://docs.stripe.com/products-prices/manage-prices)
- [Create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create)
- [Fulfill orders](https://docs.stripe.com/checkout/fulfillment)
- [Receive Stripe events in your webhook endpoint](https://docs.stripe.com/webhooks)
- [Using webhooks with subscriptions](https://docs.stripe.com/billing/subscriptions/webhooks)
- [Integrate the customer portal](https://docs.stripe.com/customer-management/integrate-customer-portal)
- [Test your integration](https://docs.stripe.com/testing)
- [Go-live checklist](https://docs.stripe.com/get-started/checklist/go-live)
- [Pricing and fees](https://stripe.com/pricing)
