Skip to content

Stripe Payments prompt

Rules that make your coding agent build Stripe payments that hold up in production: Checkout Sessions, prices from Stripe, verified idempotent webhooks and subscriptions synced to your database.

What it makes your agent good at

Left alone, agents trust a price from the browser, fulfill on the success page, parse the webhook body before verifying it and write against fields Stripe has removed. This prompt gives them the stripe 23 SDK as installed: Checkout Sessions with prices resolved by lookup key, webhooks as the source of truth with idempotent handlers, subscription state synced from Stripe, and the checks to run with the Stripe CLI.

  1. Prices from Stripe, not the clientLookup keys resolved on the server, one Product per plan, and only a plan key or product IDs accepted from the browser.
  2. Checkout Sessions by defaultHosted, embedded_page or elements for one-time and subscription payments, with dynamic payment methods and no payment_method_types.
  3. Verified, idempotent webhooksRaw body from request.text(), constructEvent with the signing secret, and each event id recorded once in the write's transaction.
  4. Subscriptions synced to your databaseStatus, price and the item's current_period_end stored per subscription, refetched from Stripe, access from active or trialing.
  5. No double chargesIdempotency keys on create calls, fulfillment safe to run twice, delayed payments fulfilled only once paid.
  6. Tested the way payments failStripe CLI forwarding, duplicate events, 3D Secure and failing test cards, and test clocks for renewals.

The Stripe Payments rules

128 lines, current to Stripe Node SDK 23 (API 2026-09-30) and Next.js 16.4. Last reviewed October 23, 2026. Plain Markdown, no front matter: each agent's is below.

Download

stripe-payments.md

# Stripe Payments

You are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.

## Before you write code

- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.
- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.
- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.

## The client and the catalog

```ts
// lib/stripe.ts
import "server-only";
import Stripe from "stripe";

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);
```

- One client, server only. `Stripe` is a class: call `new Stripe(key)`. Do not pass `apiVersion` unless the project pins one already: the default matches the types.
- Create webhook endpoints on the same API version as the SDK; events are rendered in the endpoint's version, not the SDK's.
- Products and prices live in Stripe, not in code. One Product per plan (Starter, Pro, Team); several Prices on a Product only for variants of that plan (monthly, yearly, currencies). Give each price a `lookup_key` (`pro_monthly`) and resolve it on the server: `stripe.prices.list({ lookup_keys: ["pro_monthly"], expand: ["data.product"] })`.
- The client sends a plan key or a cart of product IDs and quantities, never a price ID it chose, an amount or a currency. The server validates the key against an allowlist and looks up the price.
- Show prices on the page from Stripe (cached, and refreshed on `price.*` events) so the page and the charge cannot disagree.

## Checkout Sessions first

Use Checkout Sessions for one-time payments (`mode: "payment"`) and subscriptions (`mode: "subscription"`). Create them in a Server Function or Route Handler after authenticating the user.

```ts
"use server";
import { redirect } from "next/navigation";

export async function startCheckout(plan: string, attemptId: string) {
  const user = await requireUser();
  const origin = process.env.APP_URL; // configured, never the Host header
  const price = await priceForPlan(plan); // lookup key -> Stripe.Price, or throws
  const customer = await customerIdFor(user); // created once, stored on the user
  const session = await stripe.checkout.sessions.create(
    {
      mode: "subscription",
      customer,
      client_reference_id: user.id,
      line_items: [{ price: price.id, quantity: 1 }],
      automatic_tax: { enabled: true },
      customer_update: { address: "auto" },
      success_url: `${origin}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${origin}/pricing`,
    },
    { idempotencyKey: `checkout-${user.id}-${attemptId}` }
  );
  redirect(session.url as string);
}
```

- `ui_mode` is `"hosted_page"` by default (redirect to `session.url`). For checkout inside your page use `ui_mode: "embedded_page"` with a `return_url` instead of `success_url`, return `session.client_secret` to the client, and mount Stripe's embedded Checkout from `@stripe/react-stripe-js`. For a fully custom form use the Payment Element backed by a Checkout Session (`ui_mode: "elements"`), not a hand-built card form.
- Do not pass `payment_method_types`: it is removed from Checkout Sessions in this API version. Payment methods come from the Dashboard (dynamic payment methods); narrow them with `excluded_payment_method_types`, or `allowed_payment_method_types` only when you must.
- Load Stripe.js once per page with `loadStripe(publishableKey)` from `@stripe/stripe-js` at module scope, never inside a render.
- The success page is for showing a receipt, not for fulfilling. It may read the session by `session_id`, check it belongs to the signed-in user, and show its state.
- Use PaymentIntents directly only for off-session charges or flows Checkout cannot model. Never use the Charges API, Sources, Tokens or the Card Element.

## Customers and subscriptions

- Map one user (or one organization, for team billing) to one Stripe Customer. Create the customer before the first checkout, store `stripeCustomerId` with a unique index, and pass `customer` on every session so payment methods and invoices stay on one record.
- Resolve events to your records through Stripe's objects: customer ID to user, subscription ID to subscription row. Use `metadata` and `client_reference_id` only as a fallback.
- Store per subscription: Stripe subscription ID, customer ID, status, price ID or lookup key, `cancel_at_period_end`, and the period end. The period end is on the item: `subscription.items.data[0].current_period_end` (seconds), not on the subscription.
- Grant access from the stored status: `active` and `trialing` have access; decide deliberately whether `past_due` keeps a grace period; `incomplete`, `incomplete_expired`, `unpaid`, `canceled` and `paused` do not.
- On an invoice, the subscription is at `invoice.parent.subscription_details.subscription`, not `invoice.subscription`.
- Upgrades, downgrades, cancellations and card changes go through the Billing (customer) Portal: `stripe.billingPortal.sessions.create({ customer, return_url })`, then redirect to its `url`. Configure allowed plan changes in the Dashboard. Build your own flow only for what the portal cannot do, with `stripe.subscriptions.update` and proration settings you choose.
- Never build renewals with PaymentIntents in a cron job: Billing handles renewals, retries and dunning.

## Webhooks are the source of truth

```ts
// app/api/webhooks/stripe/route.ts
import type Stripe from "stripe";
import { stripe } from "@/lib/stripe";

export async function POST(request: Request) {
  const body = await request.text();
  const signature = request.headers.get("stripe-signature") ?? "";
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET as string);
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }
  await handleEvent(event); // throws on failure, so Stripe retries
  return new Response(null, { status: 200 });
}
```

- Read the raw body with `await request.text()` and verify it before parsing. Never call `request.json()` first or re-serialize the body: the signature covers the exact bytes. On an edge or worker runtime, use `constructEventAsync`.
- Keep the webhook route public: exclude it from `proxy.ts` auth redirects and never require a session on it. The signature is its authentication.
- Handle the events you act on and acknowledge the rest with 200:
  - `checkout.session.completed` and `checkout.session.async_payment_succeeded`: fulfill when `payment_status` is not `"unpaid"`. `checkout.session.async_payment_failed`: tell the customer.
  - `customer.subscription.created`, `.updated`, `.deleted`: sync the subscription row.
  - `invoice.paid`: extend access for the new period. `invoice.payment_failed`: flag the account and notify. `invoice.payment_action_required`: send the customer to the hosted invoice to authenticate.
  - `charge.refunded` and `charge.dispute.created` when access or records depend on them.
- Make every handler idempotent. Record `event.id` in a table with a unique constraint inside the same transaction as the write; a duplicate insert means the event was handled, so return 200.
- Events arrive late, twice and out of order. For subscriptions, retrieve the current object (`stripe.subscriptions.retrieve(id)`) and write that state, rather than applying the event's snapshot over newer data.
- Respond within seconds. Move slow work (emails, provisioning) after the write. A non-2xx response makes Stripe retry for days, so return 500 only when a retry can succeed.
- Fulfillment code is one function called by the webhook (and optionally by the success page), safe to run twice.

## Money safety

- Pass an `idempotencyKey` (second argument, request options) on create calls that charge or create objects, derived from the attempt (a form token or order ID), so a double click or retried request returns the first result instead of a second charge. Reusing a key with different parameters is an error.
- 3D Secure and other authentication are handled by Checkout and the Payment Element. Do not try to detect or skip them. For renewals that need authentication, handle `invoice.payment_action_required` and keep Stripe's customer emails for failed and incomplete payments on.
- Delayed methods (bank debits, vouchers) complete hours or days later: a subscription can sit in `incomplete` and a session can be `complete` while `unpaid`.
- Stripe Tax: `automatic_tax: { enabled: true }` collects nothing until the account has an active registration in the customer's jurisdiction and products have tax codes. Say so when you enable it. It cannot be combined with manual `tax_rates` on the same object. For returning customers, `customer_update: { address: "auto" }` saves the address entered at checkout.
- PCI: card data never touches your server. Collect it only in Checkout or Stripe Elements; never log, store or proxy card numbers, and never put a secret or restricted key in client code or a `NEXT_PUBLIC_` variable.
- Catch `Stripe.errors.StripeError` (and subclasses like `StripeCardError`) around API calls and return a message the user can act on; log the request ID, not the payload.

## Do not

- Do not trust a price, amount, currency, plan or quantity limit sent by the browser.
- Do not fulfill orders or grant access from the success URL alone, or skip signature verification "for now".
- Do not pass `payment_method_types`, read `subscription.current_period_end` or `invoice.subscription`, or call `Stripe(key)` without `new`: those belong to older API versions and SDKs.
- Do not use the Pages Router `bodyParser: false` config, Charges, Sources, Tokens, the Card Element or the deprecated `plan` object.
- Do not create a new Stripe Customer on every checkout, or a Product per price.

## Before you finish

- Run the type checker and linter; the SDK's types catch removed parameters.
- Test in a sandbox with the Stripe CLI: `stripe listen --forward-to localhost:3000/api/webhooks/stripe` (use the `whsec_` it prints locally), then `stripe trigger checkout.session.completed` and the subscription events. Send each event twice and confirm one write.
- Pay with test cards: `4242 4242 4242 4242` succeeds, `4000 0025 0000 3155` requires 3D Secure, `4000 0000 0000 0341` attaches but fails later charges. Use test clocks to advance a subscription through renewal and failure.
- List the Dashboard settings the change depends on (webhook events and API version, portal configuration, tax registrations, payment methods) for the reviewer.

11,199 characters, 1,577 words. Under Windsurf's 12,000-character limit for a rule, as every prompt here is.

Use it in your agent

The same rules, where your agent reads them. Each file has the front matter its agent needs, set to load when the task fits.

Claude Code

A rule it loads every session

  1. Save it as .claude/rules/stripe-payments.md in your project, front matter included, or run the install command.
  2. Claude Code loads every file in .claude/rules with your CLAUDE.md when a session starts.
  3. Prefer one file? Paste it into CLAUDE.md under its own heading instead.

.claude/rules/stripe-payments.md

# Stripe PaymentsYou are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.## Before you write code- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.## The client and the catalog…

Or let the shadcn CLI write this file: sign in (free) for your command.

Cursor

A project rule with front matter

  1. Save it as .cursor/rules/stripe-payments.mdc, front matter included, or run the install command.
  2. Cursor attaches it when you work on matching files, or when the task fits its description.
  3. Check it under Cursor Settings, Rules, then commit the folder for your team.

.cursor/rules/stripe-payments.mdc

---description: "Payments with Stripe: Checkout Sessions, prices, customers, subscriptions, the billing portal, webhooks, idempotency and tax."alwaysApply: false---# Stripe PaymentsYou are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.## Before you write code- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.## The client and the catalog…

Or let the shadcn CLI write this file: sign in (free) for your command.

Windsurf

A workspace rule for Cascade

  1. Save it as .windsurf/rules/stripe-payments.md, or run the install command.
  2. trigger: model_decision lets Cascade pull it in when the task fits its description.
  3. Windsurf reads up to 12,000 characters per rule; this one is 11,199.

.windsurf/rules/stripe-payments.md

---trigger: model_decisiondescription: "Payments with Stripe: Checkout Sessions, prices, customers, subscriptions, the billing portal, webhooks, idempotency and tax."---# Stripe PaymentsYou are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.## Before you write code- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.## The client and the catalog…

Or let the shadcn CLI write this file: sign in (free) for your command.

GitHub Copilot

Instructions for the repository

  1. Save it as .github/instructions/stripe-payments.instructions.md, or run the install command.
  2. applyTo: "**" applies it to every request in this repository.
  3. Or paste it into .github/copilot-instructions.md, which Copilot reads for every request.

.github/instructions/stripe-payments.instructions.md

---description: "Payments with Stripe: Checkout Sessions, prices, customers, subscriptions, the billing portal, webhooks, idempotency and tax."applyTo: "**"---# Stripe PaymentsYou are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.## Before you write code- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.## The client and the catalog…

Or let the shadcn CLI write this file: sign in (free) for your command.

Codex & AGENTS.md

The file most agents read

  1. Paste it into AGENTS.md at your project's root, under its own heading.
  2. Codex reads AGENTS.md before it starts work, and so do Cursor, Zed, Jules, Amp and Copilot's coding agent.
  3. A folder can have its own AGENTS.md: the one closest to the file being edited wins.

AGENTS.md

## Stripe PaymentsYou are working in a Next.js 16 App Router project that takes payments with Stripe through the `stripe` Node SDK 23 and TypeScript. Write code for the versions in `package.json`: the SDK pins API version `2026-09-30.endive`, and several fields and parameters you remember have moved or been removed.### Before you write code- Read the installed SDK's types before using a parameter: `node_modules/stripe/cjs/resources/` (`Checkout/Sessions.d.ts`, `Subscriptions.d.ts`, `Invoices.d.ts`, `BillingPortal/Sessions.d.ts`). The types describe only the pinned API version; `node_modules/stripe/CHANGELOG.md` lists what changed.- Find the existing Stripe client (`lib/stripe.ts`), webhook route and billing tables, and extend them. Check how users map to Stripe customers before adding a column.- Check which environment variables exist: `STRIPE_SECRET_KEY` (prefer a restricted `rk_` key with only the permissions the server uses), `STRIPE_WEBHOOK_SECRET`, `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.### The client and the catalog…

AGENTS.md is shared with your own instructions, so paste the rules in: the copy sets their headings a level down.

Rules teach it. The MCP equips it. With Pro, your agent installs every component, block and icon it needs, from a prompt.

Get Pro

Pricing

Give your agent the parts, with Pro

The prompts are free. Every Pro plan adds the MCP server, so your agent installs the components, blocks and icons it writes code around.

4.9/5 out of 5 · 150+ reviewsfrom 150+ founders and developers.

Billed once a year in USD. Cancel anytime.

Individual

For personal projects & open source

$32instead of $49/mo

$389 billed yearly

  • How many people can use the license.Seats: 1 seat
  • Client work, SaaS products and anything you charge for.Commercial use: Personal & open source only
  • Page sections in 56 categories, from heroes and pricing tables to dashboards and settings, on every framework and UI library, in your theme.Blocks: All 6,181 blocks
  • Complete Next.js sites for startups, SaaS, agencies and portfolios, every page designed, ready to ship.Templates: All 14 templates
  • Your AI agent searches, previews and installs any component, block, icon or DESIGN.md from a prompt: 22 tools in Claude Code, Cursor, VS Code and 35 more clients.MCP server: 38 AI clients
  • Buttons with motion and states of their own, from an arrow that slides in to a burst of confetti.Animated buttons: All 35 buttons
  • Typewriters, scrambles, counters and more, for headlines, labels and numbers.Text effects: All 97 effects
  • Animated backgrounds for heroes, sections and cards, from a soft aurora to a flock that flees the cursor. Most are pure CSS.Backgrounds: All 100 backgrounds
  • WebGPU shaders, from a slow aurora to a black hole, each drawing only while it's on screen.Shaders: All 100 shaders
  • One design and one theme on all four: the components, blocks and effects are built for each framework.Frameworks: React, Vue, Svelte, Solid
  • React on Base UI, Radix UI, React Aria or Ark UI: install the version for the library your project already uses. Vue, Svelte and Solid run on Ark UI.UI libraries: Base UI, Radix, Aria, Ark
  • From a button to a date picker, a color picker or a guided tour: accessible, typed in TypeScript, each with live demos.Components: All 174 components
  • Real-world patterns built from the components, in 53 galleries: forms, tables, menus, dialogs and more.Examples: All 1,103 examples
  • Area, bar, line, pie, radar and radial charts on TanStack Charts, on every framework. React also gets the Recharts originals.Charts: All 70 charts
  • Debounce, local storage, media queries and more: each hook is one typed file you own.React hooks: All 35 hooks
  • From 222 libraries, Lucide, Heroicons, Tabler and Material Symbols among them, as SVG or a React component in one command.Icons: 294k+ icons
  • Stripe, Linear, Apple and 497 more: a brand's colors, typography and components in one file your AI agent builds from.DESIGN.md files: All 500 brands
  • Restyle every component and block at once: 8 styles, 7 grays, 18 colors and 5 radii, shared as a shadcn preset code.Theme builder: 8 styles × 18 colors
  • Priority requests are answered first.Support: Standard

Team

Most popular

For freelancers, agencies & startups

$66instead of $99/mo

$789 billed yearly · ≈ $13/dev/mo

Everything in Individual, plus

  • How many people can use the license.Seats: Up to 5 seats
  • Client work, SaaS products and anything you charge for.Commercial use: Included
  • Priority requests are answered first.Support: Priority

Organization

For companies with larger teams

$132instead of $199/mo

$1,589 billed yearly

Everything in Team, plus

  • How many people can use the license.Seats: Unlimited seats
  • Secure checkout via Stripe
  • Code lives in your repo
  • Keep what you've shipped if you cancel
  • License terms

Stripe Payments prompt FAQ

What the Stripe Payments prompt covers and how to use it in your agent.

Does the Stripe Payments prompt work with embedded Checkout and Stripe Elements?

Yes. Hosted Checkout is the default, embedded Checkout uses ui_mode embedded_page with a return_url and the client secret, and a custom form uses the Payment Element backed by a Checkout Session with ui_mode elements. The prompt keeps the agent away from the legacy Card Element and hand-built card forms.

How does the Stripe Payments prompt prevent double charges?

Idempotency keys on create calls, derived from the attempt, so a double click or a retried request returns the first result. Fulfillment is one function that is safe to run twice, and each webhook event id is recorded once. Prices and amounts are always looked up on the server, never taken from the browser.

Why doesn't the Stripe Payments prompt pass payment_method_types?

Because API version 2026-09-30, which the stripe 23 SDK pins, removed it from Checkout Sessions. Payment methods come from the Dashboard instead, so Stripe shows each customer the eligible ones, and the agent narrows them with excluded_payment_method_types when it must.

Does the Stripe Payments prompt set up Stripe Tax?

It turns on automatic_tax and has the agent say plainly that Stripe collects nothing until the account has an active registration in the customer's jurisdiction and products have tax codes. It also keeps manual tax rates off the same object and saves the checkout address for returning customers.

4.9 out of 5 from 150+ developers

Rules teach it. The MCP equips it.

Every component, block and icon, installed by your AI agent on your stack. The prompts stay free.

Get Pro
  • Cancel anytime
  • Keep what you've shipped