# Stripe

Taking payments, running subscriptions and paying sellers with
[Stripe](https://stripe.com), from the back end, with no package and no
script of Stripe's in the page. An [extension](../extensions/README.md):
ordinary Mote in `extensions/stripe/`, over [`net.send`](data.md#netsend)
(a form with bracket keys, the key as a bearer, an idempotency key, tries
again on 429 and 5xx), [`secret`](back-end.md#secrets), a
[route](back-end.md#routes) for Stripe's events and a
[`job fn`](back-end.md#later-job-fn) that does them. Back to the
[map](README.md).

**None of this has met the real Stripe.** Every call was written from
Stripe's API reference, as of 2026, for the API version pinned here
(`2024-06-20`), and run against a stand-in that speaks its shape
(`tests/svc_standin.mjs stripe`): what was sent, the form's fields, the
key, `Stripe-Account`, the idempotency keys, refusals, signatures, and
events the stand-in posts itself. [Ten minutes in test
mode](#checking-it-against-stripe-ten-minutes) is the way to check it.

## A SaaS, start to end

```mote
use "pkg:stripe/webhooks.mote"          // takes stripe, billing and payments

// The plans, in the code: stripeSync keeps Stripe's catalog so.
fn stripePlans(): StripePlanSpec[]
  return [
    {key: "pro", name: "Pro", features: ["export", "api"], prices: [
      {key: "pro_month", amount: 1200, interval: "month", trialDays: 14, currencies: [{currency: "eur", amount: 1100}]},
      {key: "pro_year", amount: 12000, interval: "year"}]},
    {key: "team", name: "Team", features: ["export", "api", "sso"], prices: [{key: "team_seat", amount: 900, interval: "month"}]},
    {key: "calls", name: "API calls", prices: [{key: "api_calls", amount: 2, interval: "month", meter: "api_calls"}]}]

fn stripeMeters(): StripeMeterSpec[]
  return [{event: "api_calls", name: "API calls"}]

// Whether this person may export: the plan's features, kept current by the events.
server fn exportAll(): bytes requires signedIn
  let me = auth.me()?.id ?? ""
  if !stripeCan(me, "export")? fail("Export is on the Pro plan.", {kind: "refused"})?
  stripeUse(me, "api_calls", 1, "")?
  return makeExport(me)?

resource standing: StripeStanding? = stripeMyStanding() else none

column gap=8 padding=16
  if standing?.access == "grace"
    text (standing?.why ?? "")
    button "Update my card" press=stripeFixCardGo
  StripeButton price="pro_month" label="Go Pro, $12 a month" mode="subscription"
  button "Manage my plan" press=stripeManageGo
```

```sh
STRIPE_KEY=rk_test_… STRIPE_WEBHOOK_SECRET=whsec_… STRIPE_SYNC=start STRIPE_CATCH_UP=start bun dist/server/main.js
```

```toml
# mote.toml, beside the entry
[packages]
stripe = "../mote/extensions/stripe"
```

- `STRIPE_SYNC=start` makes Stripe's products, prices and meters what
  `stripePlans` says when the back end starts (once, keyed, safe on many
  back ends at once); `StripeButton price="pro_month"` sells by lookup key.
- A checkout's events make the `StripePlan` row; `stripeCan` reads it,
  with no request to Stripe.
- A failed renewal leaves the plan working for `STRIPE_GRACE_DAYS` (7)
  while Stripe retries; the page offers the card update; then the feature
  is off until the invoice is paid.

## The files

| `use "pkg:stripe/…"` | |
|---|---|
| `stripe.mote` | The core: one place that talks to Stripe (`stripeCallOn`), Checkout in every mode, the portal, customers and their addresses, the catalog, subscriptions read and changed, payment intents, refunds, the program's `stripePlans`, `stripeBuy`, `StripeButton`. |
| `billing.mote` | Billing in depth: `stripeSync`, subscriptions made, changed now or at the period's end, previewed, seats, pause, cancel with why, coupons and promotion codes, invoices, credit notes, tax ids, the customer's balance, usage on meters, test clocks. |
| `payments.mote` | Saved ways of paying, charges off-session, payment links, disputes and evidence files, the balance, payouts and what they were made of. |
| `webhooks.mote` | `POST /stripe/webhook`, `StripeEvent`, `StripePlan`, the hooks, `stripeStanding`, `stripeCan`, `stripeCatchUp`. Takes the three above. |
| `connect.mote` | Connect: sellers' accounts, onboarding, `StripeAccount`, transfers, fees, `POST /stripe/connect/webhook`. Takes `webhooks.mote`. |
| `admin.mote` | `StripeAdmin`: who is on what, MRR by plan, what is owed, disputes, the catalog against the code. `pkg:admin/stripe.mote` makes it the admin panel's Billing tab. |
| `testing.mote` | For a program's own `mote test`: events built and signed as Stripe signs them. |
| `elements.mote` + `elements.js` | **Optional**: the Payment Element, the one file with a script of Stripe's (`extern script`). |
| `tests.mote` | The extension's own tests. |

## The settings

| | |
|---|---|
| `STRIPE_KEY` | The secret key, or better a restricted key (`rk_…`) with [the rights the program uses](#a-restricted-key-what-each-part-needs). A [`secret`](back-end.md#secrets): the back end does not start without it, and it is `[secret]` wherever the log would hold it. |
| `STRIPE_WEBHOOK_SECRET` | With `webhooks.mote`: the endpoint's signing secret, `whsec_…`. A secret. |
| `STRIPE_CONNECT_WEBHOOK_SECRET` | With `connect.mote`: the Connect endpoint's signing secret. A secret. |
| `STRIPE_PRICES` | More prices `stripeBuy` and `StripeButton` may sell (ids or lookup keys), with commas between. The plans' prices are on sale anyway. Or the program's own `fn stripeSells(price: string): bool`. |
| `STRIPE_TAX` | `auto`: automatic tax on every checkout, subscription, invoice and payment link made here. |
| `STRIPE_SYNC` | `start`: `stripeSync(true)` is queued when the back end starts. |
| `STRIPE_CATCH_UP` | `start`: the events made while the back end was down are read from Stripe's list when it starts. |
| `STRIPE_GRACE_DAYS` | How long a `past_due` plan still gives what it gives: 7. |
| `STRIPE_FETCH_FRESH` | `no`: an event's own copy of its object is kept (an older event never undoing a newer one). Unsaid: each object is read again from Stripe. |
| `STRIPE_METER_BATCH` | How many usage events one run of the job sends: 500. |
| `STRIPE_WEBHOOK_TOLERANCE` | How old an event's signature may be, in seconds: 300. |
| `STRIPE_PUBLISHABLE_KEY` | With `elements.mote` only: the `pk_…` key the form is drawn with (not a secret). |
| `STRIPE_VERSION` | Another API version than the one pinned (for trying an upgrade). |
| `STRIPE_API`, `STRIPE_FILES_API` | Other addresses for `api.stripe.com` and `files.stripe.com`: a stand-in, in tests. |

## The API version, in one place

`stripePinned()` in `stripe.mote` is `2024-06-20`: every request says it
(`Stripe-Version`), and the shapes were written against it. **Set your
webhook endpoints to the same version** in the dashboard: an event is
written in its endpoint's version, not the request's.

The readers already take both sides of the changes of `2025-03-31.basil`
that touch them: a subscription's period on its items, an invoice's
subscription under `parent.subscription_details`, its payment under
`payments`, a line's proration and price under `parent` and `pricing`. To
upgrade: read Stripe's changelog from the pinned date on; run the program
in test mode with `STRIPE_VERSION=<new>` and the steps
[below](#checking-it-against-stripe-ten-minutes); move the endpoints; then
change `stripePinned`. Known to need a look at an upgrade: `latest_invoice.payment_intent`
(expanded by `stripeSubscribe`: from basil, `latest_invoice.confirmation_secret`,
which the reader already reads), a phase's `iterations` in a schedule
(`duration` in later versions), and promotion codes' `coupon` (under
`promotion` in later versions, which the reader also reads).

## When it fails

Every call fails with a sentence (Stripe's own message where it gave one)
and a [kind](back-end.md#when-something-fails):

| Kind | |
|---|---|
| `"card"` | The card was refused. `err.data.decline` says why (`insufficient_funds`, `generic_decline`). |
| `"authenticate"` | The bank wants the person to confirm (3-D Secure), and they are not there: `err.data.payment`, `err.data.clientSecret`. [Below](#charges-when-the-person-is-not-there). |
| `"invalid"` | Stripe did not take what was asked: `err.data.param` names the field. Also no such object (`err.data.code` `"resource_missing"`). |
| `"auth"` | The key is wrong, or may not do this (a restricted key without the right; a connected account the key cannot reach). |
| `"conflict"` | The same idempotency key was used for something else. |
| `"limited"` · `"stripe"` | Too many requests; Stripe broke: after the call's own tries. |
| `"offline"` | Stripe did not answer. |

`err.data` is `{status, type, code, param, decline, request, payment,
clientSecret}`: `request` is Stripe's request id, which their support asks
for. Each refusal is a line of the log at `warn`, without the key.

## Doing it once

- **Every request that changes something carries an idempotency key**:
  the `key` a call is given, which names what it is for (`order-17`), or a
  fresh one. Tried again on a 429 or a 5xx, or when no answer came, it is
  the same request to Stripe. The same key with other fields is refused
  (`kind "conflict"`).
- Give a `key` of your own wherever the call may be made again after a
  restart (in a `job fn`, from a person pressing twice).
- The extension's own writes are keyed already where a key makes sense: a
  customer (`mote-customer-<user>`), a connected account
  (`mote-account-<user>`), `stripeSync`'s writes (a hash of what each asks),
  a usage event (its id), a finalize, a void, a pay.

## Checkout, the portal, customers

| Call | Gives |
|---|---|
| `stripeCheckout(ask)` | A `StripeCheckout`: send the person to `.url`. Below. |
| `stripeCheckoutGet(id)` · `stripeCheckoutExpire(id)` · `stripeCheckoutLines(id)` | The session again (on the success page); ended; what it sold. |
| `stripePortal(customer, back)` | Stripe's customer portal: card, invoices, plan, cancelling, as set up in the dashboard. |
| `stripePortalFor(customer, back, flow, subscription)` | The portal opened at one thing: `"payment_method_update"`, `"subscription_cancel"`, `"subscription_update"`. |
| `stripeCustomerFor(user, email)` | The customer of one of the program's accounts: kept (`StripeLink`), else made once. `stripeUserOf(customer)` is the way back. |
| `stripeCustomerGet(id)` | A `StripeCustomer`, with `balance`, `defaultPayment`, `address`, `taxStatus` (whether Stripe can work out their tax), `delinquent`. |
| `stripeAddressSet(customer, address, name)` · `stripeCustomerSet(id, fields)` · `stripeCustomerAdd(…)` | |

`stripeCheckout`'s ask, all but the first four optional:

| | |
|---|---|
| `mode` | `"payment"`, `"subscription"`, or `"setup"` (a card saved, nothing paid). |
| `items` | Each `{plan}` (a lookup key of the program's plans), `{price}`, or `{amount, currency, name}` (an amount said here; `product` for one of Stripe's; `interval` to recur); `quantity`; `adjustable` (`least`, `most`). |
| `success`, `cancel` | Where Stripe sends the person back to; `{CHECKOUT_SESSION_ID}` in it is the session's id. |
| `customer` or `email` | |
| `user`, `order` | The program's account and order: `client_reference_id`, `metadata.user` and `metadata.order` on the session and what it makes. |
| `trialDays`, `trialNoCard`, `trialEndsWithout` | A trial; one that asks for no card; what happens at its end with none (`"cancel"`, `"pause"`, `"create_invoice"`). |
| `promotionCodes`, `coupon`, `promotion` | A field for the person's code, or a discount given here (not both). |
| `tax`, `taxIds`, `address`, `phone`, `terms` | Automatic tax (and the address it needs kept on the customer), a business's tax id, the billing address, a phone, the terms accepted. |
| `currency`, `locale` | Adaptive pricing (Stripe showing a price in the person's own currency) is left to the dashboard's setting. |
| `saveCard`, `capture: "manual"`, `invoice` | Keep the card for later; authorise now and take it with `stripeCapture`; an invoice and receipt for a one-off. |
| `expiresAt` | |
| `destination`, `fee`, `feePercent`, `onBehalfOf`, `group`, `account` | Connect: [below](#connect-marketplaces-and-platforms). |
| `key` | |

For a page, whoever is signed in: `stripeBuy(price, mode, back)` (a
`server fn`, 20 a minute, only what `stripeSells` allows, a plan's price by
its lookup key with its trial), `stripeManage(back)`, `stripeFixCard(back)`
(the portal at the card); the actions `stripeGo`, `stripeManageGo`,
`stripeFixCardGo`; `StripeButton price= label= mode=`. `back` is an address
of the site's own; anything else is the site's first page.

## The plans, kept at Stripe from the code

The program says its plans once, with `fn stripePlans(): StripePlanSpec[]`
(and its meters with `fn stripeMeters()`), and `stripeSync(apply)` makes
Stripe's catalog say the same:

- each plan is a **product whose id is the plan's key** (`"pro"`): made,
  or its name, description, tax code and features (`metadata.mote_features`)
  changed;
- each price is **found by its lookup key** (`"pro_month"`): made; or,
  when its amount, currency, interval or meter changed (which Stripe never
  allows on a price), a new price that takes the key over
  (`transfer_lookup_key`), and the old one archived. Subscriptions on the
  old price stay on it until they are moved (`stripeChangePlan`);
- each meter is found by its event name; a meter's formula cannot change,
  and a step says so;
- a product made from the code (`metadata.mote_plan`) that the code no
  longer has is archived. Nothing is ever deleted.

`stripeSync(false)` only says what it would do (`StripeSyncStep[]`: `what`,
`name`, `why`, `id`, `done`); `true` does it. Each write's idempotency key
is a hash of what it asks, so two back ends starting at once (or a job
tried again) make one of each. `STRIPE_SYNC=start` runs it in a job at
start; the admin panel has a Compare and a Keep button.

## Subscriptions

| Call | |
|---|---|
| `stripeSubscribe({customer, items, user?, trialDays?, trialEnd?, coupon?, promotion?, paymentMethod?, tax?, currency?, destination?, feePercent?, key?})` | A subscription made from the back end (a second one, one begun by staff, an upgrade from a free plan), `payment_behavior: default_incomplete`: `incomplete` until its first invoice is paid; when the bank asks, `.invoiceUrl` is Stripe's page where the person confirms it. |
| `stripePreviewChange({subscription, price, quantity?, prorate?})` | What a change would cost now: `change` (the proration lines), `total`, `tax`, `lines`, and the `prorationDate` it was worked out for. |
| `stripeChangePlan({subscription, price, quantity?, item?, prorate?, at?, prorationDate?, key?})` | The upgrade and the downgrade. `prorate`: `"next"` (credited and charged on the next invoice), `"now"` (an invoice now; the change waits until it is paid: `pending_if_incomplete`), `"none"`. `at: "period_end"`: a schedule of two phases, the new price beginning when what is paid for ends. Pass the preview's `prorationDate` to charge what was shown. |
| `stripeChangeUndo(subscription)` | Takes back a change waiting for the period's end. |
| `stripeSeats(subscription, quantity, prorate)` | Seats. |
| `stripePause(subscription, behavior, resumesAt)` · `stripeUnpause(subscription)` | Collection paused (`"void"`, `"keep_as_draft"`, `"mark_uncollectible"`), until a moment or until told; a subscription Stripe paused (a trial ended with no card) resumed with a new period. |
| `stripeCancel(id, atEnd)` · `stripeResume(id)` · `stripeCancelWith({subscription, atEnd, feedback?, comment?, invoiceNow?, prorate?})` | Cancel at the period's end and take it back; cancel with the person's reason. |
| `stripeCouponMake(…)` · `stripePromotionMake(…)` · `stripePromotionFind(code)` · `stripeDiscountGive(sub, promotion, coupon)` · `stripeDiscountRemove(sub)` | |
| `stripeSubscriptionGet(id)` · `stripeSubscriptions(customer)` | A `StripeSubscription`: every item, the period, trial, pause, cancel, latest invoice and its page, schedule, discounts. A customer may have several. |
| `stripeChange(id, price, quantity, prorate)` | The simple form of `stripeChangePlan`. |

**Currencies.** A price may be sold in several currencies
(`currencies` in a plan's price: `currency_options`); a checkout's
`currency` picks one. Stripe keeps all of one customer's subscriptions in
one currency.

## What a person may do: standing, `stripeCan`

The events keep a `StripePlan` row for each subscription; these read it,
with no request to Stripe, and are right as of the last event:

| | |
|---|---|
| `stripeCan(user, feature)` | Whether one of the account's plans whose access is `full` or `grace` gives the feature (the code's `stripePlans`, else the product's `mote_features`), or Stripe's own Entitlements do (`entitlements.active_entitlement_summary.updated`). |
| `stripeStanding(user)` | The best of the account's plans, as a `StripeStanding`: `access`, `next`, `url`, `until`, `why`, `plan`. |
| `stripeActive(user, product)` · `stripePlanOf(user)` · `stripePlansOf(user)` | |
| `stripeMyStanding()`, `stripeMayI(feature)`, `stripeMyPlan()` | `server fn`s for whoever is signed in. |

What each of Stripe's statuses lets the person do, and what to offer:

| Stripe says | `access` | `next` | |
|---|---|---|---|
| `active`, `trialing` | `full` | `""` (`"undo_cancel"` when it ends at the period's end) | |
| `past_due`, within `STRIPE_GRACE_DAYS` | `grace` | `"update_card"` | Stripe's Smart Retries are trying again (`invoice.payment_failed`, `nextAttempt`): keep the plan on, ask for another card (`stripeFixCardGo`). |
| `past_due` after the grace, `unpaid` | `limited` | `"pay_invoice"` | `url`: the invoice's page. What happens after the last retry (cancel, mark unpaid, leave past due) is the dashboard's setting. |
| `incomplete` | `pending` | `"confirm_payment"` | The first payment waits for the bank: `url`. |
| `paused`, or collection paused | `paused` | `"resume"` | |
| `canceled`, `incomplete_expired`, none | `none` | `"subscribe"` | |

## Usage: meters

```mote
stripeUse(user, "api_calls", 1, requestId)?        // counted once per id, sent later
stripeUseAt(user, "api_calls", 40, "import-7", importedAt)?   // a late one, at its own moment
```

- Each use is a `StripeUsage` row first, so nothing is lost if Stripe is
  down; a job sends them oldest first, up to `STRIPE_METER_BATCH` a run,
  each a meter event whose `identifier` is the use's id (and its
  idempotency key): the same use sent twice is counted once.
- A late one keeps its own moment. Stripe takes a use from the last 35
  days (and five minutes ahead); an older one is kept as `"late"` and not
  sent. A use whose period's invoice is already final is billed as Stripe
  decides (it is not added to that invoice).
- One Stripe refuses (no such meter, no such customer) is `"refused"` with
  Stripe's words; one Stripe could not be reached for waits, and the job is
  tried again (and every five minutes, whatever waits is sent).
- `stripeUsageSum(event, customer, from, to)` is what Stripe has counted.

Left out: the v2 meter event stream (thousands a second, a session token);
the v1 endpoint here is enough for most products.

## Invoices, credit notes, tax, the balance

| | |
|---|---|
| `stripeInvoices(customer, status, after)` · `stripeInvoiceGet(id)` | `StripeInvoice`: `number`, `status`, `reason`, `total`, `tax`, `amountDue`, `attempts`, `nextAttempt`, `url` (its page), `pdf`, `lines`. |
| `stripeUpcoming(customer, subscription)` | The next invoice, as it would be made now. |
| `stripeInvoiceFinalize` · `stripeInvoicePay(id, paymentMethod)` · `stripeInvoiceVoid` · `stripeInvoiceUncollectible` · `stripeInvoiceSend` | |
| `stripeInvoiceMake({customer, items, daysDue?, memo?, tax?, finalize?, key})` | An invoice of the program's own (a setup fee, work done): mailed to be paid within `daysDue`, or charged. |
| `stripeCreditNote({invoice, amount, refund?, credit?, reason?, memo?, key})` · `stripeCreditPreview` · `stripeCreditNotes(invoice)` | |
| `stripeTaxIdAdd(customer, type, value)` · `stripeTaxIds` · `stripeTaxIdRemove` | A business's VAT or GST id. |
| `stripeCredit(customer, amount, currency, why, key)` · `stripeBalanceEntries(customer)` | Credit on the customer's balance, taken off their next invoices. |

Automatic tax needs Stripe Tax set up (origin address, registrations) in the
dashboard; with `STRIPE_TAX=auto` or `tax: true`, a checkout with a customer
keeps the address the person types (`customer_update[address]=auto`), which
Stripe needs to work it out.

## Payments

| | |
|---|---|
| `stripeSaveCard(customer, currency, success, cancel)` | A card saved for later with no script: Checkout in setup mode. |
| `stripeSetupMake(customer, usage, key)` | A setup intent for `elements.mote`. |
| `stripeCards(customer)` · `stripeCardDefault(customer, pm)` · `stripeCardRemove(pm)` · `stripeCardBelongs(customer, pm)` | Saved ways of paying (`StripeCard`: brand, last4, expiry, wallet, default). |
| `stripeCharge({customer, amount, currency, paymentMethod?, key, …})` | A charge when the person is not there. |
| `stripeConfirmPage(customer, amount, currency, description, key)` | Stripe's page where the person confirms a charge, with no script: an invoice's. |
| `stripePay(…)` · `stripePaymentGet` · `stripeCapture(payment, amount)` · `stripePaymentCancel(payment, why)` | Payment intents. |
| `stripeRefund(payment, amount, key)` · `stripeRefundWith({payment, amount?, reason?, reverseTransfer?, refundFee?, key})` · `stripeRefunds(payment)` | |
| `stripePayLinkMake({items, after?, promotionCodes?, tax?, order?, key?})` · `stripePayLinkActive(id, on)` · `stripePayLinks()` | A lasting address that sells. |
| `stripeDisputes(after)` · `stripeDisputeGet` · `stripeDisputeAnswer(id, evidence, submit)` · `stripeDisputeAccept(id)` · `stripeFileUpload(bytes, name, type, purpose)` | Disputes: evidence in words and files, kept as a draft or submitted. |
| `stripeBalance(account)` · `stripePayouts(account, after)` · `stripePayoutGet` · `stripePayoutMake(…)` · `stripeMovements(payout, account, after)` | The balance, payouts, and what a payout was made of. |

### Charges when the person is not there

```mote
job fn renewBox(user: string, month: string)
  let customer = stripeCustomerFor(user, "")?
  // (A card refused, Stripe down: the job fails and is tried again. The bank wanting the person: a page for them.)
  let p = stripeCharge({customer, amount: 3900, currency: "usd", user, key: `box-${user}-${month}`}) else err => (err.kind == "authenticate" ? none : fail(`${err}`, {kind: err.kind})?)
  if p == none
    let page = stripeConfirmPage(customer, 3900, "usd", `Your box for ${month}`, `box-${user}-${month}-page`)?
    mailSend({to: user, subject: "Confirm your payment", text: `Your bank wants you to confirm: ${page}`})?
```

### What the page needs without Stripe.js

Checkout (payment, subscription and setup), the portal, an invoice's page
(paying it, confirming a card) and Connect's onboarding are Stripe's own
pages: a person is sent there and back, and the program needs no script.
Only a payment form drawn *inside* the program's page (the Payment Element)
needs Stripe's script: that is `elements.mote`, optional and separate, the
one place the extension says `extern script "https://js.stripe.com/v3/"`
(with `extern js "./elements.js"`, thirty lines of glue). A program that
does not take it has no script of Stripe's. It has not been run in a
browser against Stripe.

## Events: webhooks.mote

`POST /stripe/webhook`:

1. **checks the `Stripe-Signature` header** ([`webhook.check(…,
   "stripe", …)`](back-end.md#webhooks), for both endpoints): HMAC-SHA256,
   under the endpoint's signing secret, of `<t>.<the body as sent>`, in
   lowercase hex, compared in constant time with each `v1` signature (two
   while a secret is rolled; `v0` never), and refuses a `t` more than five
   minutes from now. A refusal is a 400 with why, and a line of the log. The
   tests check it against a header worked out by hand from Stripe's recipe
   (Stripe publishes no fixed example header and body to test against);
2. **keeps the event once, by its id** (`webhook.once`, with `StripeEvent`
   holding it for its job), in the same turn as queuing its job: an event
   Stripe sends again, or twice at once, is answered `{received: true,
   again: true}` and not done again;
3. **answers at once**, and leaves the work to `job fn stripeDeliver`;
4. **reads the object again from Stripe** (events come late and in any
   order: what Stripe says now is kept, never an older copy; one Stripe no
   longer has is taken from the event), keeps `StripePlan` and
   `StripeAccount` current, then tells the hooks.

| Events | Kept | Hook |
|---|---|---|
| `checkout.session.completed`, `.async_payment_succeeded` | `StripeLink`, the plan | `stripePaid(c)` when paid |
| `checkout.session.async_payment_failed`, `.expired` | | `stripeCheckoutFailed(c)`, `stripeCheckoutExpired(c)` |
| `customer.subscription.created`, `.updated`, `.deleted`, `.paused`, `.resumed`, `.pending_update_applied`, `.pending_update_expired` | the plan | `stripeSubscriptionChanged(p)` |
| `customer.subscription.trial_will_end` | the plan | `stripeTrialEnding(p)` |
| `invoice.paid` | the plan | `stripeInvoicePaid(i)`, `stripeSubscriptionChanged(p)` |
| `invoice.payment_failed` (each Smart Retry) | the plan | `stripePaymentFailed(i)`, `stripeSubscriptionChanged(p)` |
| `invoice.payment_action_required` | the plan | `stripeActionRequired(i)`: send them `i.url` |
| `invoice.upcoming` | | `stripeInvoiceUpcoming(i)` |
| `invoice.finalized`, `.voided`, `.marked_uncollectible`, `.finalization_failed`, `.overdue`, `.will_be_due` | the plan | `stripeInvoiceChanged(i)` |
| `payment_intent.*` | | `stripePaymentChanged(p)` |
| `setup_intent.succeeded` | | `stripeCardSaved(s)` |
| `charge.refunded` | | `stripeRefunded(r)` |
| `charge.dispute.*` | | `stripeDisputed(d)` |
| `payout.*` | | `stripePayoutChanged(p)` |
| `entitlements.active_entitlement_summary.updated` | `StripeEntitlement` | `stripeEntitlementsChanged(e)` |
| `account.updated`, `capability.updated`, `person.*`, `account.application.deauthorized` (connect.mote) | `StripeAccount` | `stripeAccountChanged(a)` |
| `transfer.*` (connect.mote) | | `stripeTransferChanged(t)` |
| every event, after the above | | `stripeEvent(e)` |

A hook's `false` is not a no to Stripe; a hook that fails makes the job be
tried again. **Make each safe to run twice.**

**After downtime.** `stripeCatchUp(since, account)` reads the events made
since then from Stripe's list (it keeps 30 days), oldest first, and keeps
and does each one not yet kept: what the route missed while the back end
was down. `STRIPE_CATCH_UP=start` runs it at start, from an hour before the
newest event kept. Of a connected account with `account`.

## Connect: marketplaces and platforms

`use "pkg:stripe/connect.mote"`, and a second endpoint at Stripe
(Developers → Webhooks → "Events on Connected accounts") at
`/stripe/connect/webhook`, its secret `STRIPE_CONNECT_WEBHOOK_SECRET`.

| | |
|---|---|
| `stripeAccountFor(user, {type, country?, email?, capabilities?, business?})` | A seller's account, `"express"` or `"standard"`, made once. |
| `stripeOnboarding(account, back, again, update)` | Stripe's onboarding page (a link good once, for minutes: make it when they press). |
| `stripeAccountSession(account, components)` | A client secret for Connect's embedded components (Connect.js in the page: not part of this extension). |
| `stripeDashboard(account)` | An Express account's own dashboard. |
| `stripeAccountGet(id)` · `stripeSellerReady(user)` · `stripeMySeller()` · `stripeBecomeSeller(country, back)` · `stripeSellerGo(country)` | |
| `stripeCheckout({…, destination, fee})` · `stripeCharge({…, destination, fee})` | A destination charge: the money to the seller, the platform's fee kept. `onBehalfOf` makes the seller the seller of record. |
| `stripeCheckout({…, account})` · any call with `account` | A direct charge, on the seller's account (`Stripe-Account`). `stripeRaw(method, path, fields, key, account)` is any other call. |
| `stripeTransfer({amount, currency, destination, charge?, group?, key})` · `stripeTransfers` · `stripeTransferBack(transfer, amount, key)` | Separate charges and transfers, and their reversal. |
| `stripeFees(account, after)` · `stripeFeeBack(fee, amount, key)` | The platform's fees. |
| `stripeRefundWith({payment, reverseTransfer: true, refundFee: true, key})` | A destination charge refunded, the seller's part taken back and the fee given back. |
| `stripeBalance(account)` · `stripePayouts(account, after)` · `stripePayoutMake(…, account, key)` | A seller's balance and payouts. |

`StripeAccount` is set from `account.updated` (read again):
`charges`, `payouts`, `submitted`, `due`, `pastDue`, `eventually`,
`disabled`, `deadline`, `capabilities`, `gone`.

## Testing a program's own hooks

`use "pkg:stripe/testing.mote"` in the program, then in its tests:

```mote
test "Pro stays on through the grace, then goes"
  given secret "STRIPE_WEBHOOK_SECRET" is "whsec_test"
  given env "STRIPE_FETCH_FRESH" is "no"
  clock "2026-03-01T09:00"
  trusted
    StripeLink.add({user: "u1", customer: "cus_1"})?
    stripeTestSend("customer.subscription.updated", stripeTestSubscription("sub_1", "cus_1", "past_due", "pro_month"))?
    stripeTestSend("invoice.payment_failed", stripeTestInvoice("in_1", "cus_1", "sub_1", "open", 1200))?
  run jobs
  trusted
    expect stripeCan("u1", "export")
  clock +8 days
  trusted
    expect stripeCan("u1", "export") == false
```

`stripeTestSend` builds the event, signs it as Stripe does and hands it to
the route's own fn (`stripeReceive`): signature checked, kept once, queued.
`stripeTestSubscription`, `stripeTestInvoice`, `stripeTestCheckout` build
objects at the pinned version; `stripeTestResend` sends one again. With
`STRIPE_FETCH_FRESH` unsaid, give the object Stripe would answer:
`given net "https://api.stripe.com/v1/subscriptions/*" answers {status:
200, json: sub}`.

**Test clocks** (test mode): `stripeClockMake(name, at)`,
`stripeCustomerOnClock(email, user, clock)`, `stripeClockAdvance(id, to)`,
`stripeClockWait(id, most)`, `stripeClockDelete(id)`. A `mote test` reaches
no network, so there the clock is the test's own (`clock +31 days`) and the
events are `stripeTestSend`'s; a Stripe test clock is driven from a
`server fn` or a script against test mode, and its events arrive at the
route as real ones do. The stand-in run drives one: a month passes, the
renewal is paid; another, the card fails and the plan is in its grace.

## The admin panel

```mote
use "pkg:admin/admin.mote"
use "pkg:admin/stripe.mote"         // a Billing tab; stripeAdminMay is the rule `admin`
```

`StripeAdmin`: MRR by currency and by plan (from the catalog's amounts:
metered prices are left out of it), how many plans in each status, failed
payments in thirty days, who owes (with their standing and the invoice's
page), who is on what, usage waiting or refused, open disputes, and the
plans in the code compared with Stripe's catalog (Compare; Keep them at
Stripe). Without the admin extension: `use "pkg:stripe/admin.mote"` and the
program's own `fn stripeAdminMay(): bool`.

## A restricted key: what each part needs

Make a restricted key (Developers → API keys → Create restricted key) with
only what the program uses. The names are the dashboard's as of 2026, from
memory: check them where you make the key.

| The program uses | Write | Read |
|---|---|---|
| Checkout, `StripeButton` | Checkout Sessions, Customers | Prices, Products |
| The portal | Customer portal | |
| `stripeSync` | Products, Prices, Billing Meters | |
| Subscriptions in depth | Subscriptions, Subscription Schedules, Invoices (previews), Coupons, Promotion Codes | |
| Invoices, credit notes, balance, tax ids | Invoices, Invoice Items, Credit Notes, Customers | |
| Usage | Billing Meter Events | Billing Meters (event summaries) |
| Saved cards, off-session charges | Setup Intents, Payment Methods, Payment Intents | |
| Refunds | Refunds | |
| Payment links | Payment Links | |
| Disputes | Disputes, Files | |
| Balance, payouts | Payouts (to make one) | Balance, Balance Transactions, Payouts |
| The webhook route (reading each object again) | | Checkout Sessions, Subscriptions, Invoices, Payment Intents, Charges, Disputes, Payouts, Entitlements |
| `stripeCatchUp` | | Events |
| Connect | Accounts, Account Links, Account Sessions, Login Links, Transfers, Application Fees (refunds) | |
| Test clocks | Test Clocks (test mode only) | |

A call the key may not make fails with `kind "auth"` and Stripe's words,
which name the right that is missing.

## Checking it against Stripe (ten minutes)

In test mode, with the Stripe CLI (`stripe login` once).

1. **A key.** Make a restricted key with the rights in the table for the
   parts you use (or, for this check, a test secret key). `stripe listen
   --forward-to localhost:4870/stripe/webhook` prints `whsec_…`.
2. **Start it**: `STRIPE_KEY=rk_test_… STRIPE_WEBHOOK_SECRET=whsec_…
   STRIPE_SYNC=start` with the plans of the example above. **Look**:
   Products → `pro`, `team`, `calls`, each id the plan's key; Prices with
   the lookup keys `pro_month`, `pro_year`, `team_seat`, `api_calls`;
   Billing → Meters → `api_calls`. Start it again: the log says no changes,
   and Developers → Logs shows no new POSTs. Change `pro_month`'s amount
   and start again: a new price holds the key, the old one is archived.
3. **Buy.** Sign in, press the `StripeButton`, pay with `4242 4242 4242
   4242`. The CLI shows `checkout.session.completed`,
   `customer.subscription.created`, `invoice.paid`, each answered 200; the
   log shows the subscription read again (Developers → Logs: a GET of it);
   `stripeCan(user, "export")` is true; Customers → the customer's metadata
   has `user`.
4. **Upgrade.** Call `stripePreviewChange` to `team_seat` with `prorate:
   "now"`, then `stripeChangePlan` with its `prorationDate`: the invoice in
   the dashboard comes to the preview's `total`.
5. **Downgrade at the end.** `stripeChangePlan({…, at: "period_end"})`:
   Subscriptions → the subscription shows a schedule with two phases.
6. **Fail a renewal.** Make a test clock (`stripeClockMake`), a customer on
   it, set its card to `4000 0000 0000 0341` (attaches, then declines),
   subscribe, advance the clock a month: `invoice.payment_failed`, the plan
   `past_due`, `stripeStanding` is `grace` with the invoice's page.
7. **Usage.** `stripeUse(user, "api_calls", 5, "x1")` twice: Billing →
   Meters → `api_calls` shows 5, once.
8. **A bank that wants the person.** Save `4000 0027 6000 3184` (Checkout
   in setup mode), `stripeCharge` it: `kind "authenticate"`;
   `stripeConfirmPage` opens Stripe's invoice page that asks for it.
9. **Connect.** `stripeAccountFor(seller, {type: "express", country:
   "US"})`, open `stripeOnboarding`, fill in the test data; the Connect
   endpoint (`stripe listen --forward-connect-to
   localhost:4870/stripe/connect/webhook`) gets `account.updated`;
   `stripeSellerReady` is true; a checkout with `destination` and `fee`
   shows the transfer and the application fee in the dashboard.
10. **Downtime.** Stop the back end, `stripe trigger
    customer.subscription.updated`, start it with `STRIPE_CATCH_UP=start`:
    the event is done once (and `stripe events resend evt_…` then answers
    `again: true`).

What to look for in each answer against the shapes here, and where I was
not sure: a phase's `iterations` in a schedule update; the exact error code
Stripe gives for a meter event whose `identifier` it already has (the
extension takes any refusal that mentions the identifier as counted); the
restricted keys' right names; `customer.tax.automatic_tax` values.

## What is kept

| Model | |
|---|---|
| `StripeLink` | An account of the program's (`user`) and its Stripe `customer`. |
| `StripeCatalog` | Each price of the plans by lookup key: id, product, amount, interval, features. |
| `StripeMeterKept` | Each meter's id by event name. |
| `StripeEvent` | Each event once: `id`, `type`, `created`, `data`, `account`, `state`. A month. |
| `StripePlan` | Each subscription, as Stripe last said it: status, items, features, period, trial, pause, cancel, `owingSince`, the latest invoice and its page. |
| `StripeEntitlement` | Stripe's own Entitlements of each customer. |
| `StripeUsage` | Each use until Stripe has it (`waiting`, `sent`, `late`, `refused`); sent ones forty days. |
| `StripeAccount` | Each connected account, as `account.updated` left it. |

None has rules: a page reads them only through the `server fn`s above, or
the program's own.

## Covered, and left out on purpose

Covered: what a SaaS and a marketplace do week to week, listed above.

Left out:

- **Embedded Checkout and Connect's embedded components**: each needs
  Stripe's script in the page; `elements.mote` shows the way for the
  Payment Element, and `stripeAccountSession` gives what Connect.js needs.
- **Quotes, Issuing, Terminal, Treasury, Climate, Identity, Radar rules,
  Sigma, Revenue Recognition, the Tax calculation API** (Stripe Tax is used
  through `automatic_tax`), **reporting runs**.
- **The v2 APIs** (the meter event stream, v2 accounts and event
  destinations): v1 covers the same for most products, and v2's versioning
  was the part I was least sure of.
- **Custom connected accounts' own onboarding** (`type: "custom"` is
  refused: Express or Standard, where Stripe does the onboarding).
- **One billing facade over Stripe, PayPal, Paddle and Polar**: not built,
  on purpose; [paypal.md](paypal.md) says why.

Recorded in `tests/expect/real_svc_stripe.txt` (`tests/all.sh
real_svc_stripe`): the shop of `tests/svc_stripe/app.mote` against the
stand-in, which keeps state and posts its own signed events to both
endpoints: the first part as before (calls, refusals, a 429, a refund asked
twice, events signed, refused, sent twice, out of order); then the plans
kept at Stripe and kept again with no write, a plan bought by lookup key, a
subscription previewed, upgraded as shown, downgraded at the end, usage
once each, an off-session charge that wants the person, a seller onboarded
and paid, a test clock's renewal and failed card, catch-up after downtime,
a dispute answered, an invoice and a payment link; then the extension's own
`mote test` and the shop's (`tests/svc_stripe/unit.mote`, 28 tests).
