Stripe Integration Guide

Technology: stripe · Category: payments · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/stripe

Insight:

Stripe is codeAmani's default payment rail. The US-first customer base pays by card and wallet, and Checkout Sessions is Stripe's recommended API for almost everything, including custom forms (Elements with Checkout Sessions). M-Pesa (Daraja) is a separate rail used only for Kenya-targeted projects. Pin apiVersion: "2026-09-30.endive" (stripe@23), never send payment_method_types (Endive returns 400), verify every webhook signature, and pass an idempotency key on every state-changing create call.

███████╗████████╗██████╗ ██╗██████╗ ███████╗
██╔════╝╚══██╔══╝██╔══██╗██║██╔══██╗██╔════╝
███████╗   ██║   ██████╔╝██║██████╔╝█████╗
╚════██║   ██║   ██╔══██╗██║██╔═══╝ ██╔══╝
███████║   ██║   ██║  ██║██║██║     ███████╗
╚══════╝   ╚═╝   ╚═╝  ╚═╝╚═╝╚═╝     ╚══════╝

Stripe Integration Guide

Focus: Checkout, Billing, Tax, Connect and webhooks. Stripe is codeAmani's default payment rail for its US-first customer base.

Overview

Stripe handles card, wallet, bank and stablecoin payments: one-time charges, subscriptions and usage-based billing, invoicing, sales tax, and marketplace payouts through Connect. Per CLAUDE.md, Stripe is the default payment rail for every codeAmani project. M-Pesa via the Daraja API is a separate rail used only when a project's primary users are in Kenya (see MPESA_PATTERNS.md). The two are per-project alternatives, not a primary/secondary pair.

The payment lifecycle is a predictable loop. The webhook, not the browser redirect, is what fulfils:

flowchart LR
  A["Your server<br/>creates Checkout Session"] --> B["Customer pays<br/>hosted page or Elements"]
  B --> C["Stripe sends<br/>signed event"]
  C --> D["Your server<br/>verifies signature"]
  D --> E["Dedupe event id<br/>then fulfil once"]

What changed in this review (2026-10-20)

Area Was (2026-08-23) Now
API version 2026-07-29.dahlia 2026-09-30.endive (new breaking release)
stripe (node) 22.5.0 23.0.0 (Node ≥ 20)
@stripe/stripe-js / @stripe/react-stripe-js 9.14.0 / 6.8.2 10.1.0 / 7.0.0 (React 19 required)
@stripe/cli 1.50.4 1.54.1
payment_method_types "never pass it" (a rule) Removed from the API: 400 on Checkout Sessions, PaymentIntents, SetupIntents. Use allowed_payment_method_types
Custom payment form PaymentIntent + Payment Element Elements with Checkout Sessions (ui_mode: "elements") is Stripe's recommendation
Webhooks Snapshot events only Thin events recommended for new integrations; GA for v1 resources; EventNotificationHandler
constructEvent tolerance 0 Used default tolerance Disables the timestamp check
MCP auth OAuth or any restricted key OAuth, or an agent-tagged restricted key. Full sk_ and untagged rk_ keys stop working on the MCP after 2026-11-30
Payment Request Button Supported Removed in Endive; use Express Checkout Element
Usage-based billing Meters API Metronome is Stripe's recommendation for new builds; Meters still supported

API versioning — pin it explicitly

Stripe uses a flora-named release model: YYYY-MM-DD.codename. A new codename means breaking changes; monthly releases inside a codename are additive only.

Release First version Latest monthly (2026-10-20)
Basil 2025-03-31.basil 2025-08-27.basil
Clover 2025-09-30.clover 2026-02-25.clover
Dahlia 2026-03-25.dahlia 2026-08-26.dahlia
Endive (current) 2026-09-30.endive 2026-09-30.endive

stripe-node 23.0.0 ships ApiVersion = '2026-09-30.endive' (src/apiVersion.ts on master). Always pin the version in code. If you inherit the account default, a Dashboard upgrade silently changes the shapes your code parses.

// lib/stripe.ts
import Stripe from "stripe";

export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2026-09-30.endive",
});

A version string must include the codename. "2026-09-30" on its own is not a valid Stripe API version. Preview features (Shared Payment Tokens, some Accounts v2 fields) use 2026-09-30.preview per request, not as your pinned default.

Endive breaking changes that affect our code

Full list: reference/endive-migration-cheatsheet.md and https://docs.stripe.com/changelog/endive.

Change What to do
payment_method_types removed from Checkout Session create, PaymentIntent create/update/confirm, SetupIntent create/update (400 payment_method_types_no_longer_supported) Delete it. Use Dashboard dynamic payment methods, or allowed_payment_method_types (incompatible types are silently filtered) / excluded_payment_method_types
Terminal's payment_method_types: ['card_present'] Use allowed_payment_method_types: ['card_present']
Elements paymentMethodTypes option throws Use allowedPaymentMethodTypes
Payment Request Button throws (elements.create('paymentRequestButton')) Migrate to the Express Checkout Element
billing_cycle_anchor on subscription update/resume is now an object { type: "now" } / { type: "unchanged" }
v2 Account Links lose use_case.account_onboarding.configurations Remove it
Accounts v2 capabilities gain a rejected status; requirement errors now include eventually-due items Handle rejected as terminal; don't treat every error as blocking

Earlier breaking changes still worth knowing

Change Release What to do
latest_invoice.payment_intent replaced by latest_invoice.confirmation_secret Basil+ Expand latest_invoice.confirmation_secret for incomplete subscriptions
Checkout creates the subscription only after payment Basil Don't assume it exists before checkout.session.completed
Flexible billing mode is the default for new subscriptions Clover Set billing_mode: { type: "flexible" } explicitly (required for pause)
Legacy Stripe.js methods removed (handleCardPayment, confirmPaymentIntent, handleCardSetup, createSource…) Dahlia Use checkout.confirm() (Checkout Sessions) or stripe.confirmPayment() (PaymentIntents)
initCheckout → initCheckoutElementsSdk Dahlia Rename

stripe-node 23.0.0 SDK changes


Choosing the integration

Stripe's own guidance (docs.stripe.com/payments/online-payments): use the Checkout Sessions API for most integrations. PaymentIntents is a lower-level API where you rebuild tax, discounts, shipping, subscriptions and currency conversion yourself. Some features (Adaptive Pricing) only exist on Checkout Sessions.

Building… Use ui_mode
One-time payment, fastest path Checkout Sessions, full page (recommended) hosted_page (default) or embedded_page
Payment form embedded in our page Checkout Sessions, embedded form form
Fully custom UI (our CSS, our layout) Elements with Checkout Sessions + Payment Element elements
Subscriptions Checkout Sessions mode: "subscription" + Customer Portal any
Save a card for later Checkout mode: "setup" or SetupIntents —
Own every part of checkout (rare) PaymentIntents + Payment Element —
No website / one-off sales Payment Links —
Marketplace (Vertiq) Connect, Accounts v2, direct charges —
Usage-based billing, new build Metronome (Stripe's recommendation) or Billing Meters —
Sales tax Stripe Tax (automatic_tax) after a registration exists —
Accept USDC from customers Turn on stablecoin payments in the Dashboard —
Selling to / paying from AI agents Agentic commerce: Shared Payment Tokens, Link Agent Wallet —
Checkout Sessions Payment Intents
Built-in Stripe Tax, discounts, shipping, subscriptions, Adaptive Pricing, address collection, receipts All of that is yours to build
Hosted page, embedded form, or Elements Elements only
Expires after 24 h by default (30 min–24 h via expires_at) No automatic expiry
Webhooks for the whole checkout lifecycle Payment status events only

Environments — sandboxes vs live

Payments made in a sandbox are never processed by card networks. Stripe now recommends general sandboxes for new integrations, with separate sandboxes for local development and CI, over the legacy "test mode" sandbox.

flowchart TB
  subgraph SB["Sandbox · no real money"]
    S1["sk_test_ / rk_test_ / pk_test_"]
    S2["Test cards 4242…"]
    S3["stripe listen → whsec_ (sandbox)"]
  end
  subgraph LV["Live · real money"]
    L1["rk_live_ / pk_live_"]
    L2["Real cards"]
    L3["Event destination → whsec_ (live)"]
  end
  SB -.->|"promote after testing"| LV
# Coding agents: provision an anonymous sandbox with working keys
npm i -g @stripe/cli
stripe sandbox create --help

Sandbox limitations that matter to us:

Limitation Impact
Can't test IC+ pricing Cost models must use published rates
Can't connect a platform sandbox to connected-account sandboxes Vertiq's Connect flow can't be tested sandbox-to-sandbox end to end. Plan a live pilot with a cooperating first seller

Test clocks (Billing "Simulations")

Use test clocks to move subscriptions through time: renewals, trial ends, failed renewals, plan changes mid-cycle. Create a clock (POST /v1/test_helpers/test_clocks with frozen_time), attach a customer with test_clock, then advance with /advance. You can advance up to two billing intervals at a time (two months for a monthly price). customers.list hides clock-attached customers unless you pass test_clock. Listen for test_helpers.test_clock.ready before asserting. Keep CI clocks in the CI sandbox.

Going live

  1. Swap sandbox keys for live keys (via Hazina live references).
  2. Create the production event destination in Workbench → Webhooks and use its whsec_.... The stripe listen secret is sandbox-only.
  3. Re-check apiVersion is pinned.
  4. Run one real low-value transaction and refund it.
  5. Walk https://docs.stripe.com/get-started/checklist/go-live.

Keys

Keys are environment-scoped. A sandbox key can never touch live objects (the usual cause of No such payment_intent).

Key Prefix Where it lives Notes
Publishable pk_test_ / pk_live_ Browser (safe) Identifies the account to Stripe.js
Restricted (RAK) rk_test_ / rk_live_ Server / CI Stripe now recommends RAKs instead of secret keys for new use cases
Restricted, agent-tagged rk_... with Agent badge Agents, MCP Subject to approval rules (payouts, refunds, config changes need a reviewer)
Secret sk_test_ / sk_live_ Server only Unrestricted. Stripe "doesn't recommend" for new use cases
Organization sk_org_... Server Multi-account orgs
Webhook signing secret whsec_ Server only Per destination; not an API key

Rules we follow:


Secrets management with Hazina

codeAmani stores Stripe credentials in Hazina, the local encrypted vault (packages/hazina), not in loose .env files. The agent workflow is zero-exposure: Claude handles references and env-var names only, never values.

Catalog the secrets once (the user runs these; values go into a hidden prompt):

hazina add stripe/secret_key       --type apikey   # rk_ preferred
hazina add stripe/publishable_key  --type apikey
hazina add stripe/webhook_secret   --type apikey
hazina add stripe/agent_key        --type apikey   # agent-tagged rk_ for MCP

Bind a project's env vars to those references, then inject:

hazina bind <project> --path <projectDir> \
  --add STRIPE_SECRET_KEY=stripe/secret_key \
  --add NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=stripe/publishable_key \
  --add STRIPE_WEBHOOK_SECRET=stripe/webhook_secret

hazina inject <project>          # writes gitignored .env.local; reports key NAMES only
hazina push <project> --provider vercel --target production

SDK setup

npm install stripe@23                                         # server — 23.0.0, Node >= 20
npm install @stripe/stripe-js@10 @stripe/react-stripe-js@7    # client — 10.1.0 / 7.0.0 (React 19)

Load Stripe.js from js.stripe.com (the npm loadStripe loader does this). Don't bundle or self-host it; that breaks PCI scope. Stripe.js is versioned per release: https://js.stripe.com/endive/stripe.js.


Core patterns

1. Hosted Checkout (default)

Full file: examples/checkout-session.ts.

// app/api/checkout/route.ts
const session = await stripe.checkout.sessions.create(
  {
    mode: "payment",
    line_items: [{ price: priceId, quantity: 1 }],   // or price_data, amounts in cents
    success_url: `${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/pricing`,
    metadata: { userId, orderId },
    integration_identifier: "codeamani_hosted_0001",
    // NO payment_method_types — removed in Endive (400)
  },
  { idempotencyKey: `checkout_${orderId}` },
);
return Response.json({ url: session.url });

2. Custom form: Elements with Checkout Sessions

Stripe's recommended custom UI. The server returns the session's client_secret; the client initialises Checkout with it and confirms with checkout.confirm() (not stripe.confirmPayment). Full files: examples/checkout-elements-session.ts and examples/CheckoutElementsForm.tsx.

// server
const session = await stripe.checkout.sessions.create({
  ui_mode: "elements",
  mode: "payment",
  line_items: [{ price_data: { currency: "usd", unit_amount: 2000,
    product_data: { name: "codeAmani Pro" } }, quantity: 1 }],
  return_url: `${process.env.APP_URL}/return?session_id={CHECKOUT_SESSION_ID}`,
});
return Response.json({ client_secret: session.client_secret });
// client — note the /checkout entry point
import { CheckoutElementsProvider, PaymentElement, useCheckoutElements }
  from "@stripe/react-stripe-js/checkout";

const state = useCheckoutElements();          // { type: "loading" | "error" | "success" }
if (state.type === "success") {
  await state.checkout.confirm();             // disable Pay while !state.checkout.canConfirm
}
// <CheckoutElementsProvider stripe={stripePromise} options={{ clientSecret }}>

Without React: stripe.initCheckoutElementsSdk({ clientSecret }), then checkout.createPaymentElement().mount("#payment-element") and (await checkout.loadActions()).actions.confirm().

3. PaymentIntent (only when you must own checkout)

const paymentIntent = await stripe.paymentIntents.create(
  {
    amount: 2000,               // smallest currency unit
    currency: "usd",
    metadata: { userId, orderId },
    // dynamic payment methods are on by default; to restrict:
    // allowed_payment_method_types: ["card"],
  },
  { idempotencyKey: `pi_${orderId}` },
);
return Response.json({ clientSecret: paymentIntent.client_secret });

The client uses <Elements stripe={stripePromise} options={{ clientSecret }}> from @stripe/react-stripe-js and stripe.confirmPayment({ elements, confirmParams: { return_url } }). Don't mix this with the /checkout entry point.


Billing

Full file: examples/billing-subscription.ts.

Subscriptions

Prefer Checkout in mode: "subscription". Set billing_mode explicitly.

const session = await stripe.checkout.sessions.create({
  mode: "subscription",
  customer: customerId,
  line_items: [{ price: priceId, quantity: 1 }],
  automatic_tax: { enabled: true },             // only with an active registration
  customer_update: { address: "auto" },
  subscription_data: { billing_mode: { type: "flexible" } },
  success_url: `${process.env.APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
  cancel_url: `${process.env.APP_URL}/pricing`,
});

If you build the subscription directly (Elements + Subscriptions API), create it with payment_behavior: "default_incomplete" and expand latest_invoice.confirmation_secret. latest_invoice.payment_intent no longer exists.

New in Endive: pause and resume on demand (stripe.subscriptions.pause(id), flexible billing mode only; stops invoice generation; status paused, events customer.subscription.paused / .resumed). Trial offers are GA. Subscriptions can auto-pause after payment failures.

Customer Portal

Let customers change plans, update cards, view invoices and cancel without us building UI. Configure it in the Dashboard, then:

const portal = await stripe.billingPortal.sessions.create({
  customer: customerId,
  return_url: `${process.env.APP_URL}/account/billing`,
});
// redirect to portal.url

Usage-based billing

await stripe.billing.meterEvents.create({
  event_name: "api_requests",
  payload: { stripe_customer_id: customerId, value: "1" },
  identifier: requestId,    // idempotent on Stripe's side
});
// > 1,000 events/s live: use v2 meter event streams

For codeAmani AI products: Meters is fine for simple per-request pricing that goes through Checkout. Pick Metronome when we need prepaid AI credits or token pass-through.

Stripe Tax


Webhooks and event destinations

Webhooks are the only trustworthy fulfilment signal. Stripe now models delivery as event destinations: webhook endpoints, Amazon EventBridge, or Azure Event Grid. You create them in Workbench → Webhooks or with the v2 Event Destinations API. Max 16 destinations per live or sandbox account.

Thin vs snapshot

Snapshot (classic) Thin (recommended for new)
Payload Full Event + object snapshot Type + related_object id only
Versioning Pinned to an API version Unversioned; upgrades don't touch the destination
SDK typing Untyped event.data.object per type Fully typed EventNotification classes
Names checkout.session.completed v1.checkout.session.completed
Get data event.data.object (may be stale) await n.fetchRelatedObject() (latest) / n.fetchEvent()

Thin events for v1 resources went GA in 2026-09-30.endive. A thin destination is a separate endpoint with its own secret. Use snapshot only when a third-party tool needs the full payload, or you need previous_attributes without a fetch.

sequenceDiagram
  participant ST as "Stripe"
  participant S as "Your route"
  participant DB as "Database"
  ST->>S: POST thin notification (signed)
  S->>S: handler.handle(rawBody, signature)
  S->>DB: preHandle — insert event id if new
  S->>ST: fetchRelatedObject()
  ST-->>S: latest Checkout Session
  S->>DB: fulfil once
  S-->>ST: 2xx

Thin event handler (stripe-node 23)

Full file: examples/thin-events-webhook.ts.

const handler = stripe.notificationHandler(
  process.env.STRIPE_THIN_WEBHOOK_SECRET!,
  async (unhandled) => { /* log unknown types */ },
);
handler.preHandle(async (n) => markProcessedIfNew(n.id));   // false = skip (dedupe)
handler.on("v1.checkout.session.completed", async (n) => {
  const session = await n.fetchRelatedObject();
  if (session.payment_status === "paid") await fulfil(session.metadata?.orderId);
});

export async function POST(req: Request) {
  const sig = req.headers.get("stripe-signature");
  if (!sig) return new Response("Missing signature", { status: 400 });
  try { await handler.handle(await req.text(), sig); }
  catch { return new Response("Invalid", { status: 400 }); }
  return new Response("OK");
}

One-off parse without the class: stripe.parseEventNotification(body, sig, secret). For EventBridge/Event Grid deliveries (no signature header) use stripe.notificationHandlerWithoutVerification(...).

Snapshot handler (existing integrations)

Full file: examples/webhook.ts.

// app/api/webhooks/stripe/route.ts
export const runtime = "nodejs";               // Node crypto; not Edge

export async function POST(req: NextRequest) {
  const body = await req.text();               // RAW body — never req.json()
  const signature = req.headers.get("stripe-signature");
  if (!signature) return new Response("Missing signature", { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
    // never pass tolerance 0 — in stripe@23 that DISABLES replay protection
  } catch {
    return new Response("Webhook signature verification failed", { status: 400 });
  }
  if (await alreadyProcessed(event.id)) return new Response("OK");

  switch (event.type) {
    case "checkout.session.completed":
      if (event.data.object.payment_status === "paid") { /* fulfil */ }
      break;
    case "checkout.session.async_payment_succeeded": /* delayed methods */ break;
    case "customer.subscription.deleted":
    case "customer.subscription.paused": /* revoke access */ break;
    case "invoice.payment_failed": /* notify */ break;
  }
  return new Response("OK");
}

Delivery facts: live retries for up to 3 days with exponential backoff (sandbox: 3 tries over a few hours); manual resend from the Dashboard for 15 days; Express must register express.json() after the webhook route. Return 2xx fast and queue slow work.

Events to handle at minimum: checkout.session.completed, checkout.session.async_payment_succeeded / _failed, customer.subscription.created / .updated / .deleted / .paused / .resumed, invoice.paid, invoice.payment_failed. Connect adds account.updated (or the v2 thin v2.core.account... events).


Idempotency & reconciliation

Pass an idempotency key on every state-changing create call, and dedupe webhook events on their id. Stripe stores the first result under the key, so a retry returns the original object instead of charging twice. Generate one stable key per logical operation (order, cart), not per HTTP attempt.

const session = await stripe.checkout.sessions.create(params, {
  idempotencyKey: `checkout_${orderId}`,   // RequestOptions — last argument
});
flowchart TD
  A["Create with<br/>idempotencyKey"] --> B{"Key seen<br/>before"}
  B -->|"yes"| C["Original object<br/>no new charge"]
  B -->|"no"| D["New object"]
  D --> E["Event arrives"]
  C --> E
  E --> F{"event id<br/>already processed"}
  F -->|"yes"| G["Skip"]
  F -->|"no"| H["Record id<br/>then fulfil once"]

Keys expire after 24 hours: they protect against retries, not a deliberate re-charge the next day. Meter events use their own identifier for the same job.


Connect — marketplaces (Vertiq.market)

Vertiq is a multi-party marketplace: independent sellers list digital goods, buyers pay, Vertiq takes a commission. The requirement: sellers receive the payments and are responsible for them; Vertiq is not the party handling the money. That maps to Connect direct charges onto seller-owned accounts created with Accounts v2.

flowchart LR
  B["Buyer"] -->|"pays"| SA["Seller account<br/>(merchant of record)"]
  SA -->|"application_fee_amount"| V["Vertiq platform<br/>(commission only)"]
  SA -->|"payout"| SB["Seller bank"]
  SA -.->|"refunds · chargebacks<br/>debit THIS balance"| SA
Property Direct charges (Vertiq) Destination charges (rejected)
Funds land in Seller balance Platform balance
Merchant of record Seller Platform
Refunds / chargebacks debit Seller Platform
Platform revenue application_fee_amount Amount retained

1. Create the seller (Accounts v2)

Accounts v2 uses configurations: merchant (accept payments; holds card_payments and stripe_balance.payouts), customer (charge the account like a Customer), recipient (receive transfers). v2 responses return null for fields you don't include. Full file: examples/connect-onboard-seller.ts.

const account = await stripe.v2.core.accounts.create({
  contact_email: sellerEmail,
  display_name: sellerName,
  dashboard: "full",                                 // seller self-serves refunds/disputes
  identity: { country: "us" },
  configuration: { merchant: { capabilities: { card_payments: { requested: true } } } },
  defaults: {
    currency: "usd",
    responsibilities: {
      losses_collector: "stripe",                    // Stripe, not Vertiq, bears seller losses
      fees_collector: "stripe",                      // seller pays Stripe fees directly
    },
  },
  include: ["configuration.merchant", "requirements"],
});

defaults.responsibilities can't be changed after creation, and the country is fixed. Get the first seller right.

2. Onboard (Stripe-hosted, Stripe runs KYC)

const link = await stripe.v2.core.accountLinks.create({
  account: account.id,
  use_case: {
    type: "account_onboarding",
    account_onboarding: {                            // no `configurations` since Endive
      refresh_url: `${process.env.APP_URL}/sellers/onboarding/refresh`,
      return_url: `${process.env.APP_URL}/sellers/onboarding/complete`,
    },
  },
});

v1 stripe.accountLinks.create({ account, type: "account_onboarding", ... }) also accepts a v2 account id (Stripe's hosted-onboarding page still shows the v1 call).

Gate listings on the capability:

const acct = await stripe.v2.core.accounts.retrieve(sellerAccountId, {
  include: ["configuration.merchant"],
});
const canSell = acct.configuration?.merchant?.capabilities?.card_payments?.status === "active";
// Endive adds "rejected" — show it, don't retry forever

3. Direct charge with commission

The seller's account id goes in the request options. Full file: examples/connect-direct-charge.ts.

const session = await stripe.checkout.sessions.create(
  {
    mode: "payment",
    line_items: [{ price: listing.stripePriceId, quantity: 1 }],
    payment_intent_data: { application_fee_amount: Math.round(listing.amount * 1000 / 10_000) },
    success_url: `${process.env.APP_URL}/orders/{CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.APP_URL}/listings/${listing.id}`,
  },
  { stripeAccount: seller.stripeAccountId, idempotencyKey: `order_${orderId}` },
);

4. Connect events

Create an event destination scoped to Connected accounts to receive direct-charge events (they carry event.account / the context). For Accounts v2 lifecycle changes, also add a destination for Your account with thin v2.core.account... events. Locally: stripe listen --forward-connect-to … or --forward-thin-connect-to … --thin-events "*".

What Vertiq is still responsible for

Payment liability and marketplace structure have legal and tax consequences. Confirm the design with counsel and Stripe's Connect team before launch. This guide documents the technical mechanism, not legal advice.


Stablecoin payments

Accepting USDC through Stripe needs no wallet code and no key custody. Turn on the stablecoin payment method in Dashboard → Settings → Payment methods; it then appears in Checkout, Elements, Payment Links, Invoicing and Billing (subscriptions included) via dynamic payment methods.

Fact (docs.stripe.com/crypto/stablecoin-payments, 2026-10-20) Value
Accepted tokens USDC on Tempo, Ethereum, Solana, Polygon, Base; USDP (Ethereum, Solana; US-only); USDG (Ethereum; US-only)
Presentment currency USD (others in private preview)
Settlement Your Stripe balance, in your local currency
Who can accept US businesses; EU, HK, MX, CH in private preview
Per-transaction limit 10,000 USD
Disputes / chargebacks None (customer authenticates the payment)
Refunds Yes, partial too. Always returned as stablecoins to the original wallet
Manual capture Not supported
Connect All charge types; connected account needs crypto_payments capability (full-Dashboard sellers enable it themselves)
Price (US page) 1.5% of the transaction in USD, including conversion, AML screening and gas

Customers are redirected to crypto.stripe.com to pick a token and network and connect a wallet. Because settlement can be delayed, fulfil on payment_status === "paid" or checkout.session.async_payment_succeeded, not on redirect. On-chain work beyond acceptance (payouts to wallets, on-chain records) belongs in the blockchain/ guide.


Agents: MCP server, plugin, skills, toolkit

npm install -g @stripe/cli@latest
stripe agent setup     # detects Claude Code / Cursor / Codex…; installs MCP + skills, auto-updates

Manual alternative: npx skills add https://docs.stripe.com (no auto-update; run npx skills update -y). Skills index: https://docs.stripe.com/.well-known/skills/index.json.

Stripe MCP server (remote)

claude mcp add --transport http stripe https://mcp.stripe.com/
# then in Claude Code: /mcp  → OAuth consent

Headless agents that can't do OAuth: an agent API key (agent-tagged restricted key) as a bearer token, read from an env var:

{
  "mcpServers": {
    "stripe": {
      "type": "http",
      "url": "https://mcp.stripe.com",
      "headers": { "Authorization": "Bearer ${STRIPE_AGENT_API_KEY}" }
    }
  }
}

Deadline: 2026-11-30. From December 2026 the Stripe MCP stops accepting full-access secret keys and restricted keys without the Agent tag (401 with an OAuth challenge). Re-issue any MCP key as an agent-tagged key, or use OAuth.

For a Connect platform acting on a connected account, add a Stripe-Account: acct_... header. OAuth isn't supported for connected-account calls, so use an agent key.

Tool Purpose
stripe_api_search, stripe_api_details Find API methods and their parameters
stripe_api_read Any GET
stripe_api_write Any POST/PATCH/PUT/DELETE. Refunds and outbound payments require human confirmation via a URL (expires after 24 h)
search_stripe_documentation Docs + support articles
stripe_implementation_planner Guided integration planning
get_stripe_account_info Account details
stripe_analytics (Preview) metrics, subscription analysis, reports; Sigma SQL
atlas_company_formation Start a Delaware C-corp/LLC formation
Treasury tools (get_balance_summary, send_money, transfer_money, …) Public preview

The old create_refund / stripe_report tools from our previous review are no longer listed; refunds go through stripe_api_write. Keep your client's tool-approval setting on, and be careful combining the Stripe MCP with untrusted content (prompt injection). MCP tool calls are logged in Workbench.

The local npx -y @stripe/mcp (0.3.3) stdio server still exists for offline use, but the remote server is the documented default.

Agent toolkit (building our own agents)

@stripe/agent-toolkit (0.9.0, repo stripe/ai) exposes Stripe API calls as tools for LangChain, the Vercel AI SDK, and MCP servers. Give it a restricted key; tool availability follows the key's permissions. Use configuration.context.account to act for a connected account. Under codeAmani's AI routing policy, Claude-based agents use it through the AI SDK or MCP adapter.


Agentic commerce

For products where AI agents buy or sell (docs.stripe.com/agentic-commerce):

Treat all of this as opt-in per product. Don't add SPT acceptance to a normal SaaS checkout unless an agent channel is actually in scope.


Test cards

Card number Behaviour
4242 4242 4242 4242 Success
4000 0000 0000 9995 Declined (insufficient funds)
4000 0025 0000 3155 3D Secure required
4000 0000 0000 0002 Generic decline

Any future expiry, any 3-digit CVC. Full matrix: https://docs.stripe.com/testing. In code, prefer test PaymentMethod ids such as pm_card_visa.


Environment variables

Secrets (store in Hazina, never commit):

STRIPE_SECRET_KEY=rk_test_...              # restricted key preferred; sk_ still works
STRIPE_WEBHOOK_SECRET=whsec_...            # snapshot destination
STRIPE_THIN_WEBHOOK_SECRET=whsec_...       # thin destination (separate)
STRIPE_AGENT_API_KEY=rk_test_...           # agent-tagged key, only for MCP/agents

Non-secret settings:

Variable Example Notes
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY pk_test_... Publishable key, browser-safe
STRIPE_PRICE_ID price_... Default subscription price
APP_URL https://app.example.com Used in success/return URLs
STRIPE_SUPPRESS_NOTICES true Optional; silences stripe-node notices in sandbox

The whsec_... printed by stripe listen is sandbox-only. Production uses the signing secret of the live event destination.


Troubleshooting

Issue Fix
400 payment_method_types_no_longer_supported You're on Endive. Remove payment_method_types; use allowed_payment_method_types or the Dashboard
IntegrationError mentioning paymentMethodTypes / paymentRequestButton Endive Stripe.js. Use allowedPaymentMethodTypes / Express Checkout Element
No such payment_intent Sandbox vs live key mismatch
Webhook 400, signature mismatch Use the raw body (req.text()); check you're using the right destination's secret (thin ≠ snapshot)
Replayed old webhooks accepted Someone passed tolerance: 0 (stripe@23 disables the check). Remove it
confirmation_secret undefined Expand latest_invoice.confirmation_secret, not .payment_intent
checkout.confirm is not a function You're inside <Elements>; Checkout-Sessions forms need CheckoutElementsProvider from @stripe/react-stripe-js/checkout
React peer-dependency error on install @stripe/react-stripe-js@7 needs React 19
stripe install fails on Node 18 stripe@23 needs Node ≥ 20
Stripe MCP returns 401 after Nov 2026 Key isn't agent-tagged. Re-issue as an agent key or use OAuth
npm i -g @stripe/stripe-cli 404s The package is @stripe/cli
stripe docs says key expired stripe login again (CLI v1.43.3+)

Stripe developer resources

Resource URL
Docs (append .md for Markdown) https://docs.stripe.com
API reference https://docs.stripe.com/api
Changelog / Endive https://docs.stripe.com/changelog · https://docs.stripe.com/changelog/endive
Upgrades guide https://docs.stripe.com/upgrades
Online payments (Checkout vs PaymentIntents) https://docs.stripe.com/payments/online-payments
Elements with Checkout Sessions https://docs.stripe.com/payments/accept-a-payment?payment-ui=elements&api-integration=checkout
Event destinations / webhooks https://docs.stripe.com/event-destinations · https://docs.stripe.com/webhooks
Billing / usage-based / test clocks https://docs.stripe.com/billing · https://docs.stripe.com/billing/subscriptions/usage-based · https://docs.stripe.com/billing/testing/test-clocks
Connect + Accounts v2 https://docs.stripe.com/connect/accounts-v2
Stablecoin payments https://docs.stripe.com/crypto/stablecoin-payments
MCP / agents / skills https://docs.stripe.com/mcp · https://docs.stripe.com/agents · https://docs.stripe.com/skills
Agentic commerce https://docs.stripe.com/agentic-commerce
Keys https://docs.stripe.com/keys
Pricing https://stripe.com/pricing
stripe-node https://github.com/stripe/stripe-node

Coding agents — rules & best practices

  1. Fetch before you write. stripe docs search "...", the MCP search_stripe_documentation tool, or a .md docs page. Stripe's surface moves every month; training data is stale.
  2. Never send payment_method_types. It's a 400 on Endive. Restrict with allowed_payment_method_types / excluded_payment_method_types, or the Dashboard.
  3. Checkout Sessions first. Reach for PaymentIntents only when the user explicitly needs to own the whole checkout.
  4. Pin apiVersion: "2026-09-30.endive" and keep stripe on 23.x.
  5. Restricted keys, not secret keys, for new server code. Agent-tagged keys for agents and the MCP.
  6. No automatic_tax without an active registration.
  7. Raw body + signature check on every webhook. Never pass tolerance: 0.
  8. Idempotency key on every create; dedupe events on id.
  9. Thin events for new webhook endpoints.
  10. Keep human confirmation on MCP writes. stripe_api_write moves money.
  11. Tag Checkout Sessions with integration_identifier so flows can be compared in the Dashboard.

Version drift warning

Bundled agent skills and this guide carry static version tables that lag the live API. When they disagree, the live source wins:

npm view stripe version
curl -sL https://raw.githubusercontent.com/stripe/stripe-node/master/src/apiVersion.ts

codeAmani notes

Official docs: