← Back to dashboard
stripepaymentsfreshReader view (for NotebookLM)

Stripe Integration Guide

How a Stripe payment works

The real model

Async PaymentIntent → idempotent webhook, signed by Stripe.

Never trust the client's `redirect` callback alone — webhooks are the source of truth. Verify the `Stripe-Signature` header with your webhook secret on every POST; idempotency is on `event.id` (Stripe retries failed deliveries for up to 3 days). 3DS is mandatory under PSD2 for many EU/UK cards — you don't choose, the bank does, and Stripe surfaces it via `next_action.type === "use_stripe_sdk"`. For codeAmani, Stripe is the default rail (US-first); M-Pesa/Daraja applies only to Kenya-targeted projects. Pin `apiVersion` in code — the current release is `2026-09-30.endive` (stripe-node 23) — and never pass `payment_method_types`: Endive removed it and returns 400 (use `allowed_payment_method_types` or Dashboard dynamic payment methods). Prefer Checkout Sessions, even for a custom Payment Element UI, and store the session/PaymentIntent id against your order before the webhook can race you. For new endpoints use thin events (`v1.checkout.session.completed`) and fetch the latest object; never pass `tolerance: 0` to `constructEvent`, which now disables the replay check. ACK 2xx fast; do slow work in a queue.

The five-step lifecycle

Each step has its own failure mode. The 3DS step is the most common silent killer of conversion.

Branch the card response

Real payments don't fail or succeed — they take one of several specific paths, each with its own webhook event and recovery flow. Walk through each and read the terminal note for what your server should do.

PaymentIntent simulatorphase: idle
  1. PaymentIntent
    POST /v1/payment_intents
  2. Confirm card
    stripe.confirmPayment(client_secret)
  3. 3DS challenge
    next_action → use_stripe_sdk
  4. Webhook
    payment_intent.succeeded / .payment_failed
  5. Reconcile
    Verify signature · dedupe event.id · ACK 200

The hidden lesson: even when 3DS fails, a payment_failed webhook still arrives. Your server learns the outcome from Stripe, not from the customer's browser redirect.

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

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:

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

AreaWas (2026-08-23)Now
API version2026-07-29.dahlia2026-09-30.endive (new breaking release)
stripe (node)22.5.023.0.0 (Node ≥ 20)
@stripe/stripe-js / @stripe/react-stripe-js9.14.0 / 6.8.210.1.0 / 7.0.0 (React 19 required)
@stripe/cli1.50.41.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 formPaymentIntent + Payment ElementElements with Checkout Sessions (ui_mode: "elements") is Stripe's recommendation
WebhooksSnapshot events onlyThin events recommended for new integrations; GA for v1 resources; EventNotificationHandler
constructEvent tolerance 0Used default toleranceDisables the timestamp check
MCP authOAuth or any restricted keyOAuth, or an agent-tagged restricted key. Full sk_ and untagged rk_ keys stop working on the MCP after 2026-11-30
Payment Request ButtonSupportedRemoved in Endive; use Express Checkout Element
Usage-based billingMeters APIMetronome 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.

ReleaseFirst versionLatest monthly (2026-10-20)
Basil2025-03-31.basil2025-08-27.basil
Clover2025-09-30.clover2026-02-25.clover
Dahlia2026-03-25.dahlia2026-08-26.dahlia
Endive (current)2026-09-30.endive2026-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.

TypeScript
// 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.

ChangeWhat 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 throwsUse 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.configurationsRemove it
Accounts v2 capabilities gain a rejected status; requirement errors now include eventually-due itemsHandle rejected as terminal; don't treat every error as blocking

Earlier breaking changes still worth knowing

ChangeReleaseWhat to do
latest_invoice.payment_intent replaced by latest_invoice.confirmation_secretBasil+Expand latest_invoice.confirmation_secret for incomplete subscriptions
Checkout creates the subscription only after paymentBasilDon't assume it exists before checkout.session.completed
Flexible billing mode is the default for new subscriptionsCloverSet billing_mode: { type: "flexible" } explicitly (required for pause)
Legacy Stripe.js methods removed (handleCardPayment, confirmPaymentIntent, handleCardSetup, createSource…)DahliaUse checkout.confirm() (Checkout Sessions) or stripe.confirmPayment() (PaymentIntents)
initCheckout → initCheckoutElementsSdkDahliaRename

stripe-node 23.0.0 SDK changes

  • Node.js ≥ 20 (engines: { node: '>=20' }).
  • stripe.webhooks.constructEvent(..., tolerance) with 0 now skips the timestamp check (it used the default before). Never pass 0; omit it to keep the 300-second default. verifyHeader() without a tolerance now enforces the default.
  • The static Stripe.constructEventWithoutVerification() (added by mistake in 22.5.0) is gone. ErrorType export removed; use Stripe.errors.
  • Stalled/truncated responses throw StripeConnectionError, not StripeAPIError.
  • STRIPE_SUPPRESS_NOTICES=true silences SDK notices in test/sandbox (they still show when an AI agent is detected).
  • 22.6.2: empty webhook secrets now throw. 22.6.1: hardened request URLs.

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…Useui_mode
One-time payment, fastest pathCheckout Sessions, full page (recommended)hosted_page (default) or embedded_page
Payment form embedded in our pageCheckout Sessions, embedded formform
Fully custom UI (our CSS, our layout)Elements with Checkout Sessions + Payment Elementelements
SubscriptionsCheckout Sessions mode: "subscription" + Customer Portalany
Save a card for laterCheckout mode: "setup" or SetupIntents—
Own every part of checkout (rare)PaymentIntents + Payment Element—
No website / one-off salesPayment Links—
Marketplace (Vertiq)Connect, Accounts v2, direct charges—
Usage-based billing, new buildMetronome (Stripe's recommendation) or Billing Meters—
Sales taxStripe Tax (automatic_tax) after a registration exists—
Accept USDC from customersTurn on stablecoin payments in the Dashboard—
Selling to / paying from AI agentsAgentic commerce: Shared Payment Tokens, Link Agent Wallet—
Checkout SessionsPayment Intents
Built-in Stripe Tax, discounts, shipping, subscriptions, Adaptive Pricing, address collection, receiptsAll of that is yours to build
Hosted page, embedded form, or ElementsElements only
Expires after 24 h by default (30 min–24 h via expires_at)No automatic expiry
Webhooks for the whole checkout lifecyclePayment 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.

Bash
# Coding agents: provision an anonymous sandbox with working keys
npm i -g @stripe/cli
stripe sandbox create --help

Sandbox limitations that matter to us:

LimitationImpact
Can't test IC+ pricingCost models must use published rates
Can't connect a platform sandbox to connected-account sandboxesVertiq'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).

KeyPrefixWhere it livesNotes
Publishablepk_test_ / pk_live_Browser (safe)Identifies the account to Stripe.js
Restricted (RAK)rk_test_ / rk_live_Server / CIStripe now recommends RAKs instead of secret keys for new use cases
Restricted, agent-taggedrk_... with Agent badgeAgents, MCPSubject to approval rules (payouts, refunds, config changes need a reviewer)
Secretsk_test_ / sk_live_Server onlyUnrestricted. Stripe "doesn't recommend" for new use cases
Organizationsk_org_...ServerMulti-account orgs
Webhook signing secretwhsec_Server onlyPer destination; not an API key

Rules we follow:

  • Never prefix a secret with NEXT_PUBLIC_. Only the publishable key is public.
  • New server integrations: create a restricted key with only the resources the app uses and put it in STRIPE_SECRET_KEY (stripe-node accepts either prefix).
  • Agents, MCP clients, CI: an agent-tagged restricted key (create a restricted key and pick "Authorizing agent access to your account").
  • Rotate immediately on suspected exposure (Dashboard → API keys → rotate).

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):

Bash
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:

Bash
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
  • Use the hazina-wire skill; it encodes the zero-exposure rules.
  • Never cat .env.local back into context; never hazina get --reveal.
  • Keep separate references for sandbox and live keys.
  • hazina audit flags stale keys; rotate with hazina rotate stripe/secret_key.

SDK setup

Bash
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.

TypeScript
// 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.

TypeScript
// 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 });
TSX
// 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)

TypeScript
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.

TypeScript
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:

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

Usage-based billing

  • New build → Metronome. Stripe acquired Metronome and now calls it "the recommended starting point for all new integrations" (credits, commits, dimensional pricing, real-time usage). It's a separate account and API (signup.metronome.com). It also powers LLM token billing (public preview): Stripe syncs OpenAI/Anthropic/Google model prices and you set the markup.
  • Basic usage-based billing (Billing Meters) stays fully supported and has fuller compatibility with Checkout, Connect and Adaptive Pricing:
TypeScript
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

  • automatic_tax: { enabled: true } on Checkout / Invoices / Subscriptions.
  • Never enable it without an active tax registration. Stripe then calculates and collects no tax while the integration looks correct. Create registrations in the Dashboard or with the Registrations API first.
  • Products need a tax_code (or the account default). Endive adds a breaking "Failed Tax Calculation" error (Checkout, Billing, Invoicing) and new US tax types (admissions, gross receipts, digital excise…).
  • Pricing: Tax Basic 0.5% per transaction where registered (no-code) or $0.50 per API transaction; Tax Complete from $90/month (see reference/limits-and-pricing.md).

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)
PayloadFull Event + object snapshotType + related_object id only
VersioningPinned to an API versionUnversioned; upgrades don't touch the destination
SDK typingUntyped event.data.object per typeFully typed EventNotification classes
Namescheckout.session.completedv1.checkout.session.completed
Get dataevent.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.

Thin event handler (stripe-node 23)

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

TypeScript
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.

TypeScript
// 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.

TypeScript
const session = await stripe.checkout.sessions.create(params, {
  idempotencyKey: `checkout_${orderId}`,   // RequestOptions — last argument
});

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.

PropertyDirect charges (Vertiq)Destination charges (rejected)
Funds land inSeller balancePlatform balance
Merchant of recordSellerPlatform
Refunds / chargebacks debitSellerPlatform
Platform revenueapplication_fee_amountAmount 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.

TypeScript
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)

TypeScript
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:

TypeScript
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.

TypeScript
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

  • Negative balances on its own platform account.
  • The Stripe Connect platform agreement (prohibited businesses, conduct).
  • Tax on commission revenue; sellers handle tax on their sales.
  • A live-mode pilot (sandboxes can't link platform and connected sandboxes).
  • Telling sellers plainly that refunds and chargebacks come out of their balance.

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 tokensUSDC on Tempo, Ethereum, Solana, Polygon, Base; USDP (Ethereum, Solana; US-only); USDG (Ethereum; US-only)
Presentment currencyUSD (others in private preview)
SettlementYour Stripe balance, in your local currency
Who can acceptUS businesses; EU, HK, MX, CH in private preview
Per-transaction limit10,000 USD
Disputes / chargebacksNone (customer authenticates the payment)
RefundsYes, partial too. Always returned as stablecoins to the original wallet
Manual captureNot supported
ConnectAll 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

Bash
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)

Bash
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:

JSON
{
  "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.

ToolPurpose
stripe_api_search, stripe_api_detailsFind API methods and their parameters
stripe_api_readAny GET
stripe_api_writeAny POST/PATCH/PUT/DELETE. Refunds and outbound payments require human confirmation via a URL (expires after 24 h)
search_stripe_documentationDocs + support articles
stripe_implementation_plannerGuided integration planning
get_stripe_account_infoAccount details
stripe_analytics(Preview) metrics, subscription analysis, reports; Sigma SQL
atlas_company_formationStart 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):

  • Shared Payment Tokens (SPTs): an agent grants a seller a scoped, expiring, amount-limited credential (spt_...) for the customer's payment method. The seller confirms a PaymentIntent with payment_method_data[shared_payment_granted_token]. The API is on the preview version (Stripe-Version: 2026-09-30.preview). Available in the US, Canada and most of Europe. $0.15 per SPT issued. Sandbox test helper: POST /v1/test_helpers/shared_payment/granted_tokens. Live test: npx @stripe/link-cli.
  • Link Agent Wallet: give our agent a wallet to pay online.
  • Sell to agents: catalog feeds, Universal Commerce Protocol (UCP), and machine payments (Machine Payments Protocol, x402) for charging per tool call or HTTP request.
  • Stripe Directory: index of businesses and services that agents can search.

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 numberBehaviour
4242 4242 4242 4242Success
4000 0000 0000 9995Declined (insufficient funds)
4000 0025 0000 31553D Secure required
4000 0000 0000 0002Generic 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):

Bash
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:

VariableExampleNotes
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYpk_test_...Publishable key, browser-safe
STRIPE_PRICE_IDprice_...Default subscription price
APP_URLhttps://app.example.comUsed in success/return URLs
STRIPE_SUPPRESS_NOTICEStrueOptional; 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

IssueFix
400 payment_method_types_no_longer_supportedYou're on Endive. Remove payment_method_types; use allowed_payment_method_types or the Dashboard
IntegrationError mentioning paymentMethodTypes / paymentRequestButtonEndive Stripe.js. Use allowedPaymentMethodTypes / Express Checkout Element
No such payment_intentSandbox vs live key mismatch
Webhook 400, signature mismatchUse the raw body (req.text()); check you're using the right destination's secret (thin ≠ snapshot)
Replayed old webhooks acceptedSomeone passed tolerance: 0 (stripe@23 disables the check). Remove it
confirmation_secret undefinedExpand latest_invoice.confirmation_secret, not .payment_intent
checkout.confirm is not a functionYou'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 18stripe@23 needs Node ≥ 20
Stripe MCP returns 401 after Nov 2026Key isn't agent-tagged. Re-issue as an agent key or use OAuth
npm i -g @stripe/stripe-cli 404sThe package is @stripe/cli
stripe docs says key expiredstripe login again (CLI v1.43.3+)

Stripe developer resources


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:

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

codeAmani notes

  • Default rail. Stripe is the payment rail for every codeAmani project unless the project's primary users are in Kenya, in which case M-Pesa/Daraja applies instead (MPESA_PATTERNS.md, AFRICAN_MARKET_GUIDE.md). Stablecoin acceptance through Stripe doesn't change that. A Kenya-targeted project still defaults to M-Pesa.
  • Secrets stay server-side. STRIPE_SECRET_KEY, the webhook secrets and agent keys are never NEXT_PUBLIC_. Only the publishable key reaches the browser. Secrets live in Hazina → .env.local / Vercel env vars (ENV_MASTER.md, SECURITY.md).
  • Verify every webhook before acting. An unauthenticated POST to a webhook route is trivial to forge.
  • AI routing. Agents that touch Stripe follow the AI routing policy (Claude for reasoning/code gen). Give them an agent-tagged restricted key with the narrowest permissions, and keep Stripe's approval rules on for refunds and payouts.
  • Pin apiVersion in code so a Dashboard upgrade can't reshape what handlers parse.
  • Amounts are integers in the smallest currency unit, the same discipline as Daraja's integer-KES rule.
  • Vertiq keeps Connect direct charges on Accounts v2 with losses_collector/fees_collector = "stripe". Still correct under Endive. Only the v2 Account Link configurations parameter and the new rejected capability status needed changes.
  • African-market note. For Kenya-targeted projects Stripe is not the default, and Stripe's stablecoin acceptance is limited to US businesses (EU/HK/MX/CH preview). It's not a way to collect from Kenyan customers in place of M-Pesa.