# Kontrol API: the complete client reference (llm.md)

Everything a client or an AI agent needs to drive a Kontrol account through the API: base URL `https://api.kontrolcheckout.com`, one type of API key, restricted by its scopes, the 802 endpoints a key can call and the 14 inbound webhooks providers call. Every endpoint has exactly one place: a category and a subcategory that follow the dashboard menu. Generated from the API source: the addresses and scopes are the ones the API enforces.

- Part 1, start here: authentication, scopes, addresses, what is not documented and why, errors, limits, conventions.
- Part 2, workflows: the multi-step tasks, in order.
- Part 3, endpoint index: every documented endpoint on one line, by category and subcategory, with its scope.
- Part 4, endpoint reference: every documented endpoint in full, by category and subcategory, with the notes of each subcategory.

## 1. Start here

### Base URL and authentication

Base URL: `https://api.kontrolcheckout.com`. Every request is HTTPS and every body is JSON (`Content-Type: application/json`) unless an endpoint documents a file upload or a file download.

Send your API key on every request:

```
Authorization: Bearer <your API key>
```

```bash
export API='https://api.kontrolcheckout.com'
curl --fail-with-body -sS -H "Authorization: Bearer $KONTROL_API_KEY" "$API/v1/checkouts"
```

- A key looks like `ck_` followed by 32 characters. It is shown once, when it is created; Kontrol stores only its hash. Keep it in a secret manager, never in a URL, a page or a public document.
- `X-Api-Key: <key>` is also accepted by the payment, reporting and partner routes (`/v1/charge`, `/v1/reports/*`, `/v1/refund/*` and their neighbours), but the account routes require the `Authorization` header and answer `401 Missing bearer token` without it. Use `Authorization: Bearer` everywhere.
- Create, rename, scope and revoke keys in the dashboard (API keys) or through the API (`GET /v1/keys`, `POST /v1/keys`, scope `api_keys.read` / `api_keys.write`). A key can only grant scopes it holds itself.

### One key, restricted by its scopes

There is one type of API key. Every key of an account can drive that account: what it may do is decided only by its scopes, which the key's configuration sets precisely, category by category, read and write. All 802 client endpoints of this document are open to a key that holds the scope each one names (two of them refuse every key because they record a person's consent: see below). The 14 inbound webhooks are called by providers, never with a key, and take no scope.

- `scopes: null` (an unrestricted key) grants every category, including categories added later. `scopes: []` grants nothing.
- Read never implies write: `checkouts.read` lists and reads stores, `checkouts.write` is needed to change them. A `POST` that only searches or previews (for example `POST /v1/refund/search`) needs the read scope; the endpoint says so.
- A call outside the key's scopes answers `403` with `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"}`. Nothing is silently narrowed.
- The cross-category readers return entities of every kind, so they need every read scope (`*.read`): `GET /v1/entities/product`, `GET /v1/entities/storefront`, `GET /v1/search`.
- The partner routes (`/v1/refund/*`, `/v1/transactions*`, `/v1/blacklist*`, `/v1/scrub-bins`) need a key with explicit scopes: a key whose scopes are unrestricted (`null`) is refused there. A `clientId` sent to them must be the key's own account, otherwise `403`.
- A key acts as the account administrator, never as a platform administrator, and it only ever sees its own account: an id that belongs to another account answers `404`, exactly like an id that does not exist.
- The account needs a paid platform subscription: otherwise account routes answer `402` with `code: "subscription_required"`. A tool outside the account's plan answers `403` with `code: "subscription_module_required"` and the `module` it needs.

The 38 scopes, by category. "Addresses" lists the address families each category covers; every endpoint in Parts 3 and 4 names its exact scope.

| scopes | category | endpoints (read / write) | addresses |
|---|---|---|---|
| `charges.read` / `charges.write` | Charges & 3DS | 6 / 34 | `/v1/3ds/*`, `/v1/charge/*`, `/v1/checkout/*`, `/v1/convesio/*`, `/v1/stripe/*`, `/v1/transactions/*`, `/v2/rebill-batches/*`, `/v5/checkout/*`, `/v5/flow/*`, `/v5/payment-methods`, `/v5/standalone/*`, `/v5/store/*` and 1 more |
| `transactions.read` / `transactions.write` | Transactions | 15 / 6 | `/v1/reports/*`, `/v1/transactions/*` |
| `refunds.read` / `refunds.write` | Refunds & disputes | 3 / 11 | `/v1/refund/*`, `/v1/refunds/*`, `/v1/transactions/*` |
| `kontrolpay.read` / `kontrolpay.write` | KontrolPay | 9 / 9 | `/v1/kontrolpay/*` |
| `routing.read` / `routing.write` | ATRIs, gateways & wallets | 46 / 72 | `/v1/accounts/*`, `/v1/acquiring-banks`, `/v1/atris`, `/v1/bank-accounts/*`, `/v1/bin-catalog/*`, `/v1/bin-generation-jobs/*`, `/v1/bin-generation/*`, `/v1/bin-issuers`, `/v1/bin-profiles/*`, `/v1/bin-scrub-enabled`, `/v1/bin-scrub-hits`, `/v1/bin-scrub-rules/*` and 10 more |
| `subscriptions.read` / `subscriptions.write` | Subscriptions & schedules | 59 / 62 | `/v1/subscription/*` |
| `customers.read` / `customers.write` | Customers & blacklist | 24 / 13 | `/v1/blacklist/*`, `/v1/customers/*`, `/v1/scrub-bins` |
| `checkouts.read` / `checkouts.write` | Stores & checkout builder | 79 / 138 | `/v1/checkouts/*`, `/v1/discounts/*`, `/v1/editor/*`, `/v1/v5/*` |
| `tracking.read` / `tracking.write` | Pixels & tracking | 5 / 7 | `/v1/checkouts/*` |
| `recovery.read` / `recovery.write` | Cart recovery | 11 / 12 | `/v1/recovery/*` |
| `reports.read` / `reports.write` | Dashboard & reports | 29 / 7 | `/v1/affiliates/*`, `/v1/bin-info`, `/v1/bin-map`, `/v1/home-ai/*`, `/v1/metrics/*`, `/v1/report-jobs/*`, `/v1/reports/*`, `/v1/status/*` |
| `integrations.read` / `integrations.write` | Integrations & messaging | 34 / 37 | `/v1/expify/*`, `/v1/integrations/*`, `/v1/messaging/*`, `/v1/platformpay/*`, `/v1/sender-atris/*`, `/v1/sender-costs`, `/v1/sender-rates` |
| `api_keys.read` / `api_keys.write` | API keys | 2 / 4 | `/v1/keys/*` |
| `users.read` / `users.write` | Users & access | 2 / 4 | `/v1/users/*` |
| `settings.read` / `settings.write` | Account settings | 3 / 3 | `/v1/me/*`, `/v1/settings/*` |
| `billing.read` / `billing.write` | Kontrol subscription & agreements | 8 / 8 | `/v1/me/*`, `/v1/platform-subscription/*` |
| `operations.read` / `operations.write` | Logs & operations | 12 / 1 | `/v1/audit-logs`, `/v1/charge-logs`, `/v1/errors`, `/v1/health`, `/v1/openapi.json`, `/v1/operation-capabilities`, `/v1/perf`, `/v1/reconciliation/*`, `/v1/rejections`, `/v1/subscription-charge-logs`, `/v1/subscription-export-logs`, `/v1/wallet-logs` |
| `monitoring.read` / `monitoring.write` | Uptime monitoring | 3 / 7 | `/v1/uptime/*` |
| `affiliates.read` / `affiliates.write` | Affiliates | 6 / 8 | `/v1/affiliates/*`, `/v1/v5/*` |

`*.read` means every read scope of the table.

### Addresses

Every client endpoint lives under `/v1`, except a few batch routes under `/v2` and the headless checkout runtime under `/v5` (Part 4, Headless checkout). The account's resources answer at `/v1/<route>`: `GET /v1/checkouts`, `PATCH /v1/accounts/:id`, `POST /v1/subscription/schedules/:id/jobs`. There is no other prefix.

Each endpoint has one address and one meaning. A few account routes have an explicit address, because their natural one belongs to another endpoint or would hide what they do:

- `GET /v1/transactions/:id/details` (Get a transaction's full record (attempts, basket, 3DS, fees, pipeline, attribution))
- `DELETE /v1/transactions/notes/:noteId` (Delete a transaction note)
- `GET /v1/checkouts/:shopId/routing/details` (Read a store's full payment-routing record (key, checkout, flow, default MID))
- `GET /v1/recovery/carts/:cart_token/details` (Read a recovery cart's full record (policy, links, raw send payloads))
- `POST /v1/transactions/:id/chargeback-refund` (Refund a transaction and mark it as a chargeback (money moves unless external: true))
- `GET /v1/metrics/jobs` (List dashboard report calculations)
- `POST /v1/metrics/jobs` (Start a dashboard report calculation in the background)
- `GET /v1/metrics/jobs/:jobId` (Read a dashboard report calculation's progress)
- `POST /v1/metrics/jobs/:jobId/cancel` (Cancel a dashboard report calculation)
- `GET /v1/metrics/jobs/:jobId/result` (Read a completed dashboard report)

Use the exact address each endpoint gives in Part 4.

### How this document is organised

Every endpoint sits in exactly one place: a category, then a subcategory. They follow the dashboard menu, from the Dashboard to the Settings, then the API-only areas: Getting started, Overview, Payments, Commerce, Headless checkout, KontrolPay, Subscriptions, Customers, Reports, Settings, Inbound webhooks, Outbound webhooks and services. Part 3 lists every endpoint on one line in that order; Part 4 gives each one in full. A subcategory also states, in its notes, how the dashboard computes the figures it shows from the endpoints (rates, totals, margins, comparisons) and which endpoint returns the rows of a file the dashboard builds in the browser.

### What is not documented, and why

The API also serves routes that are not part of the client API. A key cannot call them, so they are left out on purpose:

| not documented | routes | why |
|---|---|---|
| platform operator (super admin) | 103 | The platform operator's routes: plans, platform settings, every account's data. A key acts as the administrator of its own account only. |
| affiliate portal | 90 | The affiliate portal (/v5/affiliate/*): your affiliates sign in to it with their own session. You manage affiliates through Commerce > Affiliates. |
| internal service | 33 | Service plumbing: scheduled jobs (cron secrets), service keys, the storefront's own calls and link resolution, editor previews, public pages and files, signup. |
| dashboard duplicate of a public endpoint | 18 | Dashboard routes that do exactly what a documented endpoint does. Call the documented endpoint. |

### Two actions a key cannot take: consent

Two client endpoints record a person's consent, so they answer `403` to every API key and are done by the account owner signed in to the dashboard:

- accepting a plan change of the Kontrol subscription (`POST /v1/platform-subscription/plan-change/accept`): the acceptance of billing terms is recorded against the owner's login. Reading, declining or withdrawing a plan change works with a key;
- signing the KontrolPay agreement (`POST /v1/kontrolpay/applications/:id/agreement/sign`): the signature evidence needs a person. A key can create, fill, upload to and answer an application, but the first submission waits for the owner's signature.

### Background jobs belong to who started them

A background job (report calculations, bulk edits, imports, exports, schedule operations, metric calculations) is visible to the principal that started it, and only to it. A key lists, reads, cancels and resumes the jobs it created; a job started by a person in the dashboard does not appear for a key, and a key's job does not appear in the dashboard. Keep the job id you receive. A schedule operation a person left held in the dashboard can only be resumed by that person.

### Live data: poll

There is no push API for the account's data. The dashboard's live views are reproduced by polling: read `GET /v1/transactions` with `limit=20`, `count=0` and the default sort (newest first) every 30 seconds for the latest orders, and re-read the report you show (for example `GET /v1/metrics`) at the pace you need. Order and payment events of your checkouts can also be pushed to you by the checkout webhooks (Part 4, Outbound webhooks and services).

### Errors

Errors are JSON: `{"error": "<human message>"}`, plus `code` when the error has a stable machine code and `details` when a field failed validation. Act on the status and the `code`, never on the wording of `error`.

| status | meaning | what to do |
|---|---|---|
| `400` | the request failed validation; `details` names the field | fix that field; never retry unchanged |
| `401` | missing or invalid key (`Missing bearer token`, `Invalid API key`) | send `Authorization: Bearer <key>` with an active key |
| `402` | `subscription_required`: the account has no paid platform subscription | the account owner settles the subscription |
| `403` | `insufficient_scope` (see `requiredScope`), `subscription_module_required`, a banned account, or an endpoint-specific restriction | give the key the scope, or read the endpoint's errors; never retry unchanged |
| `404` | does not exist, or belongs to another account | treat as "does not exist" |
| `409` | revision, state or uniqueness conflict | re-read the resource and reconcile; never blindly overwrite or resubmit a payment |
| `410` | the operation is retired | use the replacement the endpoint names |
| `422` | the content is well-formed but not acceptable (for example a document with issues) | fix the reported issues |
| `429` | rate limited | back off and retry later |
| `500` | unexpected server error; the body carries a `requestId` | retry once later; report the `requestId` if it persists |
| `503` | temporarily unavailable (database busy, worker or feature not ready); `Retry-After` when known | retry after the delay; nothing was written when the database was busy |

A network failure is not proof that a write failed. Read the resource, the job or the payment status before you send a write again.

### Rate limits

Limits count requests per client IP address per minute. Defaults (an operator can change them):

| scope of the limit | requests per minute |
|---|---|
| any route without its own limit (the account routes) | 300 |
| `POST /v1/charge`, the 3-D Secure sessions | 3000 |
| `POST /v1/charge/status` | 120 |
| `/v1/reports/*`, `/v1/report-jobs/*`, `GET /v1/status/daily` | 60 |
| `POST /v1/checkout/pre-auth` | 30 |
| the partner refund, transaction, chargeback and scrub routes | 20 |
| `/v2/rebill-batches` creation | 20 |
| the cart-recovery ingestion (`/v1/recovery/carts*`), per key | 1200 |

A `429` means slow down: wait, then retry with exponential backoff. Poll jobs with a bounded interval (a few seconds, growing) rather than in a tight loop.

### Idempotency and retries

- `POST /v1/charge`: `orderId` is the idempotency key, per API key. Sending the same `orderId` again with the same key returns the first result instead of charging twice. Keep one key per integration so its retries share that space. After a timeout, read the outcome with `POST /v1/charge/status` or `GET /v1/charge/orders/:orderId` before anything else.
- Report jobs: `POST /v1/metrics/jobs` takes a `requestId` (a UUID you generate). The same `requestId` identifies the same attempt, so a retry does not start a second job.
- Other long operations (bulk edits, imports, exports, creative jobs, subscription jobs) return a job: create it once, then poll the job. Several accept a request id or idempotency token; the endpoint documents it.
- Never replay a payment, a refund or a force bill because a response was lost or a redirect failed: read the existing transaction, refund or job first.

### Pagination and totals

- Lists take `limit` and `offset` (zero-based) unless the endpoint documents a cursor. Each endpoint gives its default and its maximum `limit`; keep the same filters, dates and sort while paging.
- A list that returns `total` may also return `totalExact: false`: `total` is then a lower bound (the count stops at a cap). `count=0`, where offered, skips the total (`total: null`) and is faster.
- A short page (fewer rows than `limit`) is the end of the list.
- For a complete download use the endpoint's export or its job, not deep offsets.

### Dates, time zones and money

- Dates and times are ISO-8601. Instants are UTC (`2026-08-01T00:00:00Z`). Report windows take `from` / `to`, or `hours` (a trailing window) when `from` / `to` are omitted, and `tz`, an IANA zone (`Asia/Dubai`) that decides the hour and day buckets. Convert calendar days with the account's time zone and keep that zone across metrics, lists and drill-downs.
- Money: read each field's unit. Fields named `*_cents` or `*Minor` are integer minor units (`6197` is USD 61.97 when the currency has two decimals). `amount` on `POST /v1/charge` and on the partner refund routes is a decimal amount in major units (`9.99`). Keep each row's currency: never sum different currencies and never assume a universal divisor of 100.
- Large integers stored as `bigint` (`monthly_cap_cents`, `used_cents`) arrive as JSON strings. Parse them before arithmetic, without floating-point rounding.
- Field names are exact: contracts mix camelCase (`baseRevision`) and snake_case (`amount_cents`). Never re-case keys.

### Reading the data correctly

These rules prevent plausible-looking wrong answers.

- Rates are ratios unless a field says otherwise: `0.44` is 44%. Configuration fields have their own units (3000 basis points is 30%).
- Never average a rate across rows. Recompute it from its components: approval rate = sum of approved / sum of completed, where completed is the live completed charges (approved, declined, error, unknown; no test card, no CSV import, no 3-D Secure park).
- Quantity never scales a statistic: an order of 3 units is one sale; `units` is reported separately.
- A refusal Kontrol makes before any gateway (blacklist, filter or velocity guard, BIN scrub, card pre-check, card cooldown, 3-D Secure policy) is a rejection, not a transaction: it appears in `results[].rejected` of `POST /v1/charge` and in `GET /v1/rejections`, never in a transaction list or an approval rate. A decline is a gateway verdict (`declined`) or a technical error (`error`).
- `refunded=true` filters on the refund date, not the sale date.
- `(unknown)` is a real bucket: wallet payments carry no card number and no browser context, so brand, device and OS are genuinely absent.
- An ATRI is a routing pool (in addresses: `trips`). A MID is one merchant account at a gateway (in addresses: `accounts`).

## 2. Workflows

### Build stores, product pages and checkouts

#### Native funnels without a store

For editorial, product-selection, questionnaire and checkout funnels, use the native Funnel Builder and Flow Builder. A product page is a `landing` document with explicit account-owned catalogue offers; no store is required. `POST /v1/v5/catalog/products` creates reusable catalogue data with idempotent `requestKey`; `GET/PATCH /v1/v5/catalog/products/:id` reads/edits it with exact `baseUpdatedAt`. Upload media through `/v1/v5/funnels/:id/assets` and fonts through the editor font API.

Compose semantic text/media/disclosure, tabs, galleries, collections, sliders and popups from native blocks. Commerce blocks bind actual offers, variants, quantity and explicit purchase mode. Quiz blocks validate declared options. Use `funnel.checkout` for graph continuation and native checkout form/payment blocks for payment. Do not reproduce a page as an image, iframe or HTML/script embed.

Follow the complete native funnel recipe and schemas (see *Build an entire funnel without a store* under *Pages and flows* in Part 2), then the commerce workflow (see *Native store-free funnels* under *Commerce workflows* in Part 2). Keep initial selection, required option confirmations, server quote revision, subscription terms and billing/delivery fields intact while matching the reference. Validate desktop/mobile behavior and each navigation edge; a preview is not a payment success.

The store/product recipes were source-reviewed on 2026-10-18; commerce access, storefront theme and checkout integration updates below were reviewed on 2026-11-11. An agent is an external REST client, not a separate server endpoint. Use the account-scoped endpoints and the authentication documented for each operation. Read the endpoint reference (Part 4) for parameters, examples and errors. Replace identifiers with values returned by your own account.


Current supplements: V5 agent workflows in *Commerce workflows* in Part 2, authentication, reporting and job recovery in *Operations, reporting and current behavior* in Part 2, the complete method/path and scope index in the endpoint index (Part 3), and account agreement generation in *Account agreements* in Part 2. A visible UI action does not imply API-key authorization. The store/catalogue recipe in sections 3–5 is one workflow; an autonomous standalone offer link (see *Standalone checkouts and saved offer links* in Part 2) requires neither a connected store nor an existing product catalogue.

#### 1. Know which object you are editing

| Object | API surface | What it changes |
|---|---|---|
| Store | `/v1/checkouts` and `/v1/checkouts/:shopId` | Domain, brand, contact information, platform, shipping protection |
| Store site content | `/v1/checkouts/:shopId/storefront` | Company identity, About us, home copy, FAQ, brand kit, fonts, site-wide content |
| Product | `/v1/checkouts/:shopId/products/:pid` | Product facts and separate options, variants, media, sections and pricing tables |
| Storefront theme | `/v1/checkouts/themes/custom` | Product, home, collection and content-page layout |
| Checkout profile | `/v1/checkouts/profiles` | Payment route and reusable checkout configuration |
| Checkout document | `/v1/checkouts/profiles/:id/document` | Checkout editor blocks, styles, variables, drafts and versions |
| Store checkout assignment | `/v1/checkouts/:shopId/checkout` | A direct checkout or a published flow; A/B and Conditions are nodes inside the flow |
| Standalone checkout template | `/v1/checkouts/standalone` | Reusable published design and payment settings on an ownership-verified serving domain |
| Saved autonomous offer | `/v1/checkouts/standalone/:id/short-links` | Link-specific products, prices, branding, integrations and pixels; no store/catalogue dependency |
| Funnel page | `/v1/v5/funnels` | Landing, post-sell or Thank-you document and published versions |
| Flow | `/v1/v5/flows` | Entry, pages, checkout, weighted A/B, Conditions and confirmation paths |
| Bank/MID storefront catalog | `/v1/storefronts` | Gateway basket catalog. **Does not create a customer-facing store or product page.** |

Storefront theme documents and checkout editor documents are different formats. Never submit one to the other's endpoint. A Shopify store keeps its product pages in Shopify; the in-house theme editor does not rewrite its Shopify theme. `cms: "product"` creates the in-house store type. `cms: "shopify"` and `cms: "medusa"` represent integrations; use their dedicated setup workflows.

#### 2. Authenticate and discover before writing

For the merchant store-building requests below, use an existing API key of the account in `Authorization: Bearer` with the required category scopes. A key stays account-scoped and acts as the account administrator, never as platform super admin. A Supabase access JWT is the human-session alternative; some operations require that session rather than a key, as specified in the endpoint reference. Do not put credentials into URLs, source files, screenshots or saved request examples.

Affiliates work in their own affiliate workspace; it is not part of the client API. Shared checkout View permits an affiliate's own saved offers on an active published template; it does not grant merchant configuration or publication. Every owned checkout uses the current commerce runtime without version enrollment or a flow-runtime feature switch. Active stores, publication, ownership, integration configuration and access checks remain mandatory.

Shell examples use Bash, curl and jq. For requests without a body (including DELETE and bodyless POST), add `-H 'Content-Type:'` to suppress the helper's JSON header; an empty JSON body is invalid:

```bash
export API='https://api.kontrolcheckout.com'
# Populate KONTROL_API_KEY through your secret manager; do not commit it.
api() { curl --fail-with-body --silent --show-error -H "Authorization: Bearer $KONTROL_API_KEY" -H 'Content-Type: application/json' "$@"; }
api "$API/v1/checkouts" > stores.json
api "$API/v1/atris" > atris.json
api "$API/v1/checkouts/profiles" > checkouts.json
api "$API/v1/checkouts/themes" > theme-catalog.json
```

Scoped keys need `checkouts.read` for these GETs and `checkouts.write` for store, product, theme and checkout mutations. `/v1/editor/*` uses those same scopes. `GET /v1/me` (the key's identity) uses `settings.read`; failing that call does not prove a checkouts-only key is invalid. `GET /v1/atris`, the ATRI picker, uses `routing.read`. `/v1/storefronts/*` is `routing.read/write`. Pixel/event routes are `tracking.read/write`. A `403` with `code: "insufficient_scope"` includes `requiredScope`. Do not expand your own permissions to evade a refusal.

Choose existing IDs from these results; never invent an ATRI, API-key, product, variant, integration or store ID. If a request times out after a write, read the relevant list/detail before retrying: most creation routes are not idempotent.

#### 3. Create an in-house store and establish its payment route

This minimal store body is valid. Use a domain you control and intend to connect, not the sample domain:

```json
{"internal_name":"Demo store","shop_name":"Demo","domain":"shop.example.com","cms":"product","register_domain":false,"is_active":false,"primary_color":"#2255AA","support_email":"support@example.com","shipping_protection_mode":"off","shipping_protection_price_cents":0}
```

```bash
api -X POST "$API/v1/checkouts" --data-binary @store-create.json > created-store.json
SHOP_ID=$(jq -er '.shop.id' created-store.json)
api "$API/v1/checkouts/$SHOP_ID" > store.json
```

`internal_name`, `shop_name` and hostname-only `domain` are required. No scheme, slash or path in `domain`. `register_domain:false` skips external domain registration while creating an inactive draft store for API building and signed preview. Omit it (default true) for normal registration. Later use the store domain verification/setup workflow when the real domain is ready. Normal creation tries domain registration and can return a saved store with `domainWarning`; that is not permission to POST another duplicate store. Inspect the Domain/overview result before retrying provider work.

Every new in-house store (`cms:"product"`) initializes an owned checkout route, including stores created with a payment provider. The route owner is resolved from the provider account when present, otherwise from the creating account. This allows authorized checkout assignment immediately; a separate routing write is not required just to attach a checkout. Ownership does not imply payment readiness. When configuring the underlying charging route, save the account route explicitly:

```bash
jq -n --arg atri "$ATRI_ID" --arg key "$ROUTE_KEY_ID" \
  '{atri_id:$atri,api_key_id:$key,crm:"nmi",active:true,apple_pay:false,google_pay:false}' > routing.json
api -X PUT "$API/v1/checkouts/$SHOP_ID/routing" --data-binary @routing.json
api "$API/v1/checkouts/$SHOP_ID/overview" > overview.json
```

`api_key_id` is the ID (from `GET /v1/keys`) of the account API key this route charges with, not its secret; it does not have to be the key your curl requests use. Choose the route from the real account configuration. A store with no account cannot receive a shared checkout (`422`). All newly created in-house stores already carry an owned route; routing writes configure that existing route. Legacy unassigned stores are not claimable by arbitrary accounts and require administrative assignment. Do not activate wallets merely because a design includes wallet buttons: live providers and their domains must be configured.

Set logo/favicon using `PUT /v1/checkouts/:shopId` with `logo_url`, `favicon_url`, `logo_height_override` and `primary_color`. This store update is a partial update, despite using PUT. `logo_url` must be a URL. Upload a local asset first:

```bash
curl --fail-with-body --silent --show-error -X POST \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H 'Content-Type: application/octet-stream' \
  --data-binary @logo.png "$API/v1/checkouts/$SHOP_ID/assets?content_type=image%2Fpng&prefix=logos"
```

Use the returned URL. Binary upload avoids base64 expansion. The legacy JSON upload accepts `content_type`, `data_base64` and optional `prefix`. Product media has separate routes below.

#### 4. Create the complete product, then review and publish

These product endpoints manage the **internal Kontrol catalog** used by the in-house storefront. They do not create or edit upstream Shopify products or a Shopify theme. Catalogue CRUD and paging requests are routed to the API database regardless of the deployment's `CHECKOUT_DATA_LOCAL` setting; callers do not need to enable that flag. For a visible legacy store ID, the server resolves its internal store identity before accessing products. Use IDs returned by the API and keep the selected store context. Store settings, provider integrations and the legacy read-only product-stats RPC retain their own storage routing. A visible legacy store without an internal copy returns 409; a missing store returns 404. Availability changes validate target-store visibility before mapping their IDs.

The existing `POST /v1/checkouts/:shopId/products` also accepts a complete product in one atomic write. It creates the product, listing, option matrix, prices, gallery, specifications, sections and page settings together. A validation or ownership failure leaves no partially created product. The response remains HTTP 201 **the product row directly**, so read `.id`, not `.product.id`. Use the detail GET to verify related arrays.

```json
{
  "title":"Demo mug",
  "handle":"demo-mug",
  "subtitle":"Everyday essentials",
  "description":"A ceramic mug.",
  "currency":"USD",
  "status":"draft",
  "is_active":false,
  "vendor":"Demo",
  "product_type":"Mug",
  "tags":["ceramic","mugs"],
  "seo_title":"Demo ceramic mug",
  "seo_description":"Explore the Demo ceramic mug.",
  "price_cents":2499,
  "compare_at_price_cents":2999,
  "sku":"MUG",
  "inventory_qty":20,
  "options":[{"name":"Color","display_type":"button","values":[{"value":"Blue"},{"value":"White"}]}],
  "variants":[
    {"option_values":["Blue"],"sku":"MUG-BLUE","price_cents":2499,"inventory_qty":10,"is_active":true},
    {"option_values":["White"],"sku":"MUG-WHITE","price_cents":2599,"inventory_qty":10,"is_active":true}
  ],
  "media":[{"url":"https://assets.example.com/mug.jpg","alt":"Blue ceramic mug","kind":"image"}],
  "specs":[{"label":"Material","value":"Ceramic"}],
  "tiers":[{"min_quantity":2,"discount_pct":10,"unit_price_cents":null}],
  "sections":[{"type":"faq","enabled":true,"props":{"heading":"Product questions","items":[{"q":"Material?","a":"Ceramic."}]}}],
  "page_config":{"buyButton":{"label":"Add to cart","showPrice":true},"stickyBar":{"enabled":true,"label":"Add to cart"}}
}
```

Replace the example image with an actual approved HTTP(S) asset before sending. Atomic creation stores media URLs without contacting external hosts or rehosting. `media` accepts at most 100 entries; upload/rehost separately when needed. No variant UUIDs are supplied at creation: `option_values` contains the exact declared texts in option order. Duplicate combinations and values outside the declared matrix are rejected. Top-level price/SKU/inventory provide matrix defaults; explicit variants override their combination. Omit options for a single default variant. Supply `bundle` with existing component variant IDs belonging or linked to this store; `subscription_product_id` must likewise belong to the account. Unknown top-level fields are rejected. Body limit: 2 MiB.

All core fields also remain accepted: nullable `gift_banner_text`, `scarcity_text`, `social_proof_text`, `rating_value`, plus `rating_count` and nullable `subscription_product_id`. Only publish genuine rating/customer evidence. `status` controls the product; `is_active` controls its listing on this store. Neither activates the store. IDs, timestamps and `product_url` are server-managed; do not send them as editable fields.

```bash
api -X POST "$API/v1/checkouts/$SHOP_ID/products" --data-binary @complete-product.json > created-product.json
PRODUCT_ID=$(jq -er '.id' created-product.json)
api "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID" > full-product.json
jq '{product,options,variants,media,tiers,bundle,shops}' full-product.json
```

##### AI copy and page creation in the same workflow

AI is an optional preceding step. Read configured integrations first. With an enabled OpenAI or Anthropic integration, create `/v1/integrations/creative/jobs` using a fresh UUID `requestId`, `provider` and `input:{prompt,system?,maxTokens?}`. Ask for copy based only on supplied product facts. Read `job.status`; only `completed` output is usable. Anthropic text is in `job.result.content` entries of type `text`; OpenAI text is in `job.result.output[].content` entries of type `output_text`. Parse any requested JSON as data, review claims and map supported fields to `description`, SEO and the `sections`/`page_config` structures above. A creative result is not automatically a product or a page.

See *Creative integrations* in Part 2 for exact request, idempotency and failure behavior. `uncertain` or incomplete output is not a reason to submit a second billable request automatically. If no provider is configured, use supplied copy and report AI as untested; do not claim generation occurred. Provider integration settings and creative jobs require `integrations.read/write` in addition to `checkouts.read/write`.

For an existing product, apply reviewed copy using core PUT and the separate sections/page-config routes. Use the store's theme palette to position those sections, then open its signed product preview. To add one or several existing catalog products to another store, call `POST /v1/checkouts/:shopId/products/attach` with `{"productIds":["<product-id>","<another-product-id>"]}` (1–200 UUIDs). This additive operation keeps other store listings and existing prices/positions, and safely accepts retries. Use `/availability` only when replacing the complete intended listing selection or changing a store price; omitted stores are unlisted. Choose a checkout from `/v1/checkouts/profiles` and assign it to that store with `POST /v1/checkouts/:shopId/checkout` and `{"checkoutId":"<chosen-profile-id>"}`. That store-level choice applies to its products, not only the newly created product. For a new inactive store, complete the remaining route/theme/domain setup and verify checkout before activation.

##### Incremental product editing


A product has at least four independent readiness conditions: active core status, active priced variant, active store listing and reachable storefront. Minimal creation defaults to a draft and inactive listing. Full creation can set core status and listing activity explicitly; it does not activate the store or configure a payment processor.

```bash
api -X POST "$API/v1/checkouts/$SHOP_ID/products" -d '{"title":"Demo mug"}' > created-product.json
PRODUCT_ID=$(jq -er '.id' created-product.json)
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID" \
  -d '{"title":"Demo mug","handle":"demo-mug","currency":"USD","description":"A ceramic mug.","status":"draft"}'
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/options" \
  -d '[{"name":"Color","display_type":"button","values":[{"value":"Blue"},{"value":"White"}]}]' > full-product.json
```

Options are an array, not `{options: [...]}`. Up to two options, 50 values per option and 200 Cartesian combinations. Saving options rebuilds the variant matrix. For a product with no options, save `[]`; rebuild creates the default variant. Read the resulting `variants` array and price every intended active variant:

```bash
jq '[.variants[] | {id,sku:(.sku // ""),price_cents:2499,compare_at_price_cents:null,inventory_qty:null,is_active:true,image_url:(.image_url // "")}]' full-product.json > variants.json
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/variants" --data-binary @variants.json
api -X POST "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/media" \
  -d '{"url":"https://cdn.example.com/mug.jpg","alt":"Blue ceramic mug","kind":"image","rehost":true}'
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/specs" \
  -d '[{"label":"Material","value":"Ceramic"}]'
```

Replace the sample media URL with your actual asset. In this USD example, `price_cents:2499` is USD 24.99, not a decimal-dollar price. Follow each endpoint's currency and unit contract; do not extrapolate this example to every monetary API. Variant updates require existing IDs, and defaulted fields may overwrite omitted values: preserve returned fields when editing an existing catalog. Renaming an option value creates a new value identity; vanished combinations are deactivated, not deleted. Re-read variants after option changes.

Optional quantity discount:

```json
[{"min_quantity":2,"extra_off_cents":500,"discount_pct":0,"label":"Buy two","badge":"Bundle","unit_price_cents":null}]
```

Send that array to `PUT .../tiers`. `unit_price_cents` omitted preserves a legacy fixed unit price; explicit null clears it. Do not confuse `extra_off_cents` with a final unit price. Bundle components are a separate array sent to `PUT .../bundle`:

```json
[{"component_variant_id":"<existing-component-variant-uuid>","quantity":1,"is_gift":true,"price_override_cents":0}]
```

After creation, products, options, variants, tiers, bundles, specs and media have separate update resources. A core product PUT does not save those arrays. The complete POST below can initialize them atomically.

##### Product page content

`PUT .../sections` accepts an ordered array (max 30). Types currently supported: `info_tabs`, `logos_carousel`, `ugc_videos`, `rich_section`, `reviews`, `faq`, `customization`. Read the current product's returned `product.page_sections` before replacing them; the concrete props below are supported by the renderer. Unknown invented props may validate as records but have no renderer. Do not create fabricated reviews or claims to fill examples.

The following complete section payload uses renderer-supported props. It replaces the current section list, so merge existing sections first when editing an established product. The placeholder image URL must be replaced with a real uploaded asset URL.

```bash
cat > sections.json <<'JSON'
[
  {"type":"info_tabs","enabled":true,"props":{"tabs":[
    {"key":"why","title":"Description","body":"<p>A ceramic mug for everyday use.</p>"},
    {"key":"specs","title":"Specifications","body":"<p>See product specifications.</p>"}
  ]}},
  {"type":"rich_section","enabled":true,"props":{
    "layout":"image_text","eyebrow":"Everyday essentials","title":"Your morning companion",
    "mediaUrl":"https://assets.example.com/mug.jpg","side":"left",
    "body":"<p>A simple design for your daily coffee or tea.</p>"
  }},
  {"type":"rich_section","enabled":true,"props":{
    "layout":"feature_grid","title":"Product details","mediaUrl":"https://assets.example.com/mug.jpg",
    "items":[{"iconUrl":"","title":"Material","text":"Ceramic"}]
  }},
  {"type":"rich_section","enabled":true,"props":{
    "layout":"how_to_steps","title":"Getting started",
    "steps":[{"imageUrl":"https://assets.example.com/mug.jpg","title":"Before first use","text":"Wash according to the product care instructions."}]
  }},
  {"type":"faq","enabled":true,"props":{"heading":"Product questions","items":[
    {"q":"What is it made from?","a":"Ceramic."}
  ]}}
]
JSON
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/sections" --data-binary @sections.json
```

The `specs` tab automatically uses saved specification rows when present. A rich section's `layout` selects the supported renderer; arbitrary new layout names or prop names do not create new functionality. Product content remains separate from the theme's section placement: the selected storefront theme must include the corresponding section type to render it.

`PUT .../page-config` accepts the full page-config structure, with defaulted nested objects. Read `product.page_config`, merge changes and send the resulting object; sending a tiny partial object can reset other sections to defaults. Top-level keys: `subBar`, `banner`, `freeGift`, `priceBlock`, `bundles`, `salesPoints`, `buyButton`, `trustBadges`, `stickyBar`, `cartDrawer`, `overstock`, `lightbox`, `preOrder`. Unknown top-level keys are rejected. For example, a new product may start with:

```json
{"buyButton":{"label":"Add to cart","showPrice":true},"priceBlock":{"showCompareAt":true,"showSaveTag":true},"stickyBar":{"enabled":true,"label":"Add to cart"}}
```

After reviewing content and price, activate both product and listing:

```bash
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID" -d '{"status":"active"}'
jq -n --arg shop "$SHOP_ID" '{active:[{shop_id:$shop,position:0}]}' > availability.json
api -X PUT "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID/availability" --data-binary @availability.json
api "$API/v1/checkouts/$SHOP_ID/products/$PRODUCT_ID" > product-verified.json
```

Availability is the complete selected store list within the caller's visible stores. Preserve other intended listings when editing an existing shared product. Omitting `price_override_cents` keeps a store override; null clears it. Never guess a public product path from the UUID: customer paths use the saved handle; signed operator preview links are returned in overview/theme detail.

#### 5. Configure the home page and storefront theme

`GET /v1/checkouts/:shopId/storefront` returns the site content, theme information and preview information. The matching PUT is a whole editable-content save with defaults, not a deep patch. Keep existing fields by starting from the returned editable storefront object and stripping response metadata. The accepted top-level keys are:

`company`, `aboutUs`, `contactPhone`, `homeIntro`, `homeStory`, `homeTestimonials`, `homeFaq`, `brandKit`, `fontFamily`, `headingFontFamily`, `trackOrder`, `theme`, `colors`, `announcement`, `whyShop`, `keypoints`, `support`, `tiktok`, `whySoCheap`, `whyChooseUs`, `finalCta`, `footerMedia`, `pressLogos`, `languages`, `currencies`, `locales`, `customCss`, `customJs`.

`brandKit` is empty, `classic`, `editorial`, `warm`, `bold`, `performance` or `clinical`. `locales` is the real language-picker configuration: `fr,it,es,pt,pl,de,nl,sv,da,no,fi`; English is implicit. `languages`/`currencies` are decorative lists and do not enable translation or currency conversion. Checkout translation coverage differs from product-page coverage. Technical `whopTracking`, `handleRedirects` and `i18n` fields are preserved server-side, not edited through this form. Do not use custom JS/CSS to bypass payment or security logic.

##### Company identity and About us

In **Stores → Site content → Settings**, Company and About us are per-store content. The same fields are accepted by the storefront PUT:

```json
{
  "company": {
    "name": "Example Trading Ltd",
    "address": "12 Example Street\nExample City"
  },
  "aboutUs": {
    "title": "About our store",
    "intro": "Explore our collection and the details on each product page.",
    "sections": [
      { "title": "Product questions", "body": "Use the contact page for questions about a listing or an order." }
    ]
  }
}
```

This is the edited portion, not a replacement for the read-modify-write workflow above. Merge it into the full returned editable storefront object. The sample legal facts are illustrative: use only the merchant's verified company name and registered office, and leave unknown facts empty. `company.name` is at most 200 characters; `company.address` is a multiline string of at most 2000. Omitting the top-level `company` or `aboutUs` preserves that existing block for older clients; sending an empty object clears that authored block through its defaults. Existing defaulted storefront fields still require the complete configuration save.

`aboutUs.title` allows 160 characters, `intro` 4000, and `sections` up to 12 entries with `title` up to 160 and required `body` up to 8000. These fields are plain text; paragraphs use blank lines and stored markup is escaped. Unknown nested keys in these two new blocks or About sections are rejected. About text uses the existing storefront translations. Company facts are excluded from translation generation and overlay application.

The native page is `/about-us`, with `/pages/about-us` as a compatibility alias and supported locale prefixes such as `/fr/about-us`. Both point canonically to `/about-us` in the active locale. The nine native theme footers link to it. Custom About introduction or sections take precedence over old `homeIntro`/`homeStory`; with no authored About content the page reuses those fields, then a neutral localized introduction. A title alone does not suppress the home-copy fallback. No founding date, founder, certification or commercial promise is generated by the fallback.

Company and address appear below the native footer logo. The legal sentence names the store's domain and configured company; it omits the ownership sentence without a company name and omits the registered-office clause without an address. Native checkout and `/paid` confirmation use the same explicit store facts, independently of payment-provider identity. Blank configuration keeps these additions absent. External Shopify/Medusa storefront templates, their About pages and their footers require changes in their own source; saving this object does not publish them.

The checkout `site.footer` block has a separate `companyLegal` toggle, defaulting to true. Setting it to false hides that checkout block's company name, address and ownership statement without deleting the store's saved identity, its storefront legal pages or the separate default confirmation footer. The block's `disclaimer` control is independent. Modify and publish the intended checkout document rather than clearing company data across the account.

The same configured identity appears inside all five legal documents: Privacy Policy, Terms of Service, Refund Policy, Shipping Policy and Cookie Policy. This covers every native theme and custom content layout, Market policy dialogs, checkout policy dialogs and the existing support-policy export. The company name and address remain unchanged; the heading and ownership sentence are localized. Existing policy clauses are preserved. `/api/policies/:slug` returns the existing `{title, bodyHtml}` shape, resolves the current store hostname and does not accept `?shop` as a store override. A supported explicit `?locale` permits a 300-second public cache only outside signed previews; preview or inferred-locale responses are private and not stored.

The theme content palette now includes `content_about` with `classic` variant. It renders only in About context. Older stored non-empty content layouts gain this enabled block when absent, with a collision-free ID; an existing explicitly disabled About block stays disabled. Preview it using the existing signed content-preview route with `page=about-us`. This addition retains the site's existing noindex policy and does not change sitemap behavior.

##### Storefront themes

The built-in storefront catalogue contains Legacy (`legacy`), Market (`market`), Circuit (`builtin:circuit`), Depot (`builtin:depot`), Haven (`builtin:haven`), Pulse (`builtin:pulse`), Nest (`builtin:nest`), Terrain (`builtin:terrain`), Botanica (`builtin:botanica`) and Bikery (`builtin:bikery`). Use these exact selection IDs. A plain slug such as `circuit` still refers to an account-owned custom theme; it is not a built-in alias. These presets restyle existing sections and merchant data without adding commerce capabilities.

To select an appearance, call the existing assignment route and read back its assigned ID:

```bash
api -X PUT "$API/v1/checkouts/$SHOP_ID/theme" -d '{"themeId":"builtin:circuit"}' > theme-assignment-result.json
jq '.shop.theme_id' theme-assignment-result.json
```

Selecting a visual preset on a Legacy/Classic composition keeps its stable sections and overrides. Selecting it on a Market or custom composition preserves section IDs, types, variants, order, enabled states, settings and home/collection/content layouts through an account-owned copy in the existing custom-theme model. Existing per-store overrides are folded into that copy; explicit source font and supported token edits survive while default appearance values adopt the new preset. The copy is specific to the store, is reused for an identical saved manifest, and does not edit the source theme or other stores. The returned `shop.theme_id` can therefore be a private custom slug. Assignment checks the store version read before preparation; a concurrent change returns 409. Reload the store before retrying.

Explicit merchant font/colour settings remain authoritative in previews and saved themes. Plain presentation roots such as `circuit` are used in `document.root` and persisted `manifest.chrome.root`; the `builtin:` namespace belongs only to selection IDs. The existing cart, checkout, payment and routing contracts remain unchanged. Shopify and Medusa storefronts do not use these in-house skins.

For a custom layout, fetch the actual palette rather than inventing blocks:

```bash
api "$API/v1/checkouts/themes" > theme-catalog.json
jq '{rows,fonts,palette,groups,roots,pages,templates}' theme-catalog.json
api -X POST "$API/v1/checkouts/themes/custom" -d '{"name":"Demo site theme","basedOn":"legacy"}' > created-theme.json
THEME_ID=$(jq -er '.theme.id' created-theme.json)
THEME_SLUG=$(jq -er '.theme.slug' created-theme.json)
api "$API/v1/checkouts/themes/custom/$THEME_ID" > theme-detail.json
```

`basedOn` accepts any of the ten built-in selection IDs above. The existing database `based_on` remains `legacy` or `market`; a visual preset uses `based_on: legacy` plus its plain visual root. Optional `template` is an ID from the catalog's `templates`; Legacy/Market enforce template base compatibility, while a visual base retains its visual root when applying the validated page template. Custom-theme store assignment uses **slug**, while detail/update uses **UUID**. Theme document fields are `tokens`, `fonts`, `root`, `sections` (product page), and `pages` (home/collection/content). Use `theme-detail.json`'s expanded `document` as your starting point. `root` uses a plain value from the catalogue's `roots`, never a `builtin:` ID. Do not supply a checkout block document here.

```bash
# edited-theme-document.json is the expanded document read above and edited against the palette.
jq -n --slurpfile doc edited-theme-document.json '{draft:$doc[0]}' > theme-draft.json
api -X PATCH "$API/v1/checkouts/themes/custom/$THEME_ID" --data-binary @theme-draft.json
api "$API/v1/checkouts/themes/custom/$THEME_ID" > theme-preview.json
# Open returned preview.url / preview.pages links. Do not construct signatures yourself.
jq -n --slurpfile doc edited-theme-document.json '{document:$doc[0]}' > theme-publish.json
api -X PATCH "$API/v1/checkouts/themes/custom/$THEME_ID" --data-binary @theme-publish.json
jq -n --arg theme "$THEME_SLUG" '{themeId:$theme}' > theme-assignment.json
api -X PUT "$API/v1/checkouts/$SHOP_ID/theme" --data-binary @theme-assignment.json
```

Saving `document` publishes for every store already on that theme; it clears the draft unless an explicit draft accompanies it. `draft:null` discards work in progress. This theme API does not have the checkout document's `baseRevision` protocol: serialize writers and re-read before publishing. Theme validation returns named errors, not silently accepted arbitrary tokens. Directly assigning an existing custom slug clears per-store compiled theme overrides, as before; the visual-preset preservation copy above folds those settings into its own document instead. Preview links can be null when there is no eligible store/product or no preview host. A custom slug matching a plain preset name still resolves its own published/draft document and requires its signed theme preview claim.

#### 6. Build and publish a reusable checkout

```bash
api -X POST "$API/v1/checkouts/profiles" \
  -d '{"name":"Demo Checkout","applePay":false,"googlePay":false,"active":true}' > created-checkout.json
CHECKOUT_ID=$(jq -er '.checkout.id' created-checkout.json)
api "$API/v1/checkouts/profiles/$CHECKOUT_ID/document" > checkout-state.json
jq '.draft // .published // .defaultDocument' checkout-state.json > checkout-document.json
```

The machine-readable catalog is `GET /v1/editor/catalog?pageType=checkout` (requires `checkouts.read`). It returns `format`, `catalogVersion`, `pageType` (root fields/defaults, variables and visibility facts), all allowed `blocks` (fields/defaults/slots/constraints/variants), the grouped `library`, `defaultDocument`, and `templates` with ready-to-save documents and validation issues. This endpoint accepts **checkout only**; `landing`, `post_sell`, `thank_you` and unknown query fields return 400. For funnel pages read their own document resource's `draft`, `published` or `defaultDocument`, then use that resource's draft/publish validation. Function predicates are omitted from JSON; server validation remains authoritative. The catalog contains no account products or credentials; use entity endpoints when a block actually references a catalogue entity.

```bash
api "$API/v1/editor/catalog?pageType=checkout" > checkout-catalog.json
jq '.templates[] | {id,label,description}' checkout-catalog.json
# Choose an ID returned above, then start from its real document.
jq --arg id "$TEMPLATE_ID" '.templates[] | select(.id==$id) | .document' checkout-catalog.json > checkout-document.json
jq -e '.format == 1 and .pageType == "checkout"' checkout-document.json
```

Template node IDs are unique inside each returned document. Preserve them for subsequent edits; generate unique IDs when duplicating nodes within one document. The catalog response does not create a saved checkout or publish anything. Source definitions remain in `packages/editor-core/src/catalog/` and the API's synchronized editor core.

Checkout document shape:

```json
{"format":1,"pageType":"checkout","root":{"props":{"primaryColor":null,"accentColor":null,"legalLinkMode":"modal","showValidTick":true}},"content":[]}
```

That illustrates the envelope only; empty content is not a publishable checkout. Start from the real default document so required payment, contact, totals and address blocks remain. Each node has a unique `id`, registered `type`, `props` and optional named `slots`, `style`, `visibility`, `conditions`. Slot children are arrays of nodes; a flat arbitrary HTML object is not a block.

Use store binding fields correctly: `root.props.primaryColor:null` inherits `store.primaryColor`; `site.header.props.logo:null` inherits the store logo. These binding fields do not accept `$link`. Ordinary compatible color/image/text fields and style values can use link values, for example `{"$link":"theme_primary","fallback":"#2563eb"}`, `theme_surface`, `theme_on_primary`, `store_logo`, `store_name`. Fonts, spacing and colors belong in editor fields, not processor parameters. Localized text uses `{"$localized":true,"values":{"en":"Pay now","fr":"Payer"}}`. Device-specific values use the field's supported `$responsive` format. Validate every edit; not every field accepts every value kind.

For account entities, query `/v1/editor/entities/products?checkoutId=<id>&q=<text>&limit=50`, `/v1/editor/entities/subscription-products`, `/v1/editor/entities/discount-codes`. Resolve up to 100 refs with `/v1/editor/entities/resolve?refs=product:<uuid>,productVariant:<uuid>,checkout:<uuid>` (also `subscriptionProduct` and `discountCode`). Missing/foreign/deleted references all return `missing:true`. Use the exact entity-link structure declared by the relevant block field; never put an entire product snapshot where an ID/link is expected.

Draft saves use optimistic concurrency:

```bash
REV=$(jq -er '.draftRevision' checkout-state.json)
jq -n --argjson rev "$REV" --slurpfile doc checkout-document.json '{baseRevision:$rev,document:$doc[0]}' > checkout-save.json
api -X PUT "$API/v1/checkouts/profiles/$CHECKOUT_ID/document/draft" --data-binary @checkout-save.json > checkout-saved.json
jq '.issues' checkout-saved.json
```

A saved draft can still have validation errors. Refuse to call publish while any `issues[].severity` is `error`. On `409`, reload, merge deliberately and use the new revision; never overwrite concurrent work with a blind retry. Structural failures can return `400`; publish blocks invalid drafts with `422`.

```bash
api "$API/v1/checkouts/profiles/$CHECKOUT_ID/document/stores" > preview-stores.json
jq -n --arg shop "$SHOP_ID" '{kind:"preview",mode:"draft",storeId:$shop}' > preview-request.json
api -X POST "$API/v1/checkouts/profiles/$CHECKOUT_ID/document/links" --data-binary @preview-request.json > preview-link.json
# Open the exact returned URL. storeId:null uses the neutral sample context.
REV=$(jq -er '.draftRevision' checkout-saved.json)
jq -n --argjson rev "$REV" '{baseRevision:$rev,note:"Reviewed store-branded checkout"}' > publish.json
api -X POST "$API/v1/checkouts/profiles/$CHECKOUT_ID/document/publish" --data-binary @publish.json
jq -n --arg checkout "$CHECKOUT_ID" '{checkoutId:$checkout}' > assignment.json
api -X POST "$API/v1/checkouts/$SHOP_ID/checkout" --data-binary @assignment.json
```

`storeId` must come from the allowed preview-store list for the checkout's account. `kind:"canvas"` also requires an allowed `Origin` header; use `preview` for normal agent review. These links grant temporary access to drafts: keep them private and do not alter their signatures. Missing signing infrastructure returns `503`.

Profile payment settings use camelCase (`atriId`, `apiKeyId`, `threeDsIntegrationKey`, `applePay`, `googlePay`); store routing uses snake_case. Get `/v1/checkouts/profiles/3ds-options?checkoutId=<id>` and choose a returned configured integration. Do not invent or paste a PAAY API secret into `threeDsIntegrationKey`. A direct checkout assignment overrides the store's underlying route without rewriting its original payment columns. `{"checkoutId":null}` unassigns.

For a flow, send **only** `{"flowId":"<published-flow-uuid>"}` to the same assignment endpoint. It requires an enabled account/runtime, a valid published flow, and active, chargeable account-owned store checkouts on every payment branch. Standalone checkouts and saved-link pins cannot be assigned to a store flow. A direct assignment returns `{shop_id,checkout_id}`; a flow assignment also returns `flow_id`. The persisted bootstrap `checkout_id` is not evidence that every visitor takes that branch: actual routing is pinned per cart. Read back the store and verify the public journey.

```bash
# FLOW_ID comes from GET /v1/v5/flows and must have a published version.
jq -n --arg flow "$FLOW_ID" '{flowId:$flow}' > flow-assignment.json
api -X POST "$API/v1/checkouts/$SHOP_ID/checkout" --data-binary @flow-assignment.json
```

Never send both IDs, an empty body, `flowId:null` or `abTestId`; this strict schema returns 400. New experiments belong to a flow's weighted A/B node. `GET /v1/checkouts/ab-tests` retains history, but POST on that collection and PATCH `/:id` return **410** with `code:"checkout_ab_tests_retired"`. See *Pages and flows* in Part 2 for Entry, Conditions, version pinning and default confirmation behavior.

Version rollback is explicit: GET `.../document/versions`, POST `.../document/versions/:version/restore` with current `baseRevision`, inspect the restored draft, then publish its new revision. Restore alone does not change the live checkout.

##### V5 pages and autonomous links

For a storeless offer, select an active published standalone template, read `GET /v1/checkouts/standalone/:id/link-options`, then create its saved offer with `POST .../:id/short-links`. A minimal body is:

```json
{"name":"Travel bag campaign","parameters":{"currency":"USD","product1_name":"Travel bag","product1_variant":"Black","product1_price":"5999","product1_quantity":"1"},"active":true}
```

All `parameters` values are strings. This is one USD 59.99 product; no catalogue product/variant ID is required. The response contains `link`; read the inventory for its authoritative `url` and revision. Use `POST .../:id/link-assets` for an image, optional language/country/legal parameters and owner-scoped integration choices from link-options. Pixels are a separate top-level array on the link, with write-only server secrets; use the exact standalone link contract (see *Standalone checkouts and saved offer links* in Part 2). The merchant owns the template; a link editor's product choices do not alter it. A verified technical serving domain and valid payment configuration are still required. Use a signed template preview rather than a bare checkout URL with no basket.

Create a visual page with `POST /v1/v5/funnels` and, for example, `{"name":"Order confirmation","pageType":"thank_you"}`. Its 201 response is `{item:...}`. Read `GET /v1/v5/funnels/:id/document`, start from `draft // published // defaultDocument`, save through `/document/draft` using `baseRevision`, inspect issues and publish the corrected revision. Funnel documents and storefront theme documents are not interchangeable. Post-sell pages additionally require their published offer configuration; a decorative product block alone cannot authorize a charge.

Create and publish a flow from its returned graph, preserving the server-generated Entry identity. Pin the published pages, select checkout branches, and choose the published Thank-you page on its node. Post-sell buyers select only published offers; the server determines their prices, quantities and total, and preserves the initial payment's verified method, provider and MID. A wallet or wire uses its native confirmation; a card flow can require a fresh security code according to `paymentRequirements`. Do not submit PAN, MID or price overrides in a flow action. Read *Commerce workflows* in Part 2 for complete ordered requests and *Pages and flows* in Part 2 for valid graphs and multi-offer selection. Signed previews remain inert; rendering a Pay or Accept control does not test payment acceptance.

#### 7. Shipping, wallets and payment verification

Store shipping protection is configured with `shipping_protection_mode` (`off`, `on`, `forced`), `shipping_protection_price_cents`, label and description. Checkout `settings` can override these. A protection block is presentation; it does not create a shipping carrier tariff. Do not add an arbitrary `shipping_methods` array: the store schemas here do not define one. In the current checkout implementation, the built-in delivery method is free; verify actual cart totals and platform integration behavior rather than claiming unsupported live carrier rates. The example protection fee is a distinct line, never a disguised shipping charge.

A wallet block must exist in the document AND the route/profile/provider must offer the wallet on that visitor's device. Preview wallet logos are inert demonstrations. Their presence does not prove Apple Pay/Google Pay provisioning, domain validation or live charging. Special Pre-Auth has its own subscription/card-registration requirements and is not equivalent to a standard wallet sale. Payment brands displayed on the card field are not a processor enablement switch.

Review desktop, tablet and mobile: logo loaded, per-store color applied, one visible order summary per intended device, reviews not accidentally hidden with the whole sidebar, quantities/discounts/gifts/protection reflected in total, correct legal modal behavior, and no duplicate payment/protection controls. Test from the actual store product page through its cart, not solely from a mocked editor preview.

##### Update a Shopify or Medusa storefront integration

Use the merchant [integration guides](https://app.kontrolcheckout.com/integration-guides). Their downloadable resources are copied from executable integration sources; do not maintain a second hand-written checkout script in an agent answer.

For an existing Shopify installation, back up the active theme and replace **both** `assets/cart-checkout-btn.js` and `snippets/cart-checkout-btn.liquid` with the current [JavaScript](https://app.kontrolcheckout.com/integration-guides/downloads/cart-checkout-btn.js) and [Liquid](https://app.kontrolcheckout.com/integration-guides/downloads/cart-checkout-btn.liquid). Keep the existing `{% render 'cart-checkout-btn' %}` calls and label settings. Saving an active external theme publishes that change; a Kontrol deploy alone does not update an already installed Shopify asset. Restore both files together to roll back.

The current Liquid uses a native button and retains one click that arrives before its lazy JavaScript is ready. It immediately shows loading, executes that queued navigation once when ready, and restores a retryable button on a script error or a 15-second load timeout. Late script arrival after timeout does not execute the stale click. The JavaScript also preserves UTM sets and supported click IDs, synchronizes cart quantities and suppresses duplicate checkout dispatch. Updating only the Liquid does not upgrade an old JavaScript's attribution handling.

Verify with a new cart entered using `?utm_source=integration_check&utm_campaign=checkout_check`: change quantity/variant, open the real cart drawer, click checkout once, then check retained markers and matching totals on the owned checkout domain. Test the first click before the script finishes loading, and a failed-script retry separately. Homepage or locale middleware that drops the query must be corrected in that storefront's source; a later checkout cannot reconstruct discarded campaign values.

Medusa recovery preserves the upstream `prod_` and `variant_` identifiers alongside the internally priced cart. Older saved carts can recover those identities only through catalogue rows belonging to the same store. An unresolved or mismatched identity is a conflict to investigate, not permission to replace a signed basket, fabricate IDs or accept client-supplied prices. Receipt images likewise come from the verified server cart; test the original product, selected variant, free gift and accepted upsell in the final summary. No new integration parameter or catalogue duplication is required for these fixes.

Technical payment-return URLs are issued on the canonical API origin, while the buyer resumes the original validated checkout/flow. Do not rewrite provider-required merchant identity, wallet domains or ACS URLs to match the API. Follow the flow integration checklist (see *Verify a store-to-flow integration* under *Commerce workflows* in Part 2) to distinguish simulator results, browser evidence and actual provider tests.

#### 8. Local HTTP probe plan (isolated fixture environment)

Use a disposable local database, fixture-owned API keys, fake domain-registration and asset-upload adapters, and a local storefront configured to the same database. Do not point test creation at production Render/DNS/Shopify. Use `register_domain:false` on the create-store request: inactivity alone does not suppress external domain registration.

1. GET catalogs with a checkouts-read key; verify write returns `403 insufficient_scope`.
2. POST store and read back its UUID; assert owner visibility and hostname validation. Retry read after an injected post-commit transport failure, not another POST.
3. PUT route using fixture ATRI/key. Reject foreign-account selections. Create product, save two option values, confirm two variants, set integer-cent prices and add fixture media.
4. Activate product + listing; assert a second account cannot read/write it. Edit availability without a price override and confirm the prior override survives; explicit null clears it.
5. PUT quantity tiers and bundle gift; visit product/cart and verify merchandise/discount/protection arithmetic. Exercise variant switch and quantity updates.
6. Create custom theme from a catalog template; save draft, inspect previews, publish and assign by slug. Reject unknown token, invalid template and wrong document format.
7. Create checkout profile; GET default; save draft at revision N. A second save at N must return 409. Save corrected content using current revision. An invalid draft must not publish; a valid draft returns incremented publishedVersion.
8. Mint preview for allowed store and null; reject foreign store and unlisted canvas Origin. Verify store colors/logo match and null preview uses sample data.
9. Assign checkout; verify public render and retained original route. Restore a version to draft and confirm the live version stays unchanged until publish.
10. Use only configured reserved test-card handling or a gateway sandbox for success/decline. Assert order/transaction attribution, test flags, thank-you totals and no real export/fulfillment. For 3DS, separately exercise an actual sandbox ACS challenge, cancellation, timeout and callback replay; a reserved success card that bypasses 3DS cannot prove challenge behavior.

Cleanup only the explicitly disposable fixtures. Record HTTP status, response issues, created IDs, expected totals and screenshots. Report which steps ran versus which were only specified; never turn this checklist into an unexecuted claim of coverage.

### Commerce workflows

Commerce workflows were source-reviewed on 2026-11-02; the checkout integration, attribution, receipt and payment-return updates below were reviewed on 2026-11-11. Base URL: `https://api.kontrolcheckout.com`. Use the endpoint index (Part 3) and the endpoint reference (Part 4) for exact parameters and errors. This guide describes registered merchant REST operations and separates them from native affiliate and buyer-runtime capabilities.

#### Start with identity and existing resources

Every independent merchant and owned checkout uses the same commerce capabilities. Shared account identity is provisioned automatically for old and new records; no release enrollment or feature activation is required. Roles, affiliate grants and sharing still apply. Identity provisioning does not publish or assign a flow to a store. A direct checkout remains direct and a flow follows its published graph.

Ordinary `GET /v1/filters/facets` includes the account's flows and affiliates without `v5=true`. Reports include the relevant commerce facts without a version opt-in; old facts without recorded flow attribution remain unattributed rather than invented. Historical `/v5/` route names and `v5_flow` fields remain supported API contracts, not product activation switches. Missing mandatory schema is a deployment failure, never a signal to use a feature-reduced legacy mode.

Workers run on the elected API job leader when `BACKGROUND_JOBS_ENABLED` permits jobs. The API `CHECKOUT_ENCRYPTION_KEY` and storefront `ENCRYPTION_KEY` derive the same purpose-specific HMAC key; a dedicated `V5_FLOW_EFFECTS_SECRET` overrides that fallback on both services. Never expose these keys to a browser or agent prompt. Missing or invalid effect authentication rejects worker startup.

An API key of the account, sent as `Authorization: Bearer <key>`, needs the endpoint's read/write category scope. It never grants super-admin powers or bypasses a session-only route. Account ownership, published state and live access checks still apply. See *Operations, reporting and current behavior* in Part 2.

Affiliates work in their own affiliate workspace; it is not part of the client API. Never send `accountId`, creator identity or an arbitrary affiliate ID to override ownership.

Discover before creating. Use `GET /v1/checkouts/standalone`, `GET /v1/v5/funnels` and `GET /v1/v5/flows`, then read the chosen resource. UUIDs below are placeholders for IDs returned in this account. Foreign or unpublished resources can return 404. Editing a document does not publish it or change background-job configuration.

#### Native store-free funnels

Source-reviewed 2026-11-16. A complete `landing → product selection → quiz → checkout` journey can use native Funnel Builder documents and a Flow Builder graph without a store or store product page. Product pages use the `landing` document type with explicit owned offers. Reuse account catalogue products; do not duplicate a product merely to put it on another page.

1. Create/reuse catalogue data with `POST /v1/v5/catalog/products`, `GET /v1/v5/catalog/products/:id`, and `PATCH /v1/v5/catalog/products/:id`. Create uses a persistent `requestKey`; edit uses the exact returned `baseUpdatedAt`. Catalogue routes need `checkouts.read/write` and merchant management rights.
2. Upload page images/videos with `POST /v1/v5/funnels/:id/assets`; use the returned hosted URL. Static SVG is validated; scripts/HTML are not an import mechanism. Fonts retain the existing editor-font API.
3. Bind one to ten explicit published offers to native commerce blocks. One-time versus subscription is explicit. Render `commerce.purchaseTerms` from the selected server plan. Required variants use `requireChoice:true` and concrete `confirmedOptions`.
4. Publish pages/checkouts first, then the graph, then create the shared saved flow link. `kontrolcheckout.com` supports store-free checkout hosting; custom domains retain ownership checks. Session versions remain pinned.
5. Buyer `continue` carries `initialSelection` and optional enum-only `quizAnswers`. The checkout cart endpoint requires the latest `initialCart.revision`. Neither operation charges. Once payment is reserved, cart edits are refused.

Saved flow links enter the pinned graph's first page, including any preceding A/B decision. Do not bypass the landing/product/quiz chain because no cart has been selected yet. The checkout URL resumes the current flow node; direct checkout links without an explicit landing still start at checkout.

Read *Pages and flows* in Part 2 (Build an entire funnel without a store) for complete catalogue fields, native block names, quiz limits, request examples and concurrency behavior. Documents are bounded to 2 MiB/depth64 with a 2.5 MiB draft-request budget. Media is separate.

Separate checkout delivery uses optional strict `shippingAddress`; flat charge address fields remain billing. When omitted, the existing same-address path remains unchanged. The receipt retains both shipping and nested billing data. Do not alter prices, attribution, routing or payment policy when reproducing a reference layout.

#### Reusable checkout design, independent saved offer

The checkout owns its design, verified domain, published settings and payment routing. Each saved offer owns its product descriptions/prices, permitted presentation parameters and pixel configuration, with an immutable revision. No store or catalogue product is required for an autonomous saved offer. Legacy catalogue-backed parameters remain readable/usable where supported; they are not a prerequisite for a new link.

1. Select a published active standalone checkout. A merchant can create and publish the design through `/v1/checkouts/standalone` and its documented settings/document operations. Affiliate blank creation and template publication remain forbidden; use a shared checkout or permitted duplicate.
2. Read `GET /v1/checkouts/standalone/:id/link-options`. It returns published parameters/bindings, locale/legal defaults and safe owner integration choices. It does **not** return a product catalogue. `allowPriceOverrides:true` reflects independent saved-offer pricing; the old template price-override policy is not a gate on these offers.
3. Create with `POST /v1/checkouts/standalone/:id/short-links`. The response is HTTP 200 with `{link:...}`. Read the inventory to obtain the public URL and current revision.

```json
{
  "name": "Linen shirt offer",
  "parameters": {
    "product1_name": "Linen shirt",
    "product1_price": "6798",
    "product1_quantity": "2",
    "product1_variant": "Blue / Large",
    "currency": "USD",
    "offered_languages": "en,fr"
  },
  "pixels": [],
  "active": true
}
```

`product1_price` is a **unit price** in integer minor units; the example is two USD 67.98 shirts. Product slots are 1–10, quantity is 1–99. Optional image, comparison price and variant label are display/offer fields, not invented catalogue IDs. All parameter values are strings. Read *Standalone checkouts and saved offer links* in Part 2 for supported currency/language lists and per-field limits. These offers currently support the documented two-decimal checkout currencies; JPY/BHD are rejected. Never divide arbitrary API money by 100 or mix currencies in a total.

Use the same POST with `id` and exact `baseRevision` to edit. An edit appends a revision and keeps the URL; sessions already entered retain their pinned configuration. A 409 means reread and reconcile, not retry an overwrite. Lifecycle uses `PATCH /v1/checkouts/standalone/:id/short-links/:linkId` with `baseRevision`, `active` and `archived`. Affiliates manage only their own links, on currently visible assets, in their affiliate workspace (not part of the client API).

##### Saved links for a flow

Use the same saved-offer payload and revision/lifecycle rules with `/v1/v5/flows/:id/link-options`, `/short-links`, `/short-links/:linkId` and `/link-assets`. An API key needs `checkouts.read` or `checkouts.write` for these routes. Read *Pages and flows* in Part 2 for the published-flow and checkout prerequisites.

The shared editor and API preserve free products, pixels, integration choices and webhooks. Read the returned `webhookCheckoutId` to scope webhook operations. When editing an existing link, pass its `linkId` to `link-options` so its original source checkout context is retained. New revisions pin the published flow and its branch checkout configurations; existing entered sessions retain their immutable revision. Store checkout templates can back a flow link without changing the template's direct-store routing. Archive or access revocation prevents new payment actions while already dispatched payments can still settle and reconcile.

##### Integration selection, pixels and automatic attribution

Select `three_ds_integration_key` and `receipt_sender_id` only from this checkout’s `link-options` choices. These are owner-bound references, never API keys or SMTP credentials. Omit an override to use the published default. Country overrides may narrow checkout restrictions, never widen them. Legal destinations must pass the documented URL checks. Visibility belongs to the builder document; retired link-form switches do not supersede it.

A saved link can contain multiple pixels. Browser networks are `facebook`, `tiktok`, `snapchat`, `google`, `pinterest`, `applovin` and `x`. Server Purchase delivery is supported only for Meta/TikTok/Snapchat and follows the winning acquisition network. Google/X require their documented event mapping. There is no fixed recipient-count promise: pixel JSON is bounded to 128 KiB and the request to 256 KiB; duplicates/conflicting mappings are rejected.

Pixel `accessToken` is write-only. Omit it to retain the secret for the same pixel identity; `null` clears it. Omitted `pixels` retains the previous revision’s configuration; `[]` removes recipients. Responses expose safe fields such as `hasAccessToken`, never tokens or ciphertext. Never copy a server token into a document, generated URL, client-side script or issue log.

Acquisition is captured automatically from validated UTM/click IDs and tracking extras. The saved-link creator is server-forced and persists through a flow checkout change; distinct non-neutral creator/flow-owner conflicts are rejected. A selected target link supplies its own commercial snapshot. For reporting, one canonical link is credited per sale: an explicit target offer link wins; otherwise the acquisition source link remains. Checkout reporting uses the actual capture checkout. Do not create a second conversion or double-count the same sale.

On a new charge, transaction attribution is written asynchronously **after** its parent transaction and order-context link commit. A replay does not create or replace that attribution, and a rolled-back claim does not publish it. This optional write cannot fail the payment. When diagnosing a missing campaign, compare the entry URL, persisted order/session/context and transaction attribution separately; an approved payment alone does not prove that every attribution write succeeded. Do not resend a charge to repair reporting, or infer historical attribution from a store's current flow.

Purchase events use actual captured non-test order facts and stable order-ID deduplication. Merely creating a link or opening a preview does not send a Purchase. Profile-level affiliate pixel management is retired; link-owned pixels are the supported affiliate workflow. Worker overrides are operational settings, independent of these REST edits.

#### Flow attribution, reporting and Upsell

`GET /v1/metrics/flows?from=2026-10-01&to=2026-10-30&tz=Asia%2FDubai` returns account-scoped flow performance. A maximum 366-day window is supported. Use the shared `flow` filter with comma-separated owned flow UUIDs; `none` selects direct/legacy transactions with no recorded flow. Foreign IDs are rejected. Transactions expose `v5_flow` from their immutable session/version, not the store's current assignment. Existing historical transactions without a recorded session are not retrospectively attributed to a new flow.

Revenue is captured gross amount, separated by currency; minor-unit amounts are returned as decimal strings. AOV is initial plus upsell volume in the selected period for sessions whose initial payment also falls in that period, divided by those initial paid sessions. Upsell take rate is the percentage of those initial paid sessions with at least one captured upsell in the same period/currency. It is not clicks divided by offer views. Refunds and chargebacks are cohort reversals through the report end. Use the response's `basis`, `aovBasis` and `takeRateBasis` in downstream reports.

`source=upsell` selects post-purchase charges. Upsell is a subset of Straight, so `source=straight` already includes it; `source=straight,upsell` still returns each matching transaction once. Never add an Upsell subtotal to Straight to form a grand total. Captured upsell revenue is distinct from initial-order revenue, and retries, rejected offers and failed charges do not create paid upsell volume.

#### Post-purchase payment methods

Post-sell admission depends on a confirmed initial payment, independently of NMI, Convesio, Stripe, wallet or wire. Registered card adapters create a new customer-initiated sale with the original source and winning MID; NMI uses `type=sale`. Wallets and wire use their native buyer confirmation flow with the original owned source. The original captured transaction, owner and session remain mandatory; never send an upsell through Customer Vault, a reference-sale endpoint, the rebill scheduler or another ATRI cascade. An offer is charged only after its displayed amount and explicit acceptance are verified. An unavailable payment method does not suppress the post-sell page or authorize a replacement MID.

New storefront checkouts omit the card-reuse paragraph and record no acceptance of it. For a paid NMI or Convesio upsell without that prior evidence, submit the current priced selection, signed quote, displayed v2 acceptance and a freshly entered security code. Only this explicit confirmation can authorize use of the verified original card for that basket, session, node and MID. Historical checkout evidence remains versioned. A view, a quote, a decline or adding an item to the cart does not authorize collection. Fresh post-sell authentication uses the Post-sell policy and the same original payment source.

When the flow view returns `paymentRequirements.securityCodeRequired: true`, collect a fresh three- or four-digit security code. Send `payment.securityCode` on confirm and on each non-cancel authentication continuation for that purchase. The value belongs only in request memory. Recollect after reload and clear it when the confirmation ends. Background observation and reconciliation never use it. An invalid format returns 400. A missing required code returns 409 before dispatch. Read the current flow state before offering any manual retry.

Never log, export or return PAN, CVV, expiry, vault tokens or credential ciphertext while investigating these paths. Reconciliation queries the same MID and durable order reference; it must work without replaying a sale or loading the stored card again. See *Pages and flows* in Part 2 (Reusable payment capability).

#### Private webhooks on an owned link

Endpoint management is `/v1/checkouts/:checkoutId/webhooks`. The account can also select link scope with `?linkId=<link-id>` (see *Checkout webhooks* in Part 2). Affiliates manage the webhooks of their own links in their affiliate workspace, which is not part of the client API.

```json
{
  "description": "Offer notifications",
  "url": "https://events.example.com/kontrol",
  "format": "json",
  "events": ["order.paid"],
  "scope": "checkout",
  "includeCustomer": false,
  "status": "active"
}
```

Consult *Checkout webhooks* in Part 2 for the endpoint's full create shape and event keys before sending. Link endpoints must remain `scope:"checkout"` and `includeCustomer:false`; they omit customer data, gateway references, card last-four and affiliate cuts. They cannot subscribe to other links or account-wide traffic. Link recipients follow persisted source-link attribution even when a flow selects another checkout; merchant checkout recipients follow the actual final checkout.

Delivery destinations must pass the public HTTPS/port/DNS checks. A signing secret is shown once at creation/rotation and must be stored securely. Verify signatures on original bytes and deduplicate the stable event ID. Test deliveries are synthetic; they do not prove a real purchase. Read the documented retry/rotation behavior instead of dispatching duplicate business events yourself.

#### Native page documents and discovery

`GET /v1/editor/catalog?pageType=checkout` supplies checkout block definitions, fields, defaults, variants, templates and the default document. It currently rejects any other `pageType`; do not invent a multipage catalogue endpoint. Metadata omits executable predicates, so server draft-save/publish validation is authoritative.

For Landing, Post-sell or Thank-you, create with `POST /v1/v5/funnels`, for example `{ "name": "Order confirmation", "pageType": "thank_you" }`, then `GET /v1/v5/funnels/:id/document`. Start from its real `draft`, `published` or `defaultDocument`, preserving IDs, payment locks, slots and current `draftRevision`. The native page editor exposes page-specific choices. A document uses `format`, `pageType`, `root` and `content`; it is not the obsolete `{version,rootId,nodes}` object.

Save the **complete** document with `PUT /v1/v5/funnels/:id/document/draft` and `{baseRevision,document}`. Read validation issues and resolve them; publish with `POST .../document/publish` using the new revision. A 409 requires a reread. A 422 requires correcting reported issues. Versions/restore create drafts and never rewrite a published version or in-flight session. Merchant post-sell saves may additionally provide `offer`; affiliate saves must omit it.

Shared native blocks cover layout/columns, text/media, actions, marketing content and Popup, alongside protected checkout and page-specific blocks. Use their actual registered properties and slots. Block previews, device controls and saved blocks use the same renderer as published pages. An image of a reference is not an editable reconstruction: express the structure with native blocks and original permitted assets. Generated content remains a draft until explicitly published.

A Popup (`layout.popup`) opens from a referenced element or a bounded delay and supports dialog, drawer and sheet layouts. It cannot hide payment-critical controls or satisfy a post-sell’s required visible offer/global-decline controls. Trigger IDs must reference the actual document. Preview/canvas uses the inert renderer and its signed capability; it does not exercise payments or live pixels.

Styling covers responsive width, spacing, typography, color, borders and visibility. Sections expose one effective control per property. Legacy scalar padding/background/radius/width values normalize into styles without changing their rendered precedence, zero values, responsive resets or bindings. A color binding moves intact to Styling. A legacy non-transposable linked width/padding/radius retains its visible legacy control while the corresponding universal control is omitted; unlinking to a literal normalizes immediately. Do not write both authorities or flatten a binding into a guessed value.

Render variables come from verified published settings and the session’s real commerce/brand context. For a saved-link input use `parameters.store_name`; a document binding uses `{ "$link": "store_name" }`, resolved from `data.store_name`. Do not invent `shop_name`. Do not manufacture totals, order IDs, customer fields, receipt status, support addresses or currency conversion in copy or HTML. Missing facts remain absent.

#### Build, validate and publish a flow

Create with `POST /v1/v5/flows` and `{name}`; read its current draft. The first **Entry point** is immutable: retain its ID, name, position and graph entry. It is a structural node with one `next` output, not a page. Published older graphs remain compatible; editing creates a normalized draft without changing existing sessions.

Pages and Logic are separate native categories. `ab_test` and `condition` are independent nodes with their own ports, before or after a checkout where graph rules permit. Edges are `{from,output,to}`. Connect on canvas by drag, click or keyboard; dropping an output on empty canvas opens quick-add and connects the selected node. The modal edits node settings, not a separate connection list. Contained fullscreen, restore, free panning and edge panning affect the editor only.

| Node | Outputs / contract |
| --- | --- |
| `entry`, `landing`, `checkout` | `next`; landing references a published page; checkout can select a checkout and exact saved-link revision |
| `ab_test` | `branch:<id>` for 2–8 unique branches; positive integer relative weights totaling at most 10,000 |
| `condition` | `matched`, `unmatched`; `mode:"all"` or `"any"`, 1–16 rules |
| `post_sell` | `accepted`, `declined`, optional `payment_failed`; references a published post-sell page |
| `thank_you` | No output; optional published Thank-you page, otherwise native default |

Condition fields are `country`, `store`, `currency` with `in`/`not_in`; `products` with `contains_any`/`contains_all`/`contains_none`; and `cart_amount`, `aov`, `item_count` with `eq`, `gt`, `gte`, `lt`, `lte`, `between`. Money rules use integer `value`, explicit `currency`, and `upper` only for `between`. For example, a USD 59.99 minimum is `{ "field":"cart_amount", "operator":"gte", "value":5999, "currency":"USD" }`. Countries/currencies use uppercase ISO codes; store/product values are discovered UUIDs. Unknown facts and currency mismatches do not become inferred matches, including negative membership checks.

Use `POST /v1/v5/flows/validate` with `{graph}`, then `PUT /v1/v5/flows/:id/draft` with `{graph,baseRevision}` and `POST .../:id/publish` with the saved revision. Every completed path must pass exactly one checkout before post-sells/Thank-you; cycles, unpaid completion and return to checkout after payment are rejected. All required outputs must connect. Publication checks ownership, page type/version, active checkout and assigned-store compatibility. Do not supply an invented `pageVersionId`; publication resolves approved references.

Runtime routing is server-authoritative and deterministic, with context and decisions pinned for the cart/session. Browser condition values or a second visit cannot select another published branch. `shortLinkId` requires `checkoutId` and positive `shortLinkRevision`; the live link/creator/grant checks remain in force. Store paths cannot use standalone offer links.

Assign a store with `POST /v1/checkouts/:shopId/checkout` using `{flowId}` or `{checkoutId}`, never both; `{checkoutId:null}` unassigns. A real verified cart is required for a store entry. For checkout-specific flows, use the flow assignment preview/apply contract. New checkout AB writes are retired: authorized `POST /v1/checkouts/ab-tests` and `PATCH /v1/checkouts/ab-tests/:id` return 410; historical GET and pinned cart compatibility remain. Direct checkout assignment retains the existing default confirmation, while a flow follows its selected Thank-you.

#### Post-sell selection and Thank-you facts

The native catalogue exposes PS-01–PS-10. The seven reference compositions are PS-04/U10, PS-05/R04, PS-06/R06, PS-07/R21, PS-08/U03, PS-09/U07 and PS-10/U09. They inherit store branding and use real bestsellers. PS-04–PS-09 add an optional `selection.timer` to the automatic product policy, with the same `durationSeconds`, optional UTC `deadline` and `expiryBehavior` contract as manual offers. Default 600-second deadlines are server-persisted per session/node; never emulate expiry in client-only copy or restart it on refresh. PS-10 uses progress without a timer. Preserve authored discounts, product policy and historical page versions when applying a template.

The shared **Wallet payment** builder block (`checkout.expressCheckout`) is available on checkout and post-sell pages, with five presentation variants. For post-sells, `paymentRequirements.method` is derived from the verified original payment (`card`, `apple_pay`, `google_pay`, `wire`); do not invent an alternative method or change MID. The block delegates to the existing quote/consent/confirmation/authentication path. Editor preview method settings are inert and cannot select a live provider. Replacing an existing confirmation is allowed only while a visible confirmation remains; publishing is still explicit.

Use `GET /v1/metrics/postsells` for the dedicated Post-sells report (Reports → Commerce). It returns initial-order cohort conversion and AOV separately from event-dated upsell captures, refunds, chargebacks and net revenue, with page/flow/store/payment/day breakdowns, authentication, latency and diagnostics. Preserve currency exponents, scope definitions and `asOf` in any export. Page cohorts overlap and must not be summed. Zero attempts is not proof of no clicks or no errors: pre-intent request rejections are not persisted in this report. Read `basis` before interpreting the result.

Configure owned active catalogue products/variants through a merchant post-sell draft. Unlike an autonomous saved offer, this commerce uses catalogue IDs. The configuration accepts one legacy offer or `{offers:[...]}` with 1–20 unique IDs, quantity 1–10, integer unit price and one supported currency. Single/Multiple offer blocks and the native `funnel.slider` reference those IDs. The slider preserves selection across slides; confirm/decline and the exact payment disclosure stay outside it. `funnel.originalOrder` and `funnel.originalConfirmation` show only the captured initial order; `funnel.savings` uses real selected compare-at reductions and basket-level tax rounding. Accept can target one or all selected choices; declining one removes a local choice, while declining the selected set continues without purchase.

The buyer runtime confirms the complete basket with current `nodeId`, `action: "confirm"`, `scope: "page"`, quoted `selections`, `quoteToken` and displayed `acceptance` using `version: "post-purchase-accept-v2"`. Variants and quantities must stay inside the published allowlist. Legacy public `accept` and `selectedOfferIds` confirmations are refused. Buyer input cannot set prices, gateway currency, MID or PAN. The narrowly allowed `payment.securityCode` is fresh verification, never an old checkout CVV. This is a checkout service/session step of the storefront runtime, not part of the client API: an API key cannot perform it. One accepted basket produces one purchase using the initial payment's verified source. No new ATRI choice or cross-MID fallback is allowed.

Reloads/concurrent actions reuse the durable intent. A timeout becomes UNKNOWN and reconciles against the original provider reference; it must never trigger another sale. Payment-method or policy failure refuses confirmation without changing the initial purchase; the buyer can continue to the receipt. There is no Vault opt-in for new original-card sales. Fixture success is not live processor certification.

Paid post-sell views also receive buyer-scoped `confirmation.orders`; use `kind: initial` for original-order displays and all captured orders for the combined receipt.

A Thank-you page contains eleven configurable blocks: store header, confirmation, order summary, customer information, delivery map, order updates, shipping protection, email reminder, customer support, help/language/shopping, and order policy. Receipt data comes from captured initial and accepted post-sell facts, including real items, taxes, discounts and currency-separated totals. Payment display is limited to brand/last-four. An explicit flow Thank-you overrides the checkout fallback destination; a default direct-store checkout keeps its established completion. See *Pages and flows* in Part 2 for capability, recovery and rollout details.

Initial product, variant and free-gift images come from the server cart that matches the signed shop/cart/currency/price envelope. Upsell images come from the server-priced offer. Missing optional images do not change totals or refuse payment. Never fill receipt lines from the current catalogue or accept a browser-supplied image as proof of the purchased variant.

A paid expired flow may return its pinned Thank-you as `receiptOnly: true` when no unresolved intent remains. It follows unchosen offers' decline branches for display without recording invented declines, moving the session cursor, reopening offers or renewing payment authority. Pending or unknown intents still require reconciliation. A completed server route is also distinct from a browser view: the storefront records a view with the returned short-lived `observationToken`, displayed `nodeId` and stable UUID `viewId` (`event: "page_view"`) through its authenticated events proxy; this is storefront runtime, not part of the client API. Duplicate observations are deduplicated; a GET alone is not proof that the buyer saw the page.

#### Technical payment returns

Provider-facing navigation uses the API deployment's configured HTTPS origin, not the store's CMS/domain or incoming `Host`, `Origin` or `Referer`. The server creates a signed reference for the existing transaction, flow or wallet operation and supplies `/v1/payments/return?token=<reference>` to the adapter. GET and provider form POST validate that reference and its persisted binding, then return a 303 to the permitted original destination. They never charge, approve, settle, replay a sale or create a buyer session. Callback fields such as `status=success` are not payment evidence.

Use the return URL supplied by the API; do not mint a token, replace its destination or remove the original checkout's signed query context. Invalid references fail validation; expired, unavailable or unbound destinations do not produce an external redirect. Headless and rebill operations without a verified browser destination use the neutral CRM completion page, which is not a payment confirmation. Required merchant/requestor identity, MID/provider identity, registered wallet domains and provider-owned ACS URLs retain their real configured values. Centralizing technical navigation does not rewrite those fields.

#### Verify a store-to-flow integration

1. Install the current [Shopify guide and paired theme files](https://app.kontrolcheckout.com/integration-guides/downloads/shopify.md), or the matching Medusa guide for [self-hosted](https://app.kontrolcheckout.com/integration-guides/downloads/medusa-hosted.md) or [Cloud](https://app.kontrolcheckout.com/integration-guides/downloads/medusa-cloud.md). Updating Kontrol does not publish an external storefront's theme or middleware.
2. Start a fresh isolated cart on the actual product page with synthetic UTM markers. Check the homepage/locale redirect too: every redirect before checkout must retain the relevant query parameters. A marker lost before Kontrol entry cannot be recovered from the final checkout URL.
3. Change a variant and quantity, then click checkout once. Check immediate loading feedback, one navigation, retained attribution and correct server-priced products, gifts and protection. For Medusa, keep upstream `prod_`/`variant_` identities distinct from Kontrol's internal UUIDs; do not rewrite one namespace into the other to bypass a recovery conflict.
4. Use a deliberately configured test path. `TEST_CARD_ENABLED` enables the server's reserved card simulator; the default approval PAN is `4242424242424242` and default decline PAN is `4000000000000002`, unless the deployment overrides them. These numbers do not independently put a live provider into sandbox mode. Do not enable or alter production test settings as a side effect of checking a guide.
5. For an approved simulated initial payment, follow the published post-sell path, accept or decline once, and verify the configured Thank-you. Simulation is persisted and verified server-side; a browser `test` flag is not authority. Its upsell ledger stores selected offer display facts, not a real gateway intent/capture, and it omits real PSP, 3DS and Purchase-pixel delivery. A successful simulation validates application routing and display, not those provider integrations.
6. Compare persisted order/session/transaction attribution and receipt totals/images. Record browser errors and all observed request statuses, distinguish optional probes from payment failures, and measure checkout visibility, pay-click-to-offer-ready and accept-click-to-receipt separately. Browser traces cannot show server-to-server provider requests; verify those separately in an authorized provider sandbox. A lost response is not a reason to submit another payment.

#### Report the actual scope

Keep account, dates/timezone, currency, affiliate, store and checkout/link filters consistent across reads/exports. **No store** is standalone commerce; **No affiliate** is unattributed activity. Initial orders, upsell captures, refunds and rebills are separate facts. Affiliate cuts derive from the immutable captured-order rule and append-only reversals, not a newly edited rule or a guessed conversion. Never add a link and its checkout’s revenue together as independent sales.

The endpoint reference (Part 4) and endpoint index (Part 3) are generated from the same registered-route inventory. A complete inventory is not evidence that a live provider, background worker or browser journey has run in your deployment. Record what was actually read, saved, validated, published or tested; preserve pending/unknown outcomes.

##### V5.1 saved-link URL pair

Checkout and flow links share `shortUrl` (`ktrl.ink`), `longUrl` (`kontrolcheckout.com/l/<id>`) and `hosting:{short,long}` readiness. Read the returned URLs and distribute only `ready` variants; pending infrastructure is not a successful launch. Both pin the same saved offer and all flow checkout branches, including attribution and pixels. Historical URLs keep their original destination. The affiliate supplies logo content; logo size stays with the owner layout. See *Standalone checkouts and saved offer links* in Part 2 (Canonical short and long URLs (V5.1)) for request, response and failure examples.

Optional shipping protection: use signed checkout parameter `shipping_protection_default_enabled: false` for an initially unchecked optional fee. Omitted means historical enabled default; forced mode overrides false. The native `checkout.shippingProtection` block only changes presentation. Never put a fake amount or an independent checkbox beside the actual checkout control.

Initial offer inclusions: optional `initialInclusions` accepts up to 4 `{productId, variantId, quantity}` records (owned UUIDs, quantity1–10). Only initial offers accept them. The server requires an active, same-currency, in-stock, non-subscription catalogue variant and forces price 0; published inclusions are snapshotted. The merged initial cart is capped at 10 lines. Never simulate gifts with receipt text or imply a digital file is delivered merely because its product exists.

Offer-specific protection: an initial offer may set `initialProtectionMinor` to a non-negative integer in the checkout currency's minor units. This optional fee is applied once per selected offer (summed for multi-selection), replacing the signed `shipping_protection_price_cents` default for that selection. Omitting it uses the checkout default. Protection mode and `shipping_protection_default_enabled` still control whether the buyer pays that fee; the block never supplies the amount.

##### Native receipt composition

`checkout.orderSummary.receiptOrder` optionally groups canonical rows using one of `products-protection-gifts-shipping`, `products-gifts-protection-shipping`, or `gifts-products-shipping-protection`. `receiptGap` sets the spacing. Product presentation fields (`packPresentation`, `packLabels`, `imageSize`, `showVariant`, and related Cart settings) are reused; `shippingImage`, `protectionImage`, and `serviceImageSize` illustrate the actual quoted fees.

Keep a real `checkout.summaryTotals` child in the summary's content slot. The composite prevents nested Cart/fee rows from rendering twice, while neighbouring summaries are unaffected. `showSubtotal:false` hides only the merchandise-subtotal line; `subtotalLabel` optionally names that line. Discounts, tax and the authoritative total remain unchanged. Unset `receiptOrder` preserves the previous free-layout rendering.

`giftPriceLabel:"FREE"` applies only to a genuine included product priced at zero. `showPackRecurringTerms:true` displays the matching selected subscription offer's published `recurringTerms`; it invents no cadence, renewal price, or delivery claim, and displays no renewal terms for a one-time purchase. Do not fabricate compare-at prices for gifts or shipping when the catalogue does not provide them. Illustration and label settings never add cart lines or charges; protection remains linked to the existing checkout toggle.

### Standalone checkouts and saved offer links

For REST automation, use *Commerce workflows* in Part 2 alongside the endpoint reference (Part 4). Affiliates work in their own affiliate workspace; it is not part of the client API.


A checkout is a reusable published design and payment configuration. A saved link is an autonomous offer: its own products, prices, quantities, variants, images, branding, delivery options and pixels. Affiliates can create offers without a merchant product catalog or a connected store. The merchant's published builder controls the layout and visible elements; an offer does not edit the template.

#### Authentication and routes

REST base: `/v1/checkouts/standalone`. Send an API key of the account as `Authorization: Bearer <key>`, with the `checkouts.read` / `checkouts.write` scopes.

Affiliate View or Edit plus current checkout visibility permits creating and managing **their own links** on a published active checkout. Shared View does not grant draft, publication, routing or merchant settings access. Merchants see all account links; affiliates never receive another creator's saved parameters or link statistics.

| Method | Suffix after `/:id` | Purpose |
|---|---|---|
| GET | `/link-options` | Published defaults, content bindings, currencies, locale and safe owner integration choices |
| GET | `/short-links` | Saved link inventory, creator, versions, lifecycle, sales and safe pixel configuration |
| POST | `/short-links` | Add or edit an offer and its pixels; edit requires `id` and `baseRevision` |
| PATCH | `/short-links/:linkId` | Enable, disable, archive or restore with revision control |
| POST | `/link-assets` | Upload a logo or product image and obtain an asset URL |
| POST | `/document/links` | Signed inert model preview; use `{ "kind":"preview", "mode":"published" }` |

The checkout inventory also returns `links_count`, excluding archived links and scoped to the creator for affiliates. Use the returned link `url`; do not construct a domain or slug yourself.

#### Minimal agent workflow

1. List available checkouts and choose a published, active one. To create a reusable template as merchant, use the existing checkout create, document draft, publish and active endpoints. No default basket is required for publication. The account must still have an ownership-verified technical serving domain; a bare template URL without an offer has no payable basket. Use its signed builder preview to inspect the design.
2. GET `/:id/link-options`. Read `parameters`, `bindings`, `locale`, `legal`, `threeDs` and `emailProviders`. These contain public configuration or safe references, never integration credentials. A catalog lookup is unnecessary.
3. POST `/:id/short-links` with at least one product name and integer minor-unit price. No product or variant ID is needed. The following example creates one USD 59.99 product, quantity one, with a free-text variant.
4. GET the inventory and distribute the authoritative `url`. A click resolves the current immutable offer revision, creates a server-side session and removes parameters from the checkout URL before rendering. Incoming supported campaign parameters are captured automatically.

```json
{
  "name": "Travel bag — summer campaign",
  "parameters": {
    "currency": "USD",
    "product1_name": "Travel bag",
    "product1_variant": "Black / Large",
    "product1_price": "5999",
    "product1_quantity": "1",
    "store_name": "Travel collection",
    "primary_color": "#F25B16",
    "logo_url": "https://assets.example.com/travel-logo.png",
    "shipping_protection_mode": "on",
    "shipping_protection_price_cents": "799",
    "offered_languages": "en,fr",
    "allowed_countries": "US,CA",
    "terms_url": "https://example.com/terms"
  },
  "active": true
}
```

The response is `{ "link": { "id":"…", "slug":"…", "revision":1, "active":true, "pixels":[], … } }`. Read the inventory to obtain its public URL and full row. Save up to ten products using `product1_…` through `product10_…`, with quantities from 1 through 99. Sending any product fields defines the link's entire basket; old template product fields are removed first. Optional `product1_image` is an HTTPS image URL, `product1_variant` is its display variant, and `product1_compare_price` cannot be lower than its sale price.

The server creates account-scoped internal offer identifiers and stores the exact line snapshot. These identifiers are not catalog records and must not be supplied as catalog IDs later. Payment preparation, transaction reporting and receipts use the saved product names, variants, quantities and prices. Autonomous offers never synchronize orders to a connected store, including when an older template still has a connector configured. Explicit legacy catalog product/variant IDs remain supported for existing integrations and still require active account-owned records.

#### Prices and optional content

All parameter values are strings. Money parameters are **integer minor units**, for example `product1_price:"5999"` means USD 59.99. `product1_compare_price`, `shipping_price` and `shipping_protection_price_cents` use the same units. The UI presents decimal amounts and converts them on save. Supported currencies are USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS and ZAR; all use two decimal places. JPY and BHD are not offered. Product prices and computed cart totals remain bounded server-side; malformed, fractional minor-unit and excessive values are rejected.

An affiliate with access to the published checkout controls prices for their own persistent offers. The old `settings.linkPolicy.allowPriceOverrides` gate is not used for these autonomous saved links. This does not grant template editing, merchant routing changes or access to another affiliate's offer.

Useful content parameters include `logo_url`, `store_name`, `primary_color` and the published builder's configured text/image bindings. Shipping protection uses mode `off`, `on` or `forced`, label/description and its minor-unit price. The builder is the source of truth for visible countdown, header, footer and trust elements; hardcoded visibility switches are no longer offer controls. The complete parameter types and limits remain in the generated standalone parameter reference.

To upload a logo or product image, POST `/link-assets` with `{ "contentType":"image/png", "base64":"<encoded bytes>" }`, then set `logo_url` or `product1_image` to the returned `url`. PNG/JPEG/WebP/GIF only; maximum decoded image 5 MiB and JSON body 7 MiB. No SVG. Give this upload a 120-second client deadline; normal API requests retain their existing limits.

#### Languages, countries, legal links and integrations

The native editor uses multi-selects. The REST equivalents are comma-separated strings: `offered_languages:"en,fr"` and `allowed_countries:"US,CA"`. Offered languages are en, fr, it, es, pt and pl. A template's forced language must remain offered. Country codes must be recognized ISO2 codes; a link can narrow the published template's countries but cannot widen them. `allowed_countries:"*"` inherits the template's country allowance, which may already mean all countries. Do not combine `*` with country codes.

`terms_url`, `privacy_url` and `refund_url` are optional HTTPS URLs. Omit them to inherit published values; a template may omit all legal URLs. Each saved link pins the effective locale and legal settings without changing the template.

Choose `three_ds_integration_key` from `threeDs[].value` and `receipt_sender_id` from `emailProviders[].id` in link-options. The server checks the account owner again on save and entry. A selected sender enables receipts for that offer; omission retains the published receipt settings. Disabled, foreign or unconfigured references return 422. Public responses contain only integration references and labels. Never send SMTP passwords or 3DS credentials in link parameters.

#### Link pixels and server purchases

Send an optional top-level `pixels` array with a create or edit request. Each entry supports the following fields:

| Field | Meaning |
|---|---|
| `id` | Optional UUID for a new entry; retain the returned ID when editing. |
| `name` | Optional display label, at most 120 characters. |
| `network` | `facebook`, `tiktok`, `snapchat`, `google`, `pinterest`, `applovin` or `x`. |
| `pixelId` | Public destination ID, validated for the selected network. |
| `events` | Conversion mappings; `purchase` is required for Google and X. |
| `enhancedConversions` | Optional Google enhanced-conversion setting. |
| `serverEnabled` | Defaults to false; enables server **Purchase** for Meta, TikTok or Snapchat only. |
| `accessToken` | Write-only server token. Omit to retain the same existing entry's secret; null or empty clears it. |
| `hasAccessToken` | Response boolean indicating whether a secret exists; no secret is returned. |

Example top-level array on a create request:

```json
{
  "pixels": [
    { "name":"Meta campaign", "network":"facebook", "pixelId":"123456789012345", "serverEnabled":false },
    { "name":"Google purchase", "network":"google", "pixelId":"AW-123456789", "events":{"purchase":"purchase_label"} }
  ]
}
```

To enable Meta server purchases, provide `serverEnabled:true` and an actual `accessToken` over the authenticated API. Do not include tokens in public URLs, query strings or generated page content. The server encrypts them at rest. Lists and save responses return only `hasAccessToken`; public checkout rendering receives public pixel IDs and event mappings.

On edit, an omitted `pixels` field copies the previous revision unchanged. `pixels:[]` removes all link pixels from the new revision. A supplied array replaces the set; preserve each entry's `id`, network and pixel ID to retain an omitted secret. Changing its identity cannot inherit another destination's token. Lifecycle changes preserve the pixel snapshot. Existing sessions continue using their pinned immutable revision.

There is no fixed business limit on the number of pixels: the serialized pixel array must fit within 128 KiB, and the full short-link request within 256 KiB. Duplicate network/destination pairs or duplicate entry IDs are rejected. AppLovin allows one event key per checkout page. Google and X mappings must be valid and cannot conflict with published template pixel configuration.

All seven networks support the existing browser event integration. Server delivery is narrower: only a verified positive **captured initial payment or upsell** can enqueue Purchase, and only Meta, TikTok and Snapchat have server senders. Declines, test payments, revoked/disabled recipients and other event types do not produce these server purchases. Delivery uses the immutable session's **winning acquisition network**; a link's pixels on another network do not receive server Purchase. Multiple valid recipients on the winning network can receive it. Direct/unrecognized acquisition does not imply an arbitrary network.

Browser and server Purchase use the same immutable order ID for platform deduplication. Durable deliveries also deduplicate the captured payment fact and destination; transient failures retry with the same event ID. The elected API worker requires global `BACKGROUND_JOBS_ENABLED=true`. Saving pixels alone does not claim provider acceptance or start background workers.

#### Editing, history and lifecycle

Read the current row, then POST `/short-links` with its `id`, `baseRevision`, complete intended `parameters`, `name` and `active`. A successful save preserves the public URL, increments the revision and pins the currently published checkout configuration. A 409 means another editor changed the link: reload before retrying; do not blindly overwrite.

For lifecycle changes use:

```json
{ "baseRevision": 3, "active": false, "archived": true }
```

Archiving disables the link. Restore explicitly with `archived:false` and the desired active state. Each change appends an immutable revision. No history is deleted. Existing sessions retain their original offer parameters/configuration, but disabled, archived, expired or permission-revoked offers stop being available. Never submit `accountId`, `creator_affiliate_id`, `sig` or `kt` as editable link parameters.

#### Attribution and flow integration

The authenticated affiliate is permanently recorded as creator when a link is created; its `affid` is forced server-side on each save. Merchant edits preserve that creator. Merchant-created links may have explicit tracking attribution. Query parameters cannot replace the creator.

The editor has no manual UTM or click-ID inputs. Supported acquisition values on the incoming landing URL, such as `utm_source`, `utm_campaign`, `fbclid` and `ttclid`, are captured automatically into the session's attribution snapshot. Use the normal ad platform's destination tracking; do not turn a pixel secret, price or affiliate identity into a visitor-editable tracking field. Unsupported or malformed query values remain rejected.

At entry, the saved-link creator has precedence over a neutral/default checkout owner; next comes the published flow owner, then the checkout owner, then normal permitted tracking/cookie attribution. The incoming saved-link creator persists when AB selects another checkout, while the source products and prices do not transfer. Two different nonnull creator identities between incoming/selected links or an owned flow are rejected. A preserved acquisition reference is reporting-only on another checkout and cannot authorize its commercial configuration. Existing payment sessions keep their immutable attribution snapshot.

A standalone checkout node in a flow can pin `{ "checkoutId":"…", "shortLinkId":"…", "shortLinkRevision":4 }`. The pair is mandatory together. Publication and runtime verify account, published checkout, verified domain, live permissions, link lifecycle and exact immutable revision/configuration. An old link without a configuration pin must be saved once before being used in a flow. Store checkout nodes cannot use standalone saved links.

Each sale has one canonical link reference. If a selected node pins another authorized link, that selected offer link receives the link-level sale; otherwise the incoming acquisition link retains it across checkout changes. Checkout statistics still belong to the checkout that captured the sale. The system does not count one sale for both a source and target link.

Conditions use server-validated original offer facts: currency, cart amount, item count, pinned product identities and serving-request country when available. Standalone store/AOV remain unknown. A selected AB branch uses its own defaults or pinned link; products and prices from the source branch are not carried across. Flow previews resolve the exact selected link revision in inert preview mode: no payment, session, pixel recipient or buyer event is created.

#### Errors to handle

| Status | Agent response |
|---|---|
| 400 | Correct unknown/invalid fields, malformed image, parameters or unsupported values. |
| 401 | Re-authenticate; never place credentials in public URLs. |
| 403 | Respect access, creator or conflicting flow ownership. |
| 404 | Asset is foreign, hidden, revoked, disabled or unavailable; do not probe alternate tenant IDs. |
| 409 | Publish/enable the checkout or reload a stale revision as indicated. |
| 413 | Reduce image/request size. |
| 422 | Fix product details, currency, compare price, cart limits, country restrictions or integration selection. |

The legacy `/url` generator remains available for ephemeral links and keeps its existing narrower affiliate tracking-only policy. Prefer persistent `/short-links` for configurable offers, lifecycle, reporting and flow pins.


#### The same offers on Flows

Use `/v1/v5/flows/:id` with the same five saved-link suffixes above (link-options, link-assets, short-links and short-links/:linkId). The flow already selects its checkout nodes. Do not ask an affiliate to choose a store or synchronize a product catalogue. Flow link revisions pin every branch and use the same configurable products, branding, pixels, integrations and webhooks. Read `webhookCheckoutId` from link-options for webhook operations. See *Pages and flows* in Part 2 (Saved flow links) for publication and serving-domain prerequisites.

#### Canonical short and long URLs (V5.1)

Every saved checkout and flow offer returns `shortUrl`, `longUrl`, and `hosting`, on both creation and inventory reads. `url` remains an alias of `shortUrl` for older clients. New short URLs are `https://ktrl.ink/<7-character slug>`; long URLs are `https://kontrolcheckout.com/l/<saved-link UUID>`. Both resolve the same offer, affiliate, prices, pixels and immutable version. Do not construct these URLs or use the layout template's bare URL.

```json
{"link":{"id":"11111111-1111-4111-8111-111111111111","revision":1,"shortUrl":"https://ktrl.ink/aB3dE6g","url":"https://ktrl.ink/aB3dE6g","longUrl":"https://kontrolcheckout.com/l/11111111-1111-4111-8111-111111111111","hosting":{"short":"pending","long":"pending"}}}
```

`hosting.short` and `.long` are `ready` or `pending`; they describe deployed domain routing, separately from `active`. **Only distribute ready URLs.** Readiness is measured through public DNS, valid HTTPS and a matching uncached application response on the exact host. A short host also requires its pinned destination ready. Results are refreshed after 30 seconds (five seconds after failure); redirects, marketing HTML and stale nonce responses stay pending. The UI displays both URLs and explains pending hosting. Existing links keep their original host and destination after edits; they are not silently migrated.

The long browser route is served by the storefront runtime, which is not part of the client API. It resolves the link to its checkout URL (`https://kontrolcheckout.com/c/link-...?kt=...`) and issues a clean 302 with no-store/no-referrer. Unknown, revoked or unready links return 404; malformed input 400; oversize body 413; rate limits 429. `HEAD` and known preview crawlers do not count clicks. Incoming UTM/click IDs use the same automatic attribution path as short links.

Logo size belongs to the checkout owner's builder. Offer links may supply `logo_url`, but not a size control. Historical `logo_height_override` values are ignored; old signed URLs keep their original signature validation without changing the design. Pixels use a shared table and a dedicated Add/Edit modal; their encrypted server credentials remain private.

### Pages and flows

Pages stores reusable landing, post-sell and Thank-you pages. Flows connects those pages with weighted A/B tests and Conditions, selecting one checkout per customer path before the final Thank-you. Both use the shared native editor and canonical payment records. Post-sell choices use owned catalogue products; autonomous standalone offer links can define their own products without a catalogue. Existing order bumps remain part of the initial checkout cart.

#### Prepare and publish

1. Use an authenticated merchant account with the required management role. All merchant accounts have access to V5.
2. Open **Commerce → Sales journeys → Pages**, add a Landing, Post-sell or Thank-you, and edit it in the native page editor. A landing must retain its checkout button. A post-sell must retain its offer, Confirm order and Decline controls. Add buttons only build the upsell cart.
3. Configure post-sell products through **Products**: active catalogue products, variants, quantities, normal currency amounts and currency. The API stores integer minor units. Publish each page before using it in a published flow.
4. Open **Flows**. It opens in contained fullscreen, with Save, Publish and Restore at the top right. Every editable flow begins with a fixed **Entry point**; connect its output to the first page or logic node. The **Add node** picker groups Pages and Logic, offering Landing, Checkout, Post-sell, Thank-you, A/B Test and Conditions. Connect ports by dragging, or select each port with click, Enter or Space; Escape cancels. Drop an output on empty canvas to choose a new connected node; keyboard users can select an output then press Insert. Reconnect an output to replace its destination, or use its disconnect button. Select a node to edit settings; connections stay on the canvas. Drag empty canvas to pan freely, even when the graph fits; node handles support edge panning. Cards show selected assets, branch weights and actual condition values. Multiple checkout paths require explicit checkout choices.
5. Resolve validation issues, save and publish. Publication pins the exact published version of every referenced page. History restore creates a new draft and preserves live versions.
6. Preview bulk assignment, inspect the result for each checkout, then apply. Assign Default to remove a custom flow.

**Preview walk** opens the saved flow as rendered pages. Choose an allowed store or standalone checkout when the flow uses an assigned checkout. Choices follow account ownership and current asset permissions. The preview uses the checkout editor's existing inert mode and a synthetic preview cart. Continue, Pay, Accept, Decline and **Simulate failed payment** traverse the graph locally; Back and Restart let you inspect another branch. The page is labelled simulated, no order is placed, and no charge, pixel, buyer session or ledger event is created. This does not call the real card test pipeline.

The preview handoff sends a signed ten-minute capability in a POST body, stores it in a Secure HttpOnly preview-only cookie and redirects to `/preview/flow` without a token in the URL. Each read revalidates account ownership, current grants/sharing and affiliate credentials. A changed saved flow invalidates its preview. Shared assets and owner-with-View assets render approved content; only Owner+Edit may inspect an affiliate draft. Existing editor preview links keep their established signature convention.

Default remains a virtual read-only `Checkout → Thank-you` runtime graph with no database version. The builder displays a structural Entry point and duplicating it creates an editable draft with that node. Publishing a replacement never changes sessions that already entered an older version. Existing published graphs without Entry stay compatible; draft normalization does not rewrite them.

#### Build an entire funnel without a store

Editorial landing pages and product pages are native `landing` documents. Add an owned catalogue offer and native commerce blocks to a product page; a separate store product page is unnecessary. Checkout remains a native checkout document with the protected form/payment blocks. Publish each page and checkout, then publish the Flow Builder graph that connects them. Existing sessions retain their pinned page, offer and graph versions.

1. Create or reuse an account catalogue product. `POST /v1/v5/catalog/products` accepts `{requestKey,product}` and returns `{product,variants}`; an identical request key/payload reuses the creation. `GET /v1/v5/catalog/products/:id` returns the full catalogue record. These routes require merchant management permission and `checkouts.read`/`checkouts.write` API-key scope.
2. Configure explicit page offers with owned product/variant IDs, quantity, `unitPriceMinor`, currency and stable offer IDs. Landing pages support one to ten offers. `purchaseMode:"subscription"` needs an owned active simple fixed USD plan in `subscriptionProductId`; `one_time` never silently enrolls the product's default subscription. `initialShippingMinor` is an initial-order charge; recurring shipping belongs to the selected plan. Prices and recurrence are authoritative server data.
3. Use native `commerce.product`, `commerce.pack`, `commerce.gallery`, `commerce.price`, `commerce.variant`, `commerce.quantity`, `commerce.summary` and `commerce.purchaseTerms` blocks. A `funnel.checkout` CTA advances the published graph with the selected offer, variant and quantity; it does not submit payment. Its optional `offerId` chooses that published offer before continuing.
4. Use a store-free standalone checkout on `kontrolcheckout.com`, or an owned verified custom domain. Existing shared flow links provide both `ktrl.ink` and the long `kontrolcheckout.com/l/...` URL. A flow still needs a published checkout/payment configuration; a catalogue product alone does not provide one.

A saved flow link starts at its pinned graph entry, including landing, product and quiz pages before checkout. A preceding A/B decision selects the first page deterministically for that session. Opening the checkout URL resumes the current flow page until checkout is reached; absence of a selected cart does not skip earlier pages. Direct checkout links without an explicit landing retain checkout-first entry.

##### Account catalogue fields

The create body is strict `{requestKey,product}`. `requestKey` is 1–100 characters, starts alphanumeric and then permits letters, digits, `_`, `-` and `:`. Product title must be nonblank; handle is normalized from the supplied handle or title. Money is integer minor units. There is no caller-supplied owner or store.

| Product field | Limits and behavior |
| --- | --- |
| `title`, `handle`, `status`, `currency` | Title up to 300, handle up to 80 before normalization; status `draft`, `active` or `archived`; three-letter currency. |
| `subtitle`, `vendor`, `product_type`, `tags` | Nullable subtitle up to 300; vendor/type up to 120; at most 50 tags of 60 characters. |
| `description`, `seo_title`, `seo_description` | Description up to 100000; nullable SEO title up to 200, description up to 500. |
| `gift_banner_text`, `scarcity_text`, `social_proof_text` | Nullable strings up to 300. Presentation text does not create inventory, gifts or proof. |
| `rating_value`, `rating_count` | Nullable rating 0–5; nonnegative integer count. Supply only substantiated data. |
| `price_cents`, `compare_at_price_cents`, `sku`, `inventory_qty` | Base price 0–2147483647; nullable comparison price in the same range; SKU up to 120; inventory nullable integer. |
| `options` | At most two: `{name,display_type,values}`. Name 1–60; display type `button` or `image-swatch`; 1–50 unique values each. Value text 1–80, optional nullable `swatch_hex` up to 16 / `swatch_image_url` up to 2048. Combined matrix at most 200 variants. |
| `variants` | At most 200. `option_values` matches declared option order, at most two values. Fields: `sku`, `price_cents`, nullable `compare_at_price_cents`, optional nullable `cost_cents`, `weight_grams`, `barcode`, nullable `inventory_qty`, `is_active`, `image_url`. No caller-supplied variant ID on create. Prices/weight are nonnegative integers; barcode up to 80; image URL string up to 2048. |
| `media` | At most 100 `{url,alt?,kind?}` entries; HTTP(S) URL up to 2048, nullable alt up to 300, kind `image` or `video`. |
| `subscription_product_id` | Must be absent/null. Subscription enrollment is an explicit page-offer choice. |

The shared create schema also accepts legacy `tiers`, `bundle`, `specs`, `sections`, `page_config` and `is_active`. They are not a substitute for the native funnel document. Use the existing product-create reference for their nested schema; do not copy a store layout into a funnel.

Edit with `PATCH /v1/v5/catalog/products/:id` and `{baseUpdatedAt,product}`. Preserve the exact returned `product.updated_at`, including fractional precision. Metadata is partial; existing variant IDs/store links survive. Supply options with variant combinations, and an explicit base or variant price for each new variant. Omitted media remains; `media:[]` clears it. Edit rejects `bundle`, `tiers`, `specs`, `sections` and `page_config`. A stale timestamp or duplicate handle returns 409: reread and reconcile instead of overwriting.

```json
{
  "requestKey": "travel-kit-v1",
  "product": {
    "title": "Travel kit",
    "handle": "travel-kit",
    "status": "active",
    "currency": "USD",
    "price_cents": 2995,
    "options": [{"name":"Size","values":[{"value":"M"},{"value":"L"}]}],
    "variants": [
      {"option_values":["M"],"price_cents":2995,"sku":"KIT-M"},
      {"option_values":["L"],"price_cents":3495,"sku":"KIT-L"}
    ],
    "media": [{"url":"https://assets.example.com/kit.webp","alt":"Travel kit","kind":"image"}]
  }
}
```

##### Native page composition and media

| Blocks | Purpose |
| --- | --- |
| `layout.stack`, `content.textFlow`, `content.link`, `content.mediaImage` | Semantic wrappers, mixed inline typography, links and unframed responsive media; all remain editable. `anchorId` supports in-page navigation. |
| `content.disclosure` | Editable summary/content slots for keyboard-accessible expandable sections. |
| `content.tabs`, `content.tabTrigger`, `content.tabPanel`, `content.tabToggle` | Editable tab contents; subscription tabs/toggles can select matching published offers instead of changing only their appearance. |
| `content.collection`, `content.collectionItem`, `content.collectionSort`, `content.collectionPagination` | Native repeatable content with sorting and paging controls. |
| `commerce.selectionContent` | Editable content conditioned on the selected published offer, for genuine pack-specific details. It does not add unpriced gifts to a cart. |
| `commerce.option` | Composable option-choice row or card bound to a real variant group/value. It can choose a size from a guide and close its enclosing popup; required choices still pass server validation. |
| `content.input` | A local single-line or multiline text field. Its value is neither submitted nor persisted, and Enter does not submit an enclosing form. Use checkout fields or quiz controls when the flow must collect data. |
| `layout.popup`, `layout.reveal`, `content.slider` | Native dialogs, scroll-triggered content and editable slides. Popup `triggerId` accepts up to sixteen comma-separated native block IDs. Reveal supports a pixel/percentage threshold or `showAfterAnchor`: content appears when the named anchor reaches the viewport and hides again above it. The numeric threshold remains the fallback when the anchor is absent. Optional `motion: "slide-up"` animates fixed content, respects reduced motion and removes hidden controls from keyboard interaction. Deferred blocks cannot conceal required payment controls. |
| `checkout.billingAddress` | Separate billing/delivery selection, wired to the existing checkout form and receipt data. |

Gallery overlays are editable slots. Galleries can place arrows beside the image or thumbnail row. Inline countdowns support a span element inside text; countdown appearance does not override server offer expiry.

Upload owned page media through `POST /v1/v5/funnels/:id/assets` with `{contentType,base64}`. Response `{url,path}` supplies the hosted source for native blocks. Accepted MIME types: PNG, JPEG, WebP, GIF, AVIF, static SVG, MP4 and WebM. Decoded maximum is 20 MiB; SVG maximum 512 KiB. File signatures must match the MIME. Static SVG validation rejects scripts, events, animation, external references and unsafe CSS. Fonts use `/v1/editor/fonts`. Never place HTML, external executable scripts or base64 media inside a native document.

Serialized native documents are limited to **2 MiB**, depth **64**; draft requests have a **2.5 MiB** budget. Reuse inherited styles and responsive differences instead of repeating full style snapshots. Upload assets separately. Draft saving remains optimistic with exact `baseRevision`; publication validates the complete native tree.

##### Initial cart and required choices

Landing continuation accepts `initialSelection:[{offerId,variantId?,quantity?,confirmedOptions?}]`: one to ten unique published offers, quantity 1–10 inside the offer's bounds. The server resolves ownership, stock, currency, prices and subscription terms. No browser amount, product ID or plan ID is accepted. An offer's `initialShippingMinor` applies once per selected offer, independently of recurring charges.

For `commerce.variant` with `requireChoice:true`, record a concrete confirmation: `{"Size":"M"}` for a named option or `{"$variant":"<selected UUID>"}` for a whole variant. At most twenty names (1–80 characters) and values (1–160). A default quote does not count as an explicit required choice. Continuation and payment reservation validate the current published source and checkout requirements.

The flow view supplies `initialSelection` and, on checkout, `initialCart:{revision,editable,currency,totalMinor,lines}`. To edit the checkout selection, the trusted storefront sends the current `nodeId`, the exact 64-character `cartRevision` returned by the latest flow view and the new `initialSelection` to the buyer runtime (storefront runtime, not part of the client API).

This returns the refreshed authoritative flow view, including its new revision and totals, without advancing or charging. It rejects stale revisions, a different pinned source, paid/reserved carts, completed or expired sessions. The existing payment preparation signs the trusted revision. Do not compute a replacement revision or replay payment to fix a cart conflict. Runtime routes use the checkout-bound server bearer, verified domain and buyer session cookie; never put that bearer in frontend code.

##### Questionnaire pages

Use one `funnel.quiz`, with 1–30 `funnel.quizStep` children and unique `questionId` values. Options use `funnel.quizOption` or enum dropdown `funnel.quizSelect`. `funnel.quizProgress` and `funnel.quizNavigation` provide navigation. Required single/multiple choice and informational/timed steps are supported. Branches must point forward; only a single-choice auto-advance answer may branch. Finish belongs to the last step.

Finish sends `action:"continue"`, current `nodeId`, and `quizAnswers:{questionId:[declaredOptionValue]}` through the flow action endpoint. At most thirty question keys, twenty unique answers per question, 160 characters per value and 32768 serialized bytes. Arbitrary free-text answers are not accepted. The server validates reachable required questions against the immutable document, rejects unknown keys/options and stores only reachable answers atomically with advancement. An optional `initialSelection` can accompany the continuation. Neither field can accompany upsell confirmation/authentication fields, and neither submits a payment.

#### Thank-you pages

A Thank-you node can select a published Thank-you page or retain the native default confirmation. The default document separates confirmation, order summary, customer information, order updates and help into movable blocks. Each has configurable text, visibility and layout variants, alongside the shared style and width controls. Custom pages pin their published version when the flow is published. A store assigned directly to a checkout keeps its existing default confirmation; a store assigned to a flow follows the selected flow page.

Receipt totals, currencies and items come from the buyer session's captured payment and commerce facts, including accepted post-sells. Different currencies are displayed separately. Subtotal and discount appear only when recorded; there is no inferred conversion or fabricated shipping status. Customer fields use the authenticated receipt context, and payment display is limited to brand and last four digits. Missing support, return or tracking destinations are not invented. A custom Thank-you page takes precedence over the checkout's fallback completion URL.

Initial product, selected variant and gift images are copied from the exact owned, verified server cart when available. This optional presentation read does not reprice the order or change payment routing. Accepted post-sells carry their quoted item images into the combined receipt. Check both zero-price gifts and paid additions when verifying a layout; an absent historical image is not a reason to create another payment.

A buyer returning after a paid post-sell session expires can still open the configured Thank-you page and receipt. Remaining offers follow their decline route for presentation, with the pinned paid conditions and A/B choices preserved. This does not record a decline, move the stored cursor, change the original completion reason or enable another purchase. An unresolved payment continues through reconciliation; an unpaid or reversed initial payment does not authorize a paid receipt.

Page views are browser observations, distinct from reaching Thank-you on the server. Served pages include a short-lived signed `observationToken`; the browser posts `event: "page_view"`, that token, the displayed `nodeId` and a stable UUID `viewId` through the authenticated storefront proxy (storefront runtime, not part of the client API). Repeated delivery is deduplicated, and a delayed observation retains the page actually displayed. Completed or expired paid receipts can record their Thank-you visit without reopening the flow. Simulations remain excluded, and historical completions are not counted as unobserved visits.

#### Post-sell offers and selection

**Products** accepts up to 20 published configurations with unique IDs and one currency. Each configuration fixes a product, variant, quantity from 1 to 10 and unit price. The API accepts the legacy single offer or `{ "offers": [{ "id": "offer-a", "productId": "...", "variantId": "...", "quantity": 1, "unitPriceMinor": 4999, "currency": "USD" }] }`.

The Single offer block binds an `offerId`; Multiple offers and Quantity break present configured selections. Add/Remove only edit the upsell cart. Buyers can change variants and quantities only within the merchant's published `choices` allowlist and limits. Fixed legacy offers retain their configured variant and quantity. Images, price and summary follow the admitted quote together.

In the buyer runtime (storefront runtime, not part of the client API), the page quotes `nodeId` and `selections: [{offerId, variantId?, quantity?}]`, receiving authoritative totals and a short-lived `quoteToken`. Only **Confirm order** submits `action: "confirm"`, `scope: "page"`, those selections, the quote token and displayed `acceptance` (`version: "post-purchase-accept-v2"`, `locale`, `amountMinor`, `currency`). The server verifies the signed basket, recomputes availability and tax, and creates one order for all selected lines. Legacy public `accept`, unquoted confirmations, unknown IDs and caller-supplied prices, PAN or MID credentials are refused. The only additional card verification field is the freshly entered `payment.securityCode` described below. Single-card Decline removes an item; page Decline continues without a purchase. Reporting and webhooks retain the exact selected line items.

#### Native post-sell presentations

| Block | Presentations | Runtime facts |
| --- | --- | --- |
| Upsell slider (`funnel.slider`) | Spotlight, product rail, compact rail, editorial | Published product choices; configurable 1–3 products per view, images and navigation. Selection persists between slides. |
| Original order summary (`funnel.originalOrder`) | Receipt, product gallery, compact, expandable receipt | Captured initial products, quantities, paid amount and optional tax/shipping/discount/protection breakdown. |
| Original order confirmation (`funnel.originalConfirmation`) | Banner, centered, receipt header, minimal | Captured initial order number and amount. No live confirmation without an initial capture. |
| Selected offer savings (`funnel.savings`) | Summary, price comparison, receipt, compact | Actual selected compare-at reduction and the amount due with basket-level tax rounding. |

Single offer also supports reversed, image-led and editorial layouts. Multiple offers and Quantity break support featured, alternating and open catalog layouts. Order summary supports ledger, band and minimal layouts. There are 46 post-sell presentations across the ten native blocks, including confirmation and decline actions; the new layouts do not change an already published page's selected layout.

Paid post-sell views receive the same buyer-scoped `confirmation.orders` receipt as Thank-you pages. Original-order blocks select `kind: initial`; combined receipts include captured `kind: upsell` additions. Preview/editor sample data is explicitly inert and is never used as live proof of payment.

The native Upsell slider is a visible offer block. The global amount, payment disclosure, Confirm offer and Decline offer remain outside its slides. A required offer hidden inside a general `content.slider`, popup, disabled column or condition still fails publication. Savings never fabricate a discount when there is no selection or compare-at reduction.

Five complete native templates are available: Coco — Product spotlight, Corso — Curated collection, Market — Quantity selection, Shopify — Useful additions and Volt — Product rail. Product configuration and account-specific imagery remain merchant-owned.

#### Graph contract

Management routes are under `/v1/v5/funnels` and `/v1/v5/flows`. Affiliates work in their own affiliate workspace; it is not part of the client API. The endpoint reference (Part 4) includes every draft, version, publish, restore, duplicate, validate and assign operation.

The minimal valid draft graph is:

```json
{
  "format": 1,
  "entry": "entry-point",
  "nodes": [
    { "id": "entry-point", "kind": "entry", "name": "Entry point", "position": { "x": 80, "y": 80 } },
    { "id": "checkout", "kind": "checkout", "name": "Checkout", "position": { "x": 400, "y": 80 } },
    { "id": "thank-you", "kind": "thank_you", "name": "Thank you", "position": { "x": 720, "y": 80 } }
  ],
  "edges": [{ "from": "entry-point", "output": "next", "to": "checkout" }, { "from": "checkout", "output": "next", "to": "thank-you" }]
}
```

Use `next` for Entry, landing and checkout outputs. Entry has no incoming edge and its ID, name, position and `graph.entry` cannot be changed after creation. A post-sell requires `accepted` and `declined`; optional `payment_failed` defaults to the declined branch. Landing and post-sell nodes require `pageId`; Thank-you optionally references a published `thank_you` page. The server supplies immutable `pageVersionId` values on publication. Multiple landing and checkout branches are permitted, with exactly one checkout on every completed path. No unpaid path may reach a post-sell or Thank-you, and no paid path may return to Entry, a landing or checkout. All nodes must be reachable, without cycles, with at most ten post-sells per path. The graph is bounded to 64 content nodes plus Entry and 257 edges.

An `ab_test` node defines `branches: [{id, name, weight}]`: 2–8 positive relative integer weights with a sum no greater than 10,000. Connect each `branch:<id>` output. A `condition` node defines `{mode: "all" | "any", rules: [...]}` and connects `matched` and `unmatched`. Rules support country/store/currency membership, product any/all/none, and numeric equals/greater/less/inclusive-between for cart amount, item count and same-currency store AOV over the prior 30 days. Money is entered as a normal currency amount in the modal; the API uses integer minor units plus currency. Missing facts do not satisfy negative rules. After the initial payment, product, item-count and cart-amount conditions use the captured initial order, including checkout additions and the total paid. Later post-sell purchases do not change that initial basket. Country, store, routing seed and same-currency AOV remain pinned at entry. The server records each paid routing decision for replay; missing historical item details remain unknown.

Routing is server-authoritative: the entry pins the published flow version, seed, cart facts and decisions. A reload cannot reroll the experiment. A store assignment chooses the real checkout before reading its credentials; changing the store flow applies to new carts only. Standalone facts come from the validated original offer; unavailable store/AOV remain unknown. Country uses the serving request when available. Visitor URL parameters do not select a branch.

A standalone Checkout node may select a saved offer link with `shortLinkId` and `shortLinkRevision`. Publication and entry recheck its immutable configuration, account/domain, active state and creator permission. An affiliate-owned flow may use only that affiliate's saved links. Store and standalone checkout paths cannot be mixed. Publication rechecks all branches, not only the currently sampled branch. Store-assigned flows must keep active chargeable store checkouts, and assignments must be removed before archiving.

The merchant-only `GET /v1/v5/flows/options` supplies owned store/product choices without customer or credential data. A/B and Conditions preview controls choose simulated outputs locally and render each branch's own checkout.

Draft writes use `baseRevision`. A `409` means another tab changed the draft: reload before saving. A `422` on publication includes issues to correct. Read the current editor document before saving it; its structure is owned by the shared editor engine.

Affiliates may view assets permitted by their grant and sharing policy, duplicate shared assets, and edit their own drafts. Funnel edits cannot alter commerce or protected controls. Publication requires merchant review. Assigning a flow as an affiliate requires ownership of both the flow and the selected checkout. Sharing controls are supplied by the affiliate module.

The checkout, flow and entry landing may have one affiliate owner in common; merchant-owned assets are neutral. Conflicting affiliate owners prevent publication, assignment and new entries. The resolved owner takes precedence over affiliate tracking in URLs and cookies. Post-sells inherit their initial order's attribution.

#### Entry and session behavior

Pages remain on the verified checkout domain. `/funnel/:pageId` resolves a uniquely published landing entry. Standalone landings can create a new entry. A store landing requires a valid existing store cart/session; it does not invent a cart. Store checkout entry records the verified shop, checkout, cart and attribution before page rendering, then removes `kt` from the visible URL.

Reconciliation and captured-order delivery run on the elected API job leader when `BACKGROUND_JOBS_ENABLED` permits jobs. Reconciliation never starts another sale. Shutdown stops scheduling and waits up to five seconds for active work; durable records support recovery.

Order effects require a shared authenticated key on API and storefront: an explicit `V5_FLOW_EFFECTS_SECRET` of at least 32 characters, or the matching encryption-key derivation. `STOREFRONT_INTERNAL_URL` must reach the internal order-effects route. Missing or invalid secrets reject worker startup.

An opaque host-only Secure HttpOnly SameSite=Lax cookie binds the browser to a server-side session with 30 minutes of idle lifetime. The API refreshes that cookie while the shopper interacts. Tokens, session IDs, reusable payment credentials and customer details do not appear in post-payment URLs. `/flow/:checkoutId` exposes only the public checkout identifier; the cookie and exact domain select the session.

Technical payment-provider returns first use Kontrol's fixed API/CRM origin, then resume the validated buyer destination. A return navigation cannot approve or replay a sale. Required merchant identity and registered wallet domains remain separate from the return URL. During one server-rendered flow request, page data and pixel selection share the same freshly verified session access; later page requests, quotes and actions still authorize independently. This creates no public bypass, shared buyer cache or extra integration parameter.

Use *Test cards: checkout and flow simulation* in Part 2 for a persisted application simulation. A verified initial test payment follows the published flow and records accepted test additions in a separate simulation ledger; it does not create real upsell payment intents, processor requests, 3DS work, purchase pixels or order-delivery effects. The receipt includes these additions as test data. A browser `test` parameter cannot grant this behavior.

##### Store entry during the first document

The storefront may reserve a random HttpOnly flow cookie before rendering a new store checkout. This reservation grants no access. After fresh cart pricing, the storefront server calls the internal store-entry runtime route (`POST /v5/store/entry`, not part of the client API) with its existing checkout-bound API key and an optional `bootstrap` proof. The storefront verifies its local middleware proof, then signs the API proof with the exact private API key used for authentication, preserving the original issue time. The server-only HMAC binds the exact host, checkout pathname, token and issue time; it expires after 60 seconds. The API verifies identity and scope before the proof. API and storefront do not need to share `CRON_SECRET`. Normal account, shop, cart, checkout, active-state, affiliate and pinned-flow checks still run before the session is created.

Successful bootstrap admission returns `inline: true`, public pixel recipients and allowlisted tracking only after its transaction commits. The same freshly priced cart can then render without a second browser admission redirect. A colliding token returns 409 and never overwrites an existing session, including a pending or uncertain payment. Calls without `bootstrap` keep the established redirect and compatible-session behavior. A new `kt` attribution hop still takes the clean redirect before pixels.

Any attribution cookie from inline admission travels in an encrypted 60-second envelope to the browser's same-origin `POST /api/v5/store-entry`. This browser handler accepts only JSON `{cookieDelivery}`, checks Origin and the existing HttpOnly flow cookie, and emits the allowlisted attribution cookie with a 204 response. It does not create a session, place an order or initiate a payment. The signed `__Host-kontrol_flow_scope` cookie contains only a navigation scope and is signed locally by the storefront, never by the API; it never replaces server authorization. These two internal transports are not external integration APIs.

The server permits only the current node and valid predecessor. A post-sell requires a captured initial payment. Reloads, double clicks and concurrent tabs reuse the same durable intent and cannot charge a node twice. Accepted, declined and failed outcomes append immutable node-action facts. Completion appends its own immutable fact.

#### Reusable payment capability

Post-sell page admission depends on the confirmed initial payment, not its provider. A captured NMI, Convesio, Stripe, wallet or bank-wire payment can proceed to the published post-sell. Showing an offer does not prepare a payment or certify that its original payment method can be reused.

Supported original-card adapters create a **new customer-initiated sale on the exact original MID**. NMI uses `type=sale`; Convesio uses its direct card-payment API; Stripe uses its own payment and authentication continuation. These paths do not use Customer Vault, a reference-sale endpoint, the rebill scheduler or another ATRI cascade. Wallet and wire purchases use their native confirmation flow with the original owned payment source; an initial wallet approval or wire receipt never authorizes an automatic additional payment.

Store and standalone checkouts collect payment for the initial purchase. They omit the card-reuse paragraph and disregard legacy notice assertions in new browser submissions. At post-sell, a buyer can authorize one additional NMI or Convesio purchase by confirming its signed selection and total and entering the original card’s security code. The server verifies the approved initial capture, dispatched card, provider credentials, account, session and winning MID. Its evidence belongs to that specific purchase. Historical checkout notice records retain their original meaning.

##### Fresh security-code verification

When the flow view returns `paymentRequirements.securityCodeRequired: true`, collect a fresh three- or four-digit security code for this purchase and send it as `payment.securityCode` on confirmation. This applies to Convesio card sales and NMI card sales authorized at the offer without a prior checkout notice. The payment uses the original verified card and MID. The signed amount and the buyer’s explicit acceptance authorize the addition.

Keep this value only in request/browser memory for the current confirmation. When fresh 3DS returns an authentication step, include the same freshly entered value on each `action: "authenticate"` continuation that can dispatch the sale. Cancellation does not require the code; `continue` and `decline` reject `payment`. A reload must collect it again. Do not put it in URLs, cookies, browser storage, intents, authentication records, queues, analytics, diagnostic logs or API responses. Background authentication observation and payment reconciliation never accept it. Missing required verification returns 409 without sending a sale; malformed codes return 400. A status read must establish the existing payment state before any new manual confirmation; never automatically replay a failed request.

The Gateway modal **Payments** tab identifies the customer-initiated sale method without a Vault toggle. `GET /v1/v5/flow-payment-capabilities` returns `method: cit | null` and readiness `configured | inactive_mid | unsupported_provider`; `configured` describes available code, not a promise that each order has an eligible card or will be approved. The historical `enabled` Vault flag is exposed as false. Enabling it through the legacy PUT endpoint is rejected; disabling historical flags remains allowed. New Vault payments are refused. Already dispatched historical intents retain read-only reconciliation so a prior payment is not lost or charged again.

Payment admission still checks the captured source, account ownership and current payment policy. If that source cannot support the requested purchase, confirmation is refused without charging another provider; the original order remains confirmed and the buyer can decline the offer. An unavailable method does not hide the post-sell page. Recurring post-sell offers are rejected at publication; initial checkout subscriptions remain unchanged.

The runtime and page support inline bank challenges, with a single committed payment intent and status polling. Post-purchase authentication starts after explicit acceptance using the provider's supported path. PAAY defaults to two independent requests with frictionless requested; the issuer still decides whether a browser challenge is necessary. The Post-sell settings control request count, challenge preference, required proof and browser-step handling. The first payment's card authentication does not authenticate a later amount, and its cryptogram is never reused. Provider references: [NMI transaction and stored-credential fields](https://docs.nmi.com/reference/transactions-processing), [NMI Query API](https://docs.nmi.com/reference/query).

#### Pending and unknown payments

The intent and cap reservation commit before the provider request. A timeout becomes `UNKNOWN`, keeps the reservation and never retries the sale. The shopper sees a status message; the background reconciler queries the original provider transaction on the same MID. Only matching order reference, amount, currency and successful sale evidence can produce a captured fact. Conflicting or incomplete evidence remains unknown for operational review.

Known declines release the reservation and follow the failure/decline branch. A captured result atomically creates the canonical transaction, immutable payment fact, real order, action and next-node transition. If order persistence fails, the intent remains reconcilable and a second sale is not sent. Inspect the original intent and provider evidence instead of triggering a new payment.

#### Pixels and rollback

PageView fires on the first post-payment page and each later page. Initial Purchase is deferred from checkout to that first page for a custom flow; each accepted upsell adds its own Purchase. Event IDs are stable real-order UUIDs across reloads. The existing Meta, TikTok, Snapchat, Pinterest, AppLovin/Axon, X and Google browser integrations are reused, including the installed Whop bridge. Merchant recipients and eligible immutable saved-link pixels are combined without exposing server tokens. Affiliate profile pixel settings are retired; configure affiliate-owned recipients on the saved link. Conflicting Axon keys or event mappings fail explicitly.

To stop new visits, unassign or unpublish the relevant flow. Existing immutable payment facts and unknown intents remain retained; reconciliation never starts another sale. Rollback migrations refuse to remove populated monetary history.

#### Local verification and rollout

Graph, session, payment and renderer checks include local unit, mock-provider and isolated PostgreSQL tests plus fixture browser acceptance. These checks do not certify a live payment provider or certify deployment configuration. Review the deployment’s migrations, worker configuration, original-card readiness and actual provider contract before rollout. *Commerce workflows* in Part 2 separates REST editing from the server-authenticated buyer runtime.

##### Payment capability prerequisites

Inspect post-purchase readiness in the existing **Gateway modal → Payments** tab. New original-card upsells do not need Customer Vault activation. Configure authentication in **Integrations → your 3DS provider → Post-sell**, then use the modal's shared **Save** button. These are owner settings, not affiliate link options. The payment source stays bound to the initial purchase; unavailable credentials never start another ATRI dispatch or select another MID.

API: `GET /v1/v5/flow-payment-capabilities` reports implementation readiness. The historical PUT only accepts disabling a legacy flag (`{"enabled":false}`); enabling Vault is rejected. Affiliates cannot administer gateway settings.

GET rows include `readiness` (`configured`, `inactive_mid` or `unsupported_provider`), `method: cit | null` and `challengeSupported` for registered card adapters. These describe MID capabilities. Offer admission follows a verified checkout capture. Paid card confirmation separately verifies the captured source and the buyer’s authorization for the selected offer.

At acceptance and the committed dispatch gate, card payments recheck the original owned ATRI, applicable BIN rules, blacklist and original MID. A rule selecting another MID cannot reroute the upsell. Fresh 3DS is independently bound to the accepted offer amount/currency, exact original card/MID and current provider identity. Initial proofs are never reused. A changed policy, cancelled/expired authentication or failed required authentication releases the reservation and records the skip; it does not become a bank decline. Requests already dispatched continue read-only reconciliation.

Post-sell runtime responses expose the same paid-order `confirmation` as the thank-you page. `confirmation.orders` and purchase events distinguish `kind: "initial"` from `kind: "upsell"`; only confirmed captures enter the receipt. Declined, pending and uncertain payments never add receipt lines or Purchase events.


#### Saved flow links

Flows and standalone checkouts use the same Links table, offer editor, asset upload and Webhooks tab. Click the flow row to open its Details/Links modal. Builder, Preview, assignment and management are explicit Actions available from both the table and that modal.

REST uses `/v1/v5/flows/:id`. It exposes GET `link-options`, GET/POST `short-links`, PATCH `short-links/:linkId`, and POST `link-assets`. Their complete parameter/body/revision contracts match *Standalone checkouts and saved offer links* in Part 2. Affiliates manage their own flow links in their affiliate workspace, which is not part of the client API.

1. Publish a complete flow with explicit published, active checkout nodes. Each checkout needs owned payment routing and the same verified serving domain.
2. Read `GET /v1/v5/flows/:id/link-options`. No store or product synchronization is required. Freeform product lines, logo, colors, shipping/protection, offered languages/countries, legal links, pixels and supported integration choices use the shared editor and API parameters.
3. Save `POST /v1/v5/flows/:id/short-links` with `{ "name":"Offer A", "active":true, "parameters":{ "currency":"USD", "product1_name":"Travel bag", "product1_price":"5999", "product1_quantity":"1" } }`. Use the returned `link.url`; never compose a projected checkout slug yourself.
4. For link webhooks, use the returned `link-options.webhookCheckoutId` with existing checkout webhook endpoints and the saved `linkId`. Ownership checks still apply.
5. Edit by sending `id` and `baseRevision`; stale revisions return409. Save creates an immutable revision pinning the flow and every checkout branch. Republishing a flow does not silently rewrite existing links.

Store checkout templates keep their type and assignments. A signed flow link can reuse their published design through a separate commerce snapshot. Bare URLs cannot enter this snapshot. Reporting retains the actual checkout ID, flow, affiliate and link attribution while classifying autonomous offer sessions as standalone commerce. Revoked assets or creator grants are rejected at entry.

#### Thank-you blocks

The default editable Thank-you contains eleven native blocks: Store header, Confirmation, Order summary, Customer information, Delivery map, Order updates, Shipping protection, Email reminder, Customer support, Help/language/shopping, and Order policy. Customer information includes contact, shipping/billing addresses, shipping method and payment method. Captured receipt data drives money, products, payment status and customer fields; the editor controls presentation only. Legal dialogs, delivery-map fallback, locale selection and support chat retain their existing behavior. See the repository parity inventory for a field-by-field audit.

##### V5.1 saved-link URL pair

Checkout and flow links share `shortUrl` (`ktrl.ink`), `longUrl` (`kontrolcheckout.com/l/<id>`) and `hosting:{short,long}` readiness. Read the returned URLs and distribute only `ready` variants; pending infrastructure is not a successful launch. Both pin the same saved offer and all flow checkout branches, including attribution and pixels. Historical URLs keep their original destination. The affiliate supplies logo content; logo size stays with the owner layout. See *Standalone checkouts and saved offer links* in Part 2 (Canonical short and long URLs (V5.1)) for request, response and failure examples.

#### Post-purchase product sources

Merchant product configuration is saved alongside the document through `PUT /v1/v5/funnels/:id/document/draft`. Keep the current `baseRevision` and document. Manual selection still accepts `offer: { offers: [...] }`, with account-owned active product and variant IDs, quantity and unit price in minor currency units.

Automatic selection uses the following offer instead:

```json
{
  "offers": [],
  "selection": {
    "mode": "smart",
    "limit": 3,
    "discount": { "kind": "percent", "value": 10 },
    "quantities": [1, 2, 3],
    "choices": { "allowVariants": true, "maxQuantity": 10 }
  }
}
```

- `mode: smart`: rank active products from the originating store by approved, non-test units sold during the last30 days. Exclude products in captured orders of this session. `limit` is1–6. Autonomous links with no originating store must use manual products; smart selection safely skips when there is no eligible store/product.
- Optional Smart `choices` permits active variants and a maximum quantity of 1–10. With `allowVariants: false`, quantity choices apply to the default variant only. Omission preserves existing fixed offers. Prices are calculated per permitted variant using the configured discount; incompatible variants are excluded from the pinned allowlist.
- `mode: quantity`: offer additional units of the first eligible purchased product. `quantities` contains1–6 distinct quantities between1 and10. The customer selects one tier, not several tiers together.
- `discount.kind: percent`: integer0–90. `fixed`: discount per unit in minor currency units. `exact`: exact unit price in minor currency units. Final prices must be positive and cannot exceed the original unit price. Invalid/empty recommendations are skipped without blocking the original paid order.
- Quotes are persisted once per session and flow node. Refreshing or changing catalog prices cannot silently alter the displayed offer. Acceptance rechecks availability, tax, currency, account scope and the original payment binding; browser amounts are never trusted.
- The ten native post-sell templates include the original PS-01–PS-03 and seven reference compositions: thank-you/offer summary (PS-04), classic offer (PS-05), gallery/product (PS-06), advertorial (PS-07), three-product bundle (PS-08), one-product page (PS-09), and progress/three products (PS-10). All use store branding and catalogue products. Discounts and product source remain merchant commerce configuration, not affiliate editable text.
- Optional `selection.timer` uses the same shape as a manual offer timer: `durationSeconds` (1–86400), optional absolute UTC ISO `deadline`, and `expiryBehavior` (`hide-offer`, `auto-decline-and-continue`, `show-expired-text`, `keep-offer`). The deadline is persisted at the first offer view for that session/node; refresh and later catalogue changes do not restart it. PS-04–PS-09 default to 600 seconds with `show-expired-text`; PS-10 has progress steps without a deadline. Products settings expose the timer for automatic and manual sources. The server enforces expiry when quoting/confirming.
- A verified final checkout capture admits the shopper independently of the original payment provider. The existing payment capability handles explicit confirmation on the original source; these templates do not change CVV, 3DS, MID, ATRI or wallet behavior. No alternate gateway fallback is introduced.
- Deployment requires `v5_20_funnels_009_offer_selection.sql` before enabling these automatic sources. Existing fixed offers are unchanged.

Configure products from the selected block's Content → Products panel. The library offers Single offer, Multiple offers and Quantity break families with layout variants. Quantity options belong to Quantity break; the generic Source selector offers manual products or Smart select from store. With a preview store selected, the builder resolves its real catalogue, variants and images. Without a store it uses clearly labelled demonstration data; a missing purchase context for Quantity break is shown explicitly. Preview never charges a card.

New manual product picks include eligible active priced variants and quantities 1–10 under **Customer choices**. Merchants can narrow or disable them before publication. Existing saved offers are not silently widened. Block display toggles separately control variant/quantity selectors, compare-at price and discount labels; hiding them does not alter published commerce permissions. Store header and Store main color bindings follow the selected preview store.

Add/Remove only change the upsell cart. Pre-add to upsell cart prepares the selected products automatically when enabled on a block, without creating an order. Only Confirm order submits the full cart and starts its server-authorized payment; the independent-acceptance setting is retired. Empty carts cannot be confirmed, and the same confirmation cannot create duplicate payments.

Design references: [Rebuy's post-purchase setup](https://help.rebuyengine.com/en/articles/6120623-creating-a-post-purchase-offer) for exclusion and product selection, and [Shopify product offers](https://shopify.dev/docs/apps/build/checkout/product-offers) for explicit post-payment acceptance. These patterns do not guarantee a conversion or AOV uplift.


#### 3DS by sale context

Integration settings have separate Straight, Post-sell and Rebill tabs and one global Save. Straight and Post-sell can inherit or override enablement, one/two requests (PAAY), issuer challenge preference, required proof and the action when a browser step is needed. A frictionless request is a preference, not a guaranteed issuer result. The existing Straight double mechanism may reserve its second proof for future collection; post-sell requests are both for the currently accepted amount and never enroll a subscription or feed the rebill stock.

For a pending post-sell, `authentication` contains only session ID, browser action, expiry and step/count. The same-origin storefront sends `action: authenticate` to poll, finish a method/challenge or cancel. It never replays accept or supplies payment fields. Reload resumes the same offer, session group and reserved cap. Concurrent continuations can consume one proof and commit one dispatch only. Successful/declined transaction records carry the actual authentication count/result; pre-MID refusals record authentication costs without inventing sales. Pending/declined offers never enter paid totals or Purchase pixels.

Unattended PAAY rebills can consume compatible unused saved proof or turn authentication off, and can require proof. They cannot request a fresh browser challenge or double browser authentication without a customer session. Unsupported combinations are rejected instead of saved as ineffective settings.

##### Concurrent PAAY authentication

After a shopper confirms a post-sell, its primary usable authentication can proceed to the existing payment intent while the optional secondary continues separately. Both authentications concern that accepted post-sell amount. The secondary never creates subscription enrollment, enters the rebill proof stock or changes an already dispatched payment. An actual primary issuer challenge remains interactive; a secondary challenge is not shown as a hidden browser interaction.

Run returned Method actions in real hidden browser iframes while polling their existing sessions. A Method-start signal records only that its POST was submitted, not that authentication succeeded. The API returns newly available Methods before waiting on issuer updates, so delayed provider responses cannot make the browser wait for a fingerprint it has not yet been allowed to perform.

Flow responses may carry `backgroundAuthentications` with the original `nodeId` even after navigation to the receipt. The storefront continues this optional work through the buyer runtime's background-authentication operation (`{nodeId, sessionId, stage:"poll"|"method"}`; storefront runtime, not part of the client API). That operation checks the buyer session and original intent bindings; it does not run payment authorization, dispatch, capture or flow advancement. It carries secondary work rather than the `authenticate` payment action. A failed read or a late result must never trigger a new offer confirmation.

The background worker polls only accepted PAAY references and reserves eligible unused straight-sale proofs after checkout allocation is final. Browser Methods cannot run on that worker. Leaving the page before fingerprinting has run can reduce completion of the optional secondary; it does not hold up the primary purchase or turn it into an error. No fresh authentication or gateway charge is issued by the worker.

##### Optional shipping protection presentation

`checkout.shippingProtection` supports the legacy switch plus checkbox and inline presentations. Its title can contain `[label]` and `[price]`; the price always comes from the signed checkout configuration, never the block. Illustration, typography and description introduction are editable. The configured description and live selected state remain authoritative. `shipping_protection_default_enabled: false` starts optional protection unchecked; omission preserves the existing enabled default and `forced` always remains selected. Buyer changes and their cached choice take precedence over this starting preference.

`checkout.payButton.supportingText` adds a second line inside the existing payment button; `showIcon` controls its lock illustration. Optional `supportingTextGap` (0–40px), `supportingTextWeight` (100–900), and `supportingTextLineHeight` (1–3) control that line’s presentation. When unset, the existing 4px gap, 600 weight and 1.35 line height remain unchanged. It retains the same payment handler, loading state and duplicate-submission lock. `checkout.payment.headingTypography: "inherit"` uses the surrounding native block typography.

The canonical `/l/health` handler proves long-link transport availability and returns no customer/session data. It is separate from the account API.

##### Selected product labels

`commerce.summary.itemTemplate` customizes the selected-item text using `[title]`, `[variant]`,
`[quantity]`, `[pack]` and named dimensions such as `[option.Size]` or `[option.Color]`.
`packLabels` maps published offer IDs to localized pack names. Labels follow the current
selection and render as plain text, never HTML. These presentation settings do not change
the product, variant, quantity or price submitted to checkout. Omitting the template keeps
the existing label. Use square brackets here; the document's general variable engine owns
brace-delimited expressions.

##### Products included in an initial offer

An initial (pre-payment) offer can declare `initialInclusions`, at most 4 entries shaped as `{ "productId": "owned-product-uuid", "variantId": "owned-variant-uuid", "quantity": 1 }`. Quantity must be1–10. The API revalidates account ownership, active status, currency, non-subscription status and stock; included lines are fixed at zero cost by the server. Publication snapshots this selection. The initial cart contains at most 10 lines after merging. These lines appear in the native receipt alongside the paid product, without changing the selected pack quantity or its price.

Configure these through **Products → Included products**. An included digital product is a catalogue line; it does not create a download file or fulfillment integration. Attach an actual deliverable before promising delivery. Post-sell offers do not use this pre-payment inclusion field.

Offer-specific protection: an initial offer may set `initialProtectionMinor` to a non-negative integer in the checkout currency's minor units. This optional fee is applied once per selected offer (summed for multi-selection), replacing the signed `shipping_protection_price_cents` default for that selection. Omitting it uses the checkout default. Protection mode and `shipping_protection_default_enabled` still control whether the buyer pays that fee; the block never supplies the amount.

##### Native receipt composition

`checkout.orderSummary.receiptOrder` optionally groups canonical rows using one of `products-protection-gifts-shipping`, `products-gifts-protection-shipping`, or `gifts-products-shipping-protection`. `receiptGap` sets the spacing. Product presentation fields (`packPresentation`, `packLabels`, `imageSize`, `showVariant`, and related Cart settings) are reused; `shippingImage`, `protectionImage`, and `serviceImageSize` illustrate the actual quoted fees.

Keep a real `checkout.summaryTotals` child in the summary's content slot. The composite prevents nested Cart/fee rows from rendering twice, while neighbouring summaries are unaffected. `showSubtotal:false` hides only the merchandise-subtotal line; `subtotalLabel` optionally names that line. Discounts, tax and the authoritative total remain unchanged. Unset `receiptOrder` preserves the previous free-layout rendering.

`checkout.summaryBar.showComparePrice` and `checkout.orderSummary.showHeaderComparePrice` optionally show a struck-through comparison total in the closed or open summary bar. Both default to `false`. The comparison adds genuine product/selected add-on savings to the current quoted total, keeping shipping, protection and applied promotions unchanged. Gifts, invalid prices and non-discounted carts produce no comparison. The existing `checkout.orderSummary.showComparePrice` setting still controls product-row comparisons only.

Both summary headers also accept `headerLabelColor`, `headerAmountColor`, `headerAmountSize` (pixels), `headerAmountWeight`, `headerPaddingY` (pixels) and `headerMinHeight` (pixels). Size, vertical padding and minimum height support responsive values. Unset controls preserve the existing appearance; these fields never change the quoted amount or the summary's open/closed state.

`headerPaddingX` adds responsive horizontal padding, `headerLabelWeight` sets the label weight, `headerBackground` sets the header fill, and `headerBorderColor` adds one-pixel top and bottom borders. Each is optional. An ordered `checkout.orderSummary` receipt can set `showShippingRow:false` to omit its separate shipping row and `showPackShipping:true` to show authoritative shipping under the selected pack. Fees and totals remain unchanged.

`content.disclosure.summaryMinHeight` sets the expandable section's summary-row minimum height in pixels, including responsive values. Leave it unset to keep the existing minimum. Native keyboard activation, opening and the optional close button remain available.

`giftPriceLabel:"FREE"` applies only to a genuine included product priced at zero. `showPackRecurringTerms:true` displays the matching selected subscription offer's published `recurringTerms`; it invents no cadence, renewal price, or delivery claim, and displays no renewal terms for a one-time purchase. Do not fabricate compare-at prices for gifts or shipping when the catalogue does not provide them. Illustration and label settings never add cart lines or charges; protection remains linked to the existing checkout toggle.

### Checkout webhooks

A merchant administrator, or an API key of the account with `checkouts.read`/`checkouts.write`, manages endpoints through `/v1/checkouts/:checkoutId/webhooks`. Both store and standalone checkouts use the same Webhooks tab and API; saved standalone links have their own scoped Webhooks tab.

#### Saved-link webhooks

Append `?linkId=<saved-link-uuid>` to every operation to manage endpoints belonging to one link. Omit it for existing checkout/account endpoints. Cross-link, foreign-creator and foreign-account endpoints or deliveries are refused. Affiliates manage the webhooks of their own links in their own affiliate workspace; it is not part of the client API.

For link endpoints, configuration must explicitly set `scope: "checkout"` and `includeCustomer: false`. Account-wide recipients and the email macro are forbidden. Link payloads exclude customer data, gateway identity, card last four digits and affiliate cuts; payment exposes only card brand. Signed event IDs, order lines and amounts remain available. The server selects the saved link from persisted session attribution, not visitor-supplied recipient fields. A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope. Current creator permission and endpoint state are checked before delivery. Creation/rotation still shows the signing secret only once; tests, logs and resend stay inside the same link.

#### Add an endpoint

POST /v1/checkouts/:checkoutId/webhooks

```json
{"url":"https://tracker.example.com/events","description":"Conversion tracker","scope":"checkout","format":"json","events":["order.paid","order.refunded"],"status":"active","includeCustomer":true,"ratePerSecond":20}
```

The response is 201 with id and secret. Save the secret now: it is shown once and encrypted at rest. Use scope=account for all current and future checkouts of this account. Only HTTPS port 443 destinations are allowed; credentials in URLs, redirects and non-public addresses are refused. The destination is DNS-checked at save and resolved/pinned again on every dispatch. No request is sent while the endpoint is inactive.

PUT the same complete configuration to /:endpointId; DELETE pauses and removes an endpoint from settings while preserving delivery history. POST /:endpointId/rotate-secret returns the replacement secret once. The previous signature remains present for exactly 24 hours; a second rotation during that interval returns 409 so the promised grace is preserved.

#### Envelope and immutable data

id is the receiver deduplication key, including manual replays. api_version=2026-10-29 is this payload contract. created_at is the event occurrence in UTC; delivery attempt time is the signature timestamp. test=true distinguishes synthetic tests and real test-mode transactions. account_id is the owning merchant scope.

data contains checkout (id/type/name), flow (id/version) and node when applicable; order (id, parent_order_id, status, item sku/name/quantity/price, subtotal/shipping/tax/discount/total/currency); payment (gateway_label/card_brand/last4); attribution (status/affid/affiliate_name/sub1…sub10/source_id/extra); affiliate_cut entries (kind/amount/currency/created_at). All JSON money is integer minor units. data.amount is the event charge/refund, or null when there is no charge. data.currency is an ISO currency. flow.completed includes orders and ended_by (thank_you or expiry).

Customer details are on by default, but omitted entirely when disabled. Allowed fields: first_name, last_name, email, phone, country, address, address2, city, state, postal_code. All commercial/customer labels come from immutable records; unavailable historical labels are null, not reconstructed from mutable current products. PAN, security codes, provider tokens, credentials and session identifiers never appear. The outbox stores IDs only; delivery serialization cannot roll back a payment. Attributed cuts wait for their idempotent ledger consumer.

#### Delivery and retries

Background delivery runs on the elected API job leader when `BACKGROUND_JOBS_ENABLED` permits jobs. Current account ownership, creator permissions and active endpoint state are rechecked before each delivery. Local development keeps background jobs disabled.

Events with a cut-eligible order context wait for a completed cut-consumer receipt (done or noop) before serialization. The cut consumer runs under the same elected leader and global background-job configuration. A pending receipt delays delivery; inspect that durable receipt instead of bypassing the wait.

Any 2xx succeeds. Timeout: 10 seconds including DNS. Maximum request: 256 KiB. No redirects. Per-endpoint durable rate limit defaults to 20 requests/second (1–100 configurable). After an unsuccessful first attempt, retry offsets from its time are 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours, each with ±10% jitter. Ordering is not guaranteed and delivery is at least once: atomically store the event id together with your business update, then return 2xx. Never process a repeated id twice.

After 72 hours of continuous failure, the endpoint is disabled independently of the retry schedule. The owner is notified through a configured account email sender; absent sender/capacity leaves notification pending, SMTP ambiguity is marked unknown without automatic duplicate sending. Review delivery health before explicitly re-enabling. Logs retain 30 days, with up to 2 KiB of redacted response diagnostics and no stored request body. Request previews are rebuilt from the immutable event using the current customer-data policy. Removal/disable of an endpoint stops queued sends.

GET /:endpointId/deliveries accepts from/to UTC instants (to exclusive), state, limit (1–500, default 50), offset. GET /:endpointId/deliveries/:deliveryId returns rebuilt payload and retained attempt logs. POST /:endpointId/deliveries/:deliveryId/resend adds a new delivery generation with the same event id. POST /:endpointId/resend-failed accepts {"from":"2026-10-01T00:00:00Z","to":"2026-11-01T00:00:00Z"}. POST /:endpointId/test accepts {"event":"order.paid"}; every event below can be tested and synthetic tests never create orders or cuts.

#### URL templates

Use format=url_template for GET. Example:

`https://tracker.example.com/?transaction_id={extra._ef_transaction_id}&amount={amount}&order_id={order_id}`

Supported macros: {event}, {order_id}, {parent_order_id}, {amount}, {currency}, {affid}, {sub1} through {sub10}, {source_id}, {checkout_id}, {timestamp}, {extra.<key>}. {amount} is decimal in the event currency (49.99, or 100 for JPY). Empty/missing values expand to empty strings; values are individually RFC3986 encoded. Unknown macros and macros in the scheme/host/port are rejected. Customer email and other private-value macros are intentionally unavailable in GET under the approved privacy decision; use JSON POST for customer details. No flow/session identifiers or secrets belong in templates. Tracker extra values come from the approved attribution allowlist.

#### Verify the signature

Header: Kontrol-Signature: t=<unix>,v1=<hex>. Compute HMAC-SHA256(secret, timestamp + '.' + untouched request body). For GET, replace raw body with the EXACT complete received public URL, including scheme, host, path and query. Use your trusted configured public origin, never blindly trust Host or forwarding headers. During rotation the header carries two v1 values: either may match. Reject timestamps outside a ±300-second clock-skew window. Verify before parsing/using customer data. Store secrets in environment/secret storage, never source code.

Test vector: secret=test; timestamp=1793232000; raw body={"amount":4999}; v1=8ac0712812e91cae7b6828b993902cb78c9e65002e6fa090a5a1f3cf833cafe1.

##### javascript

```javascript
import {createHmac,timingSafeEqual} from 'node:crypto';
// raw is the untouched request body (POST) or the exact complete public URL (GET).
export function verifyKontrolWebhook(secret,header,raw,now=Math.floor(Date.now()/1000)) {
 const fields=String(header).split(','),times=fields.filter(v=>v.startsWith('t='));
 if(times.length!==1||!/^t=\d+$/.test(times[0]))return false;
 const t=Number(times[0].slice(2));if(!Number.isSafeInteger(t)||Math.abs(now-t)>300)return false;
 const expected=createHmac('sha256',secret).update(String(t)+'.').update(raw).digest();
 return fields.filter(v=>/^v1=[a-f0-9]{64}$/.test(v)).some(v=>timingSafeEqual(expected,Buffer.from(v.slice(3),'hex')));
}

```

##### python

```python
import hashlib
import hmac
import re
import time

def verify_kontrol_webhook(secret, header, raw, now=None):
    """raw: exact POST bytes or exact complete GET URL encoded as UTF-8."""
    fields = str(header).split(',')
    timestamps = [x[2:] for x in fields if x.startswith('t=')]
    if len(timestamps) != 1 or not timestamps[0].isascii() or not timestamps[0].isdigit():
        return False
    stamp = int(timestamps[0])
    if abs((int(time.time()) if now is None else now) - stamp) > 300:
        return False
    body = raw.encode('utf-8') if isinstance(raw, str) else raw
    expected = hmac.new(secret.encode('utf-8'), str(stamp).encode('ascii') + b'.' + body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, x[3:]) for x in fields if re.fullmatch(r'v1=[a-f0-9]{64}', x))

```

##### php

```php
<?php
function verifyKontrolWebhook(string $secret, string $header, string $raw, ?int $now = null): bool {
    $fields = explode(',', $header);
    $times = array_values(array_filter($fields, fn($v) => str_starts_with($v, 't=')));
    if (count($times) !== 1 || !preg_match('/^t=[0-9]+$/D', $times[0])) return false;
    $t = (int) substr($times[0], 2);
    if (abs(($now ?? time()) - $t) > 300) return false;
    $expected = hash_hmac('sha256', $t . '.' . $raw, $secret);
    foreach ($fields as $field) {
        if (preg_match('/^v1=[a-f0-9]{64}$/D', $field) && hash_equals($expected, substr($field, 3))) return true;
    }
    return false;
}

```

#### Event examples

All examples below are synthetic. Null fields explicitly mean unavailable or not applicable.

##### checkout.lead_captured

One explicit contact submission per session and normalized email. No order or charge yet.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "checkout.lead_captured",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": null,
    "payment": null,
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": null,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### order.paid

Initial payment captured successfully, after routing has completed.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "order.paid",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": {
      "id": "test-order",
      "parent_order_id": null,
      "status": "captured",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### order.payment_failed

Final failed initial payment attempt after eligible routing is exhausted.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "order.payment_failed",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": {
      "id": "test-order",
      "parent_order_id": null,
      "status": "failed",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### upsell.accepted

Post-sell offer captured on the initial payment’s final MID.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "upsell.accepted",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": {
      "id": "offer-1",
      "action": "accepted"
    },
    "order": {
      "id": "test-upsell",
      "parent_order_id": "test-order",
      "status": "captured",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### upsell.declined

Customer declines a post-sell offer; no charge.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "upsell.declined",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": {
      "id": "offer-1",
      "action": "declined"
    },
    "order": null,
    "payment": null,
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": null,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    },
    "parent_order_id": "test-order"
  }
}
```

##### upsell.payment_failed

Post-sell attempt fails, including an uncompleted challenge; no routing fallback.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "upsell.payment_failed",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": {
      "id": "offer-1",
      "action": "payment_failed"
    },
    "order": {
      "id": "test-upsell",
      "parent_order_id": "test-order",
      "status": "failed",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### flow.completed

Paid session ends at thank-you or expiry. Contains its initial order and every captured upsell.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "flow.completed",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": {
      "id": "test-order",
      "parent_order_id": null,
      "status": "captured",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    },
    "ended_by": "thank_you",
    "orders": [
      {
        "id": "test-order",
        "parent_order_id": null,
        "status": "captured",
        "items": [
          {
            "sku": "TEST",
            "name": "Test product",
            "quantity": 1,
            "price": 4999
          }
        ],
        "subtotal": 4999,
        "shipping": 0,
        "tax": 0,
        "discount": 0,
        "total": 4999,
        "currency": "USD"
      }
    ]
  }
}
```

##### order.refunded

Full or partial refund; data.amount is this refund’s amount, not lifetime refunds.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "order.refunded",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": {
      "id": "test-order",
      "parent_order_id": null,
      "status": "captured",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

##### order.chargeback

A chargeback is recorded; data.amount is the recorded chargeback amount.

```json
{
  "id": "evt_00000000-0000-4000-8000-000000000001",
  "type": "order.chargeback",
  "api_version": "2026-10-29",
  "created_at": "2026-10-29T00:00:00.000Z",
  "account_id": "acc_0000000000000000",
  "test": true,
  "data": {
    "checkout": {
      "id": "00000000-0000-4000-8000-000000000002",
      "type": "standalone",
      "name": "Webhook test"
    },
    "flow": null,
    "node": null,
    "order": {
      "id": "test-order",
      "parent_order_id": null,
      "status": "captured",
      "items": [
        {
          "sku": "TEST",
          "name": "Test product",
          "quantity": 1,
          "price": 4999
        }
      ],
      "subtotal": 4999,
      "shipping": 0,
      "tax": 0,
      "discount": 0,
      "total": 4999,
      "currency": "USD"
    },
    "payment": {
      "gateway_label": "Test gateway",
      "card_brand": "Visa",
      "last4": "4242"
    },
    "attribution": {
      "status": "none",
      "affid": null,
      "affiliate_name": null,
      "source_id": null,
      "extra": {}
    },
    "affiliate_cut": [],
    "amount": 4999,
    "currency": "USD",
    "customer": {
      "first_name": "Test",
      "last_name": "Customer",
      "email": "customer@example.invalid",
      "country": "US"
    }
  }
}
```

### Checkout integration: the fields of POST /v1/charge

Use this guide for a server-side checkout integration. Kontrol's native checkout already
sends the available billing address, phone, buyer context and server-priced basket.
An external caller must supply its own verified values. Keep API keys on
the server. The endpoint reference (Part 4) entry for `POST /v1/charge`
lists every parameter, validation rule, response and error; the table below covers the common card request.

#### Endpoint

```
POST https://api.kontrolcheckout.com/v1/charge
Authorization: Bearer <your API key>      (scope charges.write)
Content-Type: application/json
```

Send one order object, or a documented `orders` array for a batch. Results are returned
in a `results` array even for one order. Preserve `orderId` when reading or resuming an
existing operation; a timeout or pending authentication is not permission to submit a new sale.

#### Fields

| Field | Required | Format / example | Notes |
|---|---|---|---|
| `orderId` | ✅ | `"ORD-10293"` | Stable identifier for this operation, 1–128 characters. Reuse it when resolving a pending result. |
| `crm` | ✅ | `"nmi"` | The card-routing contract. The selected account may use NMI, Convesio or Stripe; this field does not choose the processor. Wallets use their separate session/token contracts. |
| `amount` | ✅ | `49.99` | Positive major-unit amount, at least 0.01 and no fractional cents. |
| `currency` | optional | `"USD"` | 3-letter ISO. Defaults to USD. |
| `ccnumber` | Conditional | `"4242424242424242"` | PAN for the ordinary card path; 12–19 characters, submit digits only. This example is a simulator card, not a live approval guarantee. Stripe modes have separate payment-method requirements. |
| `ccexp` | Conditional | `"1030"` | Expiry for the ordinary card path, **MMYY** (exactly 4 digits). Optional in the base schema; Stripe payment-method modes have their own requirements. |
| `cvv` | Conditional | `"123"` | Optional in the base schema; when supplied, 3–4 characters. The payment method/provider can require a fresh security code. |
| `firstName` | Optional schema; supply when collected | `"Aniyah"` | Up to 128 characters. |
| `lastName` | Optional schema; supply when collected | `"White"` | Up to 128 characters. |
| `email` | Optional schema; supply when collected | `"buyer@example.invalid"` | Valid email, up to 256 characters. |
| `phone` | Optional schema; supply when collected | `"+12025550147"` | Up to 32 characters; E.164 preferred. |
| `address1` | Optional schema; supply when collected | `"1 Test Street"` | Street address, up to 256 characters. |
| `city` | Optional schema; supply when collected | `"Los Angeles"` | Up to 128 characters. |
| `state` | Optional schema; supply when collected | `"CA"` | State/region, up to 64 characters. |
| `zip` | Optional schema; supply when collected | `"90012"` | Postal code, up to 32 characters. |
| `country` | Optional schema; supply when collected | `"US"` | Supply the actual ISO country code; the base schema accepts up to 64 characters. |
| `ipaddress` | recommended | `"203.0.113.7"` | Buyer's IP - improves approval rate + fraud scoring. |

Schema-optional does not mean that a checkout, authentication policy or gateway never
requires the field. Collect the data required by the selected payment path and send
the buyer's actual values.

#### Complete example

```json
{
  "orderId": "ORD-10293",
  "crm": "nmi",
  "amount": 49.99,
  "currency": "USD",
  "ccnumber": "4242424242424242",
  "ccexp": "1030",
  "cvv": "123",
  "firstName": "Aniyah",
  "lastName": "White",
  "email": "buyer@example.invalid",
  "phone": "+12025550147",
  "address1": "1 Test Street",
  "city": "Los Angeles",
  "state": "CA",
  "zip": "90012",
  "country": "US",
  "ipaddress": "203.0.113.7"
}
```

The card in this example is approved locally only when Kontrol's server simulator is
enabled. See *Test cards: checkout and flow simulation* in Part 2 for configuration, flow behavior and the boundary
between an application simulation and a real provider sandbox.

#### Return navigation and attribution

`checkoutReturnUrl` records the buyer's HTTPS destination (up to 16,384 characters);
`stripeReturnUrl` remains a compatible alias (up to 4,096 characters). These are not
arbitrary redirect instructions. The return handler checks persisted account, checkout,
store/cart or flow bindings, expiry and the allowed destination. Preserve the checkout's
signed query context; do not rebuild its URL from an untrusted host or query parameter.

Provider-facing technical return URLs use Kontrol's fixed API/CRM origin. Returning
through that endpoint only navigates the browser; provider verification and reconciliation
determine payment status. Merchant identity, descriptors and registered wallet domains
remain accurate and separate from this technical URL.

Pass supported UTM/click attribution with the original order. The optional transaction
attribution write runs after the new parent transaction commits. It does not block or
approve a payment, and replaying the same order must not overwrite attribution. A short
delay or missing analytics row is not a reason to repeat a charge.

For Shopify, install **both** current files from the [Shopify integration guide](https://app.kontrolcheckout.com/integration-guides/shopify).
For Medusa, preserve query parameters through locale and product redirects before reaching
Kontrol. Native cart/recovery adapters retain CMS product and variant identifiers alongside
the validated basket; do not convert external IDs into unrelated catalogue UUIDs.

#### Standalone receipt and recovery workers

Standalone receipt and recovery workers require their migrations and run on the elected API job leader when `BACKGROUND_JOBS_ENABLED` permits jobs. Local development leaves background jobs disabled.

Receipts use the order's pinned published receipt settings, a valid customer email and the account-owned enabled sender. Recovery requires an active checkout and configuration, an enabled channel in the current published settings, and the lead's pinned policy with an account-owned enabled template and provider. Both respect provider capacity; recovery also rechecks eligibility, suppression and send windows. Test sessions do not send. An uncertain provider acceptance is retained as unknown instead of being blindly retried.

Worker leadership and the operational jobs setting do not enable a product edition or
replace the merchant's receipt/recovery configuration. Do not add account enrollment or
release switches to this integration.

#### Notes

- **Use the canonical charge field names above.** Legacy export readers can recognize
  some address/phone aliases in stored payloads, but those are not equivalent gateway
  inputs. Send `phone`, `address1`, `city`, `state`, `zip` and `country` explicitly.
- The endpoint reference (Part 4) distinguishes validated payment fields, preserved attribution
  and basket metadata. Do not assume an extra JSON key is forwarded to every gateway.
- Adding these fields affects new requests; it does not reconstruct address or phone
  values missing from historical orders.
- Optional 3-DS passthrough fields (`cavv`, `eci`, `xid`, `cardholder_auth`,
  `three_ds_version`, `directory_server_id`) are accepted if you run 3-DS at checkout.

#### The checkout builder's money blocks (v3.9.17)

When the published checkout document carries an Upsell, a Discount box, a Checkbox or a Subscription product block, the
storefront's SERVER sends what it worked out for the order — from the published document and the database, never from the
browser. Each field is optional and **validated**: a malformed one is a `400` (unlike the attribution fields, these describe
money and consent, so a broken one is never silently dropped). They are stored with the transaction, as validated.

| Field | Format | Notes |
|---|---|---|
| `upsells` | `[{ "block_id", "product_id", "variant_id", "unit_cents", "quantity" }]` (≤ 20) | The lines the server priced for the rendering store (`unit_cents` integer, `quantity` 1–99). Include them in `products` too for the reporting. |
| `discount` | `{ "code", "amount_cents", "redemption_id" }` | The code the server validated, the discount it computed, the redemption it reserved (`reserve_discount_redemption`). |
| `consents` | `[{ "block_id", "purpose", "key", "checked", "text_hash" }]` (≤ 30) | `purpose` = `terms` · `marketing_email` · `marketing_sms` · `custom`; `text_hash` = sha256 hex of the text as rendered. |
| `subscription_optin` | `{ "block_id", "product_id", "text_hash", "consented_at" }` | `product_id` must be an **active** subscription product of the API key's account — otherwise `422 {"error":"subscription_optin_invalid"}` (not the account's, or deleted) or `422 {"error":"subscription_optin_inactive"}` (switched off), and **nothing is charged** (in a batch, no order is). |

On the sale's result, the subscription engine attaches the opted-in product (source `optin`) and none of the account's
auto-attach products; one subscription per customer still holds. A wallet sale has no card on file: an opt-in there attaches
nothing. The discount's redemption is the storefront's to move: `confirm_discount_redemption(id, transaction_id)` on
approval, `release_discount_redemption(id)` on decline (docs/EDITOR.md "Builder data"). The settle hook also confirms an
approved sale's redemption (idempotent), so a confirmation the storefront lost never undercounts the code's limits.


#### Friendlies (`fl`) and API-key permissions

The production base URL is `https://api.kontrolcheckout.com`. Optional JSON boolean `fl: true` on a sale (or each `orders[]` item) classifies the transaction as **Friendlies**, with a separate `source=friendlies` filter across reports. False/omitted preserves existing classification. Scopes are configured under API Keys → Permissions with Read/Write checkboxes; existing keys default to all scopes. `scopes: []` denies all, `null` grants all. Charging requires `charges.write`. See Part 1 for the full scope catalog and the endpoint reference (Part 4) for requests and responses.

#### PAAY authentication without waiting for the reserve

A PAAY double authentication creates two independent durable sessions. The primary authenticates the current purchase; the secondary may provide unused proof for a compatible future collection. The current purchase can proceed as soon as its primary proof is usable. It does not wait for the optional secondary to finish, and the payment gateway still determines approval.

For a returned `next.type: "method"`, POST the unchanged provider fields into a real hidden 10×10 browser iframe. Immediately call `POST /v1/3ds/sessions/:id/complete` with `{"stage":"method","methodCompleted":false}` to indicate that the iframe was submitted, then poll the same session. `false` does not claim successful fingerprinting. PAAY owns its Method callback, so a Kontrol-specific browser message is not required before polling. Actual primary bank challenges remain visible and follow the configured authentication policy.

For a single PAAY authentication, immediate Method delivery applies to callers that send both `browser` metadata and `threeDsChallenge: "return"`, as the checkout does. These callers can display and resume the browser step, so a silent Method or result poll is returned immediately even when inline Method wait is enabled. An actual issuer challenge still follows the configured policy.

Server-to-server callers that do not declare that browser capability keep their existing inline/skip/decline behavior. When inline Method wait is enabled, the server may perform one bounded read of the existing single authentication; it does not claim that a browser fingerprint started or completed. Any unresolved browser step then follows that caller's policy. IP address, user agent, storefront attribution or browser metadata alone do not opt an API caller into parked checkout handoff. Required authentication and liability-shift controls still take precedence over optional skip.

The charge result's `threeDs.backgroundAuthentications` and the session endpoints' top-level `backgroundAuthentications` contain optional sibling work. They include only the session ID, provider, status, Method/poll action and expiry. Start its Method concurrently with the primary. Keep secondary reads separate from charge submission: a late result must never submit, retry or change the current sale. Background methods already posted can finish after the authentication overlay closes; leaving the browser document can still interrupt fingerprinting. Server workers can read existing PAAY results but cannot substitute for browser work.

PAAY's **Optimize 3DS tokens** setting retains a sole usable proof only after both results have become terminal and authentication is optional. A usable primary with a still-pending sibling is used for the current sale. Once dispatched, the allocation does not change. Required authentication and liability-shift rules remain enforced, and a later stock claim still checks the original card, account, provider context, intended future amount/currency, expiry and one-time use.

**3DS timeout** in the PAAY integration accepts 5–120 whole seconds, default 45. The deadline begins when the primary is durably created; retries cannot restart it. Optional secondary work has its own lifetime and does not extend that deadline. An eligible timeout resumes the same order/session through the server, which can send a normal sale without 3DS when policy permits. It never turns a pending payment into an approval, bypasses a known issuer challenge or authorizes a fresh retry of an unknown bank result.

The two authentication attempts remain attributed once to their originating purchase. If a deferred secondary start later ends in a non-billable request error, the worker corrects only the originating purchase or rejection's factual authentication count. Reading or later consuming a saved proof creates no new authentication fee. A secondary success does not change the original transaction's recorded authentication or liability shift.

### Test cards: checkout and flow simulation

Kontrol's test-card simulator lets a buyer complete the application journey without sending a payment to a processor. It records an initial transaction marked `is_test`, follows the configured flow and displays its receipt. A simulated post-sell updates the test session's order summary without creating a real upsell charge.

This is different from the editor's **Preview walk**, which creates no buyer session or transaction, and from a payment provider's sandbox, which exercises that provider's test API.

#### Configuration and cards

The API service must have `TEST_CARD_ENABLED=true`. The default is `false`. `TEST_CARD_APPROVE` and `TEST_CARD_DECLINE` can override the default numbers; confirm the active configuration before testing. A card number by itself does not enable the simulator or change a live gateway into a sandbox.

| Default number | Simulator result |
| --- | --- |
| `4242 4242 4242 4242` | Approved initial test transaction; continue through the configured post-sell and Thank-you pages. |
| `4000 0000 0000 0002` | Declined initial test transaction; display the checkout's decline state. |

Use a future expiry, a validly formatted security code and synthetic contact/address data that satisfy the checkout's validation. Do not use an existing customer's cart, contact details or card.

The simulator runs after request validation and the configured blacklist check. A disabled/deleted store, invalid cart, invalid request or blacklist refusal does not become a successful test purchase.

#### Run a checkout and post-sell test

1. Open a fresh browser session. Add a product on the store, then enter its checkout. For attribution testing, start with explicit markers such as `utm_source=integration_test&utm_campaign=checkout_verification` and check that redirects preserve them.
2. Submit the approve card once. If the request is unresolved, inspect its existing status; do not generate another order just to retry the response.
3. If the published flow contains a post-sell, select an allowed product/variant and quantity. Confirm once, or decline to test that branch. Inspect the quoted amount before confirming.
4. Check the Thank-you page: original products, gifts and accepted test additions, their images, quantities, currency and recorded totals. Order bumps belong to the initial order; a post-sell appears as an additional order.
5. In Transactions, verify the initial row's **TEST** badge, final status and `TEST CARD (no gateway call)` identity. Check persisted attribution separately; browser query parameters alone do not prove that reporting attribution was saved.
6. Use a separate fresh cart for the decline card. The initial decline must not grant access to a paid post-sell or paid receipt.

#### What is and is not exercised

| Area | Simulator behavior |
| --- | --- |
| Store/cart entry, published layout, flow branching, quotes and receipts | Uses the application paths and owned synthetic session. |
| Initial transaction | Persisted with `is_test`; does not call a gateway. |
| Accepted post-sell | Recorded in the simulation ledger and receipt; no real payment intent, gateway dispatch or order-delivery effects. |
| 3DS, bank authorization, settlement and provider redirects | Not exercised. |
| Apple Pay, Google Pay and wire confirmation | Not exercised by entering a test card. |
| Paid-flow pixels and page-view events | Suppressed for simulation. They are not evidence of a real purchase conversion. |
| Exify/PlatformPay export, subscription attachment and rebilling | Exclude the initial test transaction. |
| Receipt/recovery delivery and real post-sell webhooks | Do not treat the simulated journey as a delivery test. |

Storefront analytics or other page requests before payment may still appear in a browser trace. Do not interpret them as a paid-flow pixel or as a processor call.

#### Record the result

Keep the tested CMS, published flow/page versions, test timestamps, observed request statuses, browser errors and receipt checks. Measure checkout rendering, payment submission, post-sell readiness and receipt readiness separately. State whether a result came from a browser observation, persisted test records, a local test or a provider sandbox.

A successful simulated flow does not prove a real provider authorization, 3DS challenge, wallet payment, refund or bank callback. Use that provider's configured sandbox and its supported test method for those checks; retain the same order/session and reconciliation rules.

### Stripe gateway

Stripe is available under **Gateways → Add gateway → Gateway type → Stripe**.
Choose one integration mode per gateway. To offer several modes, create separate gateways using keys from the same Stripe account and add them to the checkout's active ATRI.

| Mode | Customer experience | Payment API |
| --- | --- | --- |
| Server to server (S2S) | Card entry in Kontrol; bank authentication opens when required | PaymentIntents |
| Embedded Checkout | Stripe's secure form opens inside the Kontrol checkout | Checkout Session, `ui_mode=embedded` |
| Hosted Payment Page | Customer goes to Stripe, then returns to the same Kontrol checkout | Checkout Session, `ui_mode=hosted` |

#### Merchant setup

1. In your Stripe Dashboard, select a sandbox for testing or your live account for production. Copy the publishable key and secret key from **Developers → API keys**.
2. In the Kontrol gateway, enter the publishable key in **Publishable key** and the secret key in **Secret key**. Both must belong to the same account and environment (`test` or `live`). A restricted key needs access to PaymentIntents, Checkout Sessions and Refunds, including reads/search for reconciliation. Keep secret keys on the server.
3. Select the integration mode, complete the gateway's processor, bank and company settings, save it, activate it and include it in the active ATRI used by the checkout.
4. Optional but recommended: create a Stripe webhook destination pointing to `https://api.kontrolcheckout.com/v1/stripe/webhooks/<gateway-id>`. Subscribe to `payment_intent.succeeded`, `payment_intent.payment_failed`, `payment_intent.canceled`, `checkout.session.completed`, `checkout.session.expired`, `checkout.session.async_payment_succeeded` and `checkout.session.async_payment_failed`. Paste its `whsec_...` signing secret in the gateway. Each gateway has its own destination/signing secret.
5. Test a purchase and refund before using live keys. Kontrol's internal test-card mode simulates a transaction and does not test Stripe: use a real Stripe sandbox gateway with internal simulation disabled.

**S2S card access:** Stripe accepts account-scoped PaymentMethods without sending raw card numbers. The built-in Kontrol card form sends card data server to server; Stripe must enable raw card data API access on the merchant account for this variant. Without that access choose Embedded or Hosted. See [Stripe's raw card API access requirements](https://support.stripe.com/questions/enabling-access-to-raw-card-data-apis).

Stripe uses its native bank authentication. External PAAY or stored 3DS proofs are not imported by this adapter; a request carrying such a proof is rejected before sending a payment, rather than reporting an authentication that Stripe did not apply. Use Stripe's native flow on its checkout route.

#### How the checkout completes

Kontrol calculates the amount from its signed cart, discovers the active gateway modes server-side and shows only the compatible options. Browser modes send no card number to Kontrol. Stripe receives one order line with the exact server-calculated total; the original basket stays in Kontrol. Adaptive Pricing is disabled so the settlement currency and amount match the order.

The payment begins with a durable transaction reference and deterministic Stripe idempotency key. Open sessions, 3DS challenges, processing payments and lost network responses remain **unconfirmed**. They cannot trigger a second gateway charge. Closing the secure form or returning from Stripe does not imply failure or success.

Kontrol keeps a recovery marker and polls its authenticated status endpoint. Its settlement worker independently retrieves the Stripe object, verifies transaction metadata, currency, amount and captured/paid state, then completes the existing order workflow. Webhooks only wake this verification; their payload never directly approves a sale. The polling worker also works without a webhook. Monthly capacity remains reserved until a terminal result is verified. Sessions expire after 30 minutes.

Stripe receives a technical return URL on Kontrol's fixed API/CRM origin. That handler validates the saved transaction or flow binding and resumes the owned buyer destination; it does not accept an arbitrary return origin or treat a redirect as payment approval. A confirmed transaction appears in the normal sales/reporting and refund flows. Embedded/Hosted collect the card inside Stripe, so Kontrol does not acquire a reusable raw card for its existing rebill engine. This integration creates one-time payments, not Stripe Billing subscriptions.

#### Direct API usage

Use the usual `POST /v1/charge` contract and an API key of the account with `charges.write`. `crm` remains `nmi`, the existing card-routing channel; the gateway type selects Stripe.

S2S accepts either the usual card fields or `stripePaymentMethod: "pm_..."`. The PaymentMethod must belong to the selected Stripe account. Use an ATRI containing that account's S2S gateway. Supply `checkoutReturnUrl` for buyer navigation after authentication; `stripeReturnUrl` remains a compatible alias. The destination must pass the persisted account and checkout/store/cart or flow checks. It is kept separate from the technical URL sent to Stripe.

For browser modes, omit card fields and send `stripeMode: "embedded"` or `"hosted"`, plus an HTTPS `checkoutReturnUrl` (or the compatible `stripeReturnUrl` alias). Preserve the signed query context of an owned checkout rather than constructing a destination from request headers. A pending response contains a `stripe` action with the publishable key and the Checkout client secret or hosted URL. Treat client secrets as short-lived payment credentials; never put them in URLs or logs. Mount Embedded using Stripe.js or redirect to the hosted URL. S2S `requires_action` responses use Stripe.js `handleNextAction`.

Poll `GET /v1/charge/orders/<order-id>` with the same account API key. A `state: "complete"` result is terminal. Never resubmit a new charge merely because the browser closed or a request timed out. The hosted URL and client secret may be returned only to the authorized checkout session/account.

#### Refunds

Use Kontrol's usual refund action/API. Stripe refunds use the original PaymentIntent and encrypted account credential snapshot. Amounts are bounded by the refundable balance. A confirmed `succeeded` refund books the refund; an ambiguous result reserves the balance and cannot be dispatched again automatically. Resolve an unresolved operation against its original Stripe refund, rather than creating another one.

#### Verification and references

On 2026-10-30, real Stripe sandbox transactions for **USD 2.99** were confirmed via server retrieval in all three modes: S2S with `pm_card_visa`, Embedded completed in the browser, and Hosted completed in the browser. The S2S refund was confirmed. Raw PAN access was refused by the anonymous sandbox, so the S2S proof uses Stripe's test PaymentMethod; it is not proof that raw PAN access is enabled for a merchant.

Automated tests cover mode isolation, pending-payment recovery, exact amount/currency/identity checks, repeated settlement, callback retry, expiration, signature verification and uncertain network outcomes.

- [PaymentIntents](https://docs.stripe.com/api/payment_intents/create)
- [Checkout Sessions](https://docs.stripe.com/api/checkout/sessions/create)
- [Embedded Checkout](https://docs.stripe.com/payments/accept-a-payment?payment-ui=checkout&ui=embedded-page)
- [Stripe-hosted Checkout](https://docs.stripe.com/payments/accept-a-payment?payment-ui=checkout&ui=stripe-hosted)
- [Webhooks](https://docs.stripe.com/webhooks)
- [Test cards and authentication](https://docs.stripe.com/testing)

The adapter pins API version `2025-06-30.basil`; changing the merchant Dashboard default does not change this wire contract.

### Product description matching

A charge can be described to the gateway as a basket of products instead of one generic `"Online Order"` line. This has no endpoint of its own: it happens inside the charge, so an agent has to understand it to maintain it.

#### The chain

```
charge -> the MID chosen FOR THIS ATTEMPT -> that MID's bank page
       -> the storefront catalog for that host -> prices summing EXACTLY to the amount
       -> Level III line items sent to the gateway
```

Four things about it are load-bearing:

- **The MID's bank page, never the customer's shop.** `storefront_url` on a transaction is where the charge came from; it is analytics only and is never consulted here.
- **Re-resolved per attempt.** A cascade walks several MIDs and each can bill under a different bank page, so attempt 2 gets its own basket. Never assume one basket per order.
- **The products are the catalog's.** They come from the storefront catalog and are matched on price alone. They never derive from what the customer bought: that basket lives in the transaction's products for reporting and never reaches a gateway.
- **Exact or nothing.** A basket is sent only when the prices sum to the charge to the cent. No remainder line, no rounding, no padding: a Level III block whose lines do not add up can be rejected by the gateway.

#### It can never block a charge

On every unremarkable path (matching off for the MID, no bank page, no catalog for that host, no set of prices summing to the amount) the charge goes out exactly as it does without this feature, generic line and all. A database failure during the lookup costs a description, never a sale. Treat "no basket" as normal, not as an error.

#### Turning it on

| step | call |
|---|---|
| create the shop | `POST /v1/storefronts` `{host}`: the host only, no scheme or path |
| fill its catalog | `PUT /v1/storefronts/:id/products`: replaces the whole list |
| enable per MID | `PATCH /v1/accounts/:id` `{productMatchingEnabled: true}` |

Catalogs are keyed on the host alone and are not per account: every MID whose bank page resolves to that host bills from the same price list. Wallet charges (Apple Pay, Google Pay) follow a separate platform-wide switch, off by default: enabling matching on one MID does not affect wallets.

#### Why some amounts never match

When every price in a catalog ends in `.99`, the cents of any total are decided by how many items are in the basket: 1 item ends in `.99`, 2 in `.98`, 3 in `.97`, 4 in `.96`. So `$157.98` needs exactly two items, and if no pair of the catalog sums to it, no basket exists at any item count. A round amount like `$70.00` is unreachable from an all-`.99` ladder. When an amount does not match, the fix is a missing price point in the catalog, not a bug.

To see what an attempt actually sent, read `request_sent` on the attempt (`GET /v1/transactions/:id/details`): NMI carries it as flat `item_*_N` parameters, Convesio as a `lineItems` array.

### Headless checkout: the embedded iframe and your own front end

The checkout runtime that Kontrol's own storefront uses is open to your server: Part 4, Headless checkout, documents every call. Two ways to use it:

1. the embedded (iframe) checkout: your server opens a session, your page shows Kontrol's card form in an iframe;
2. your own front end: your server, serving the checkout's domain, makes the same runtime calls as the Kontrol storefront.

Rules for both:

- Authenticate every call with an API key of the checkout's account holding `charges.write`. The key stays on your server: never in HTML, browser JavaScript or a URL. Tenancy is the checkout's account: a checkout of another account answers `404`.
- Every call names the checkout (`checkoutId`) and its exact serving domain (`domain`, lower case, verified and published for that checkout). A domain that does not serve the checkout answers `404`.
- The buyer's session is an HttpOnly cookie (`__Host-kontrol_flow`) that the entry call issues. Your server forwards the buyer's `Cookie` header on each later call and applies the `Set-Cookie` values the entry returns. Browser-supplied account, order or price identifiers are never trusted: the session decides.
- Opening a session, entering, quoting or preparing an order never charges. Only the payment submission does, once per order.

#### The embedded (iframe) checkout, end to end

1. Create the checkout. `POST /v1/checkouts/standalone` with `settings.presentation` = `{"mode": "iframe", "allowedOrigins": ["https://merchant.example"]}` (exact HTTPS origins of the pages that will embed it, at most 20), its default basket in `settings.parameters` (every value a string: `product1_name`, `product1_price` in cents, `product1_quantity`, or `product1_id` for a catalog product), currency, payment route (`atriId`), domain and slug. Then publish: `POST /v1/checkouts/standalone/:id/publish` with `{baseRevision, documentRevision}` (read both from `GET /v1/checkouts/standalone/:id`), and enable it: `POST /v1/checkouts/standalone/:id/active` with `{"active": true}`. The iframe is for one-time card payments on a route that accepts native card submission; subscription offers, order bumps and pre-authorization offers need a full checkout.
2. Open a session from your server, for the buyer and cart you have validated: `POST /v5/standalone/iframe-session` with `{checkoutId, domain, slug, parentOrigin, rawQuery, prefill}`. `parentOrigin` must be one of `allowedOrigins`; `rawQuery` holds supported checkout link parameters without the leading `?` (an empty string for the defaults); `prefill` is required and carries `email, first_name, last_name, address, city, postal_code, shipping_country, phone (E.164)`, plus `state` when the country is US, CA or FR. The answer is `{checkoutId, url, origin, expiresAt}`; the session lasts 30 minutes and its URL is private (no analytics, no logs).
3. Embed `url` in an iframe (`allow="payment"`) and listen to `message` events whose `event.origin` is `origin` and whose `event.source` is the frame: `kontrol:iframe:ready`, `kontrol:iframe:resize` (`height`), `kontrol:iframe:payment` (`status`, `orderId`, `amountMinor`, `currency`, `isTest`). `status: "pending"` is not an approval. Card numbers, expiry and CVV are typed inside the frame only.
4. Verify on your server before you fulfil: no browser message authorizes fulfilment by itself. Read the order: `GET /v1/transactions?q=<orderId>` (the quick search matches the order id) and `GET /v1/transactions/:id/details` for the full record, or receive the signed `order.paid` webhook of the checkout (Part 4, Outbound webhooks and services > Checkout webhooks).
5. Errors of the session call: `401` the key, `403` the key lacks `charges.write` (`code: "insufficient_scope"`, checked before the buyer fields) or the parent origin is not allowed, `404` checkout, account, publication or domain, `422` missing customer fields or an offer the iframe cannot show. Never open a new payment because a response was lost: read the order first.

#### Your own front end

Your server serves the checkout's domain and drives the runtime; the buyer's browser only talks to your server.

1. Enter. For a standalone checkout link: `POST /v5/standalone/entry` with `{checkoutId, domain, slug, rawQuery, prefill?}`; it validates the link parameters and their signature, pins the configuration in a server session and returns the clean location and the `Set-Cookie` values to apply before you redirect. For a store cart: `POST /v5/store/entry` with `{checkoutId, storeId, domain, cartToken, checkoutPath, rawQuery}`; `POST /v5/store/session` tells whether the buyer's cookie already names a session of this checkout.
2. Render. `POST /v5/standalone/session` returns the pinned render data of the session (catalogue, prices, settings, whether a flow may store the card). `POST /v5/payment-methods` lists the payment methods the session can use for a currency. Record the contact form with `POST /v5/standalone/lead` and checkout activity with `POST /v5/standalone/activity` (both feed reports and cart recovery).
3. Prepare the order. `POST /v5/checkout/order` creates the canonical order of the session from your quote (`row`, `commerce`), then `POST /v5/checkout/order/reserve` returns the one payment identity (`orderId`) of the session: the same id on every replay.
4. Pay once. `POST /v5/checkout/order/dispatch` with `{orderId, channel}` claims the single payment: `claimed: true` means you may submit it; `claimed: false` means it was already submitted, so only observe it. The card payment itself is `POST /v1/charge` with that `orderId`, the prepared amount and currency, the buyer's cookie and the headers `X-Kontrol-Checkout` and `X-Kontrol-Domain` (Payments > Charging). Before re-submitting after a 3-D Secure challenge, check the order with `POST /v5/checkout/order/verify`.
5. Wallet and wire. `POST /v5/standalone/wallet-status` reads the outcome of a wallet payment of the session. `POST /v5/wire/start` returns the transfer instructions for the prepared order (the same on every call); `POST /v5/wire/check` reads its status. A buyer's "I paid" click never settles a wire.
6. After the payment. `POST /v5/checkout/order/recover` reads the session's order without dispatching anything (use it after a reload or a lost response). `POST /v5/standalone/completion` returns the thank-you data of a captured order. When a flow follows the checkout, `GET /v5/flow/:checkoutId` (header `x-v5-domain`) returns the current page, `POST /v5/flow/:checkoutId/quote` prices offer choices, `POST /v5/flow/:checkoutId/actions` accepts, declines or continues (accepting a signed quote is the only new payment), and `POST /v5/flow/:checkoutId/events` records the pages actually shown.

Replays are safe by design: reserve returns the same id, dispatch is claimed once, recover and the status reads never charge. Never create a new order because a response was lost or a redirect failed.

### Operations, reporting and current behavior

Source-reviewed on 2026-10-22. Base URL: `https://api.kontrolcheckout.com`. An external agent is an ordinary REST client; there is no separate agent API. Use the endpoint index (Part 3) to find every method/path and the endpoint reference (Part 4) for parameters, examples and errors.

Commerce access, checkout diagnostics and recovery updates reviewed on **2026-11-11**. The dated reporting update and earlier endpoint contracts below retain their own review dates. See *Commerce workflows* in Part 2 for current creation, publishing, assignment and recovery examples.

#### Choose the correct credential and scope

Use an API key of the account, sent as `Authorization: Bearer <key>`, for documented key-enabled `/v1/*` operations. Category scopes distinguish read and write; read permission does not authorize a mutation. `scopes: null` is the legacy unrestricted catalog; an empty array grants nothing. Human-session-only and platform-only operations retain their separate restrictions; a key does not authorize every route beginning with `/v1`. Roles, account ownership, integration activation and endpoint-specific checks still apply. A key only sees its own account (a foreign id answers 404) and never becomes a platform super-admin.

Affiliates work in their own affiliate workspace; it is not part of the client API, and no API-key scope grants access to an affiliate's assets.

Partner refund/transaction routes additionally accept an API key of the account with explicit non-null scopes, sent as `Authorization: Bearer`. The legacy `X-Refund-Key` remains a separate option. A scoped account key is not a refund test key: it can perform live refunds. Do not send both credential types. Refer to *Refunds, disputes and the blacklist* in Part 2 for test-mode and legacy blacklist/scrub targeting limits.

Examples below are Bash with curl and jq. Populate credentials from your secret manager. UUID placeholders must come from discovery calls; never infer a production ID from a display name.

```bash
export API='https://api.kontrolcheckout.com'
curl --fail-with-body -sS -H "Authorization: Bearer $KONTROL_API_KEY" \
  "$API/v1/transactions?limit=20&offset=0&count=0&source=sale,recovery,rebill,friendlies"
```

#### Transactions, dates and Friendlies

`GET /v1/transactions` returns `{transactions,total,totalExact?}`. Amounts in `amount_cents` are integer minor units; preserve each row's currency. Do not assume every route uses cents: partner refund `amount` is a decimal major-unit amount.

- `count=0` returns `total:null` and skips the total count. Use it for a recent-orders widget.
- When `totalExact:false`, `total` is a **lower bound**. The count is capped at 10,001 and can advance with deep pagination. Do not label it as exact or stop exporting when an earlier lower bound is reached.
- An exact answer omits `totalExact`; a short page supplies its exact end. Preserve sort, dates and filters while paging. For a complete download use the documented export route and its streaming/job behavior.
- Dashboard Last orders follows the selected UTC `from`/`to`, shows 20 rows, and refreshes every 30 seconds. All uses `source=sale,recovery,rebill,friendlies`. `straight` means sale+recovery; `subscription` means rebill; `friendlies` means only Friendlies. Pre-auth verification attempts are not sales in this list.
- Friendlies is an opt-in integration. The server hides these transactions when it is inactive. A real JSON boolean `raw_payload.fl:true` classifies Friendlies; a pre-auth channel remains pre-auth. Do not infer the source from a label or gateway name.

```json
{"transactions":[],"total":null}
```

For a custom reporting period, convert the chosen calendar days using the account's IANA timezone, then keep that same timezone and interval across metrics, lists and drill-downs. Do not reuse a cached result from another range, side, account or filter set.

##### Approval rates and money

The main dashboard `totals` and standard financial KPIs exclude Friendlies. Its separate `friendlies` object exposes sales, attempts, amount, costs, currency and missing-cost information when active. Missing costs or mixed currencies may yield `null`; null is not zero.

The inclusive approval-rate annotation uses:

```text
(totals.approved + split.friendlies.approved)
  / (totals.completed + split.friendlies.completed)
```

Return no percentage when the denominator is zero or the Friendlies completed count is unavailable. Do not average percentages and do not use `friendlies.sales / friendlies.attempts` as a substitute. Pending and duplicate transactions are outside the completed denominator. A source-breakdown row can display its own row approval rate while the main KPI excludes Friendlies.

`subs.activeSubs` is the current active-membership count, not merely the number created within the selected period. Keep it separate from new/lost subscriptions.

#### Schedules: status, counts and exact transaction drill-downs

Discover schedules through `GET /v1/subscription/schedules`. Read a selected schedule through `GET /v1/subscription/schedules/:id`.

- `transactionTotal` is the count of distinct linked transactions for the schedule, including its children. It is different from subscription/entry counts; a scheduled or blocked entry may have no transaction.
- An active job or processing work keeps a running schedule in Processing. Partial describes a finished/reopened day with remaining work; it is not a payment result. Read `activeJob`, `counts`, `nextDue`, `overdue`, `stop` and schedule status together.
- A redistribution message is a scheduling/audit event. It does not by itself prove that a payment ran or succeeded. Follow the destination entry and actual transaction.
- Changing a displayed processor label is not a routing instruction. Resolve account-owned ATRI/MID IDs and inspect the selected schedule/entry override before modifying routes.

```bash
curl --fail-with-body -sS -H "Authorization: Bearer $KONTROL_API_KEY" \
  "$API/v1/subscription/schedules/$SCHEDULE_ID/transactions?limit=50&offset=0"
```

Expected shape: `{rows:[...],total:123}`. Rows include transaction IDs, amounts/currencies, status, card brand/last four, gateway identity and decline reason. `limit` is 1–200; offset is zero-based. Only the account's schedule is accessible.

To reproduce an Analytics cell, send `segment` and its exact `key` **together**, plus optional `status=approved|declined|completed`. Dimensions include subscription, cycle, price_point, initial_value, hour, mid, category, mcc, acquirer, processor, company, issuer, card_brand, card_type, card_level, bin, traffic, store, product, geo, device, os and decline_category. For `segment=subscription`, pass the row's UUID `ref` when available. A decline `reason` is a separate filter and cannot be combined with segment/key. Encode special characters and preserve sentinel keys such as `(no gateway)` rather than fabricating a MID ID.

```bash
curl --fail-with-body -sS -G -H "Authorization: Bearer $KONTROL_API_KEY" \
  "$API/v1/subscription/schedules/$SCHEDULE_ID/transactions" \
  --data-urlencode 'segment=card_brand' --data-urlencode 'key=Visa' \
  --data-urlencode 'status=declined' --data-urlencode 'limit=50'
```

Foreign schedule: 404. Invalid combinations/unknown parameters: 400. A transaction UUID can then be read through `GET /v1/transactions/:id/details`; use returned gateway IDs for entity links.

##### Force bill with drip feed

`POST /v1/subscription/schedules/:id/jobs` accepts `dripDelaySeconds` as an integer from 0 to 86,400. Zero preserves normal dispatch; positive values serialize dispatch and persist the next dispatch time across pauses/restarts. `atriId` and `midId` are mutually exclusive. An eligible selected MID still follows card capability, cap and routing rules.

This example is a **test-mode sample**, not permission to force-bill live customers:

```json
{"kind":"sample","sampleSize":5,"testMode":true,"dripDelaySeconds":10}
```

The response contains `job`; monitor that job rather than posting repeatedly. Read the full subscription endpoint reference before bulk price or route edits: the dashboard's comma-separated price input is UI syntax, not a universal REST payload format.

#### Long operations and recovery

Use each family's documented job endpoints. Report jobs, creative jobs, subscription jobs and transaction bulk jobs have different status vocabularies and response shapes; do not apply one universal poller schema.

For account reports, `POST /v1/metrics/jobs` with `{kind,query,requestId}` returns HTTP 202 `{jobId,job}` after admission commits. A stable UUID requestId identifies the same attempt. Poll `GET /v1/metrics/jobs/:jobId`; fetch its result endpoint only when ready. `job.progress.completed/total` reports work units, not necessarily transaction rows. `recalculateRequired:true` / `resultState:"obsolete"` means the saved result must be recalculated, not presented as current. Availability flags can return 503.

```json
{"kind":"main","query":{"from":"2026-10-20T20:00:00.000Z","to":"2026-10-21T19:59:59.999Z","tz":"Asia/Dubai"},"requestId":"11111111-1111-4111-8111-111111111111"}
```

Use bounded polling/backoff. A network interruption is not proof that a write failed. Read the operation/job/status first; reuse its idempotency token when documented. A 400 needs corrected parameters; a 401/403 needs corrected authentication/authorization; 409 requires conflict reconciliation. Respect Retry-After on 429/503 when present. Never invent a successful result or an artificial progress percentage.

#### Store, checkout and AI workflows

*Build stores, product pages and checkouts* in Part 2 covers product creation, product-page content, availability across stores, checkout assignment, draft revisions and publishing. *Creative integrations* in Part 2 covers text/image/video jobs and asset reuse. Review generated assets and claims before publishing. A completed creative job does not automatically create or publish a product.

V5 also supports autonomous saved offer links (see *Standalone checkouts and saved offer links* in Part 2), without a connected store or catalogue product. The published checkout remains a reusable template; each link pins its own offer, configuration and pixel revision. Incoming acquisition parameters are captured at entry. Saved-link creator attribution cannot be replaced by a visitor's query, and an existing order/session is not reassigned when a link is edited. Select existing owner-safe 3DS/email integration references; do not put their credentials in public parameters.

Store assignment now accepts either `{checkoutId:UUID|null}` or `{flowId:UUID}` at `POST /v1/checkouts/:shopId/checkout`. New A/B tests belong inside a published flow; the former checkout A/B creation/update routes return 410. A direct checkout keeps its default confirmation, while a flow can select a published builder Thank-you page. See *Commerce workflows* in Part 2 for exact JSON and prerequisites.

Use *Account agreements* in Part 2 for the separate legal-document lifecycle. Provider pre-signing never substitutes for client acceptance. The Statement tab currently has no statement-generation API.

##### Diagnose checkout availability and payment returns

Archived stores stop public serving and new checkout/flow/payment admission. Historical payment records and reconciliation remain available; deleting a store is not a refund or cancellation of an already dispatched payment. Recheck account-owned store state instead of assigning a replacement route or retrying a stale payment. The storefront's `/internal/store-availability` read has its own per-minute rate-limit budget; it is an authenticated service endpoint, not a public merchant discovery API. Respect 429/503 responses rather than disabling availability checks.

Provider browser returns use a signed reference on the API's canonical origin. They resume only a permitted persisted checkout, flow or wallet destination, and cannot establish payment approval. Diagnose the existing transaction/session status after a return or lost response; never replay a charge because a redirect failed. See *Technical payment returns* in *Commerce workflows* (Part 2) for the distinction between technical URLs and required merchant/provider identity.

Transaction campaign attribution is a separate optional write after the new parent transaction commits. Compare entry markers, order/session/context and the transaction's attribution before diagnosing missing UTM data. An attribution failure does not fail an otherwise approved payment, and retrying the same claim does not replace attribution. Reserved test-card flows have persisted test classification and simulated upsell display records; they do not prove real provider, 3DS, wallet, fulfillment or advertising delivery. Use the store-to-flow verification checklist in *Commerce workflows* (Part 2).

##### Diagnose cart recovery without duplicating sends

Start with `GET /v1/recovery/health`, then the account's `/v1/recovery/carts`, `/v1/recovery/carts/:cart_token/details` and `/v1/recovery/sends` reads. The endpoint reference (Part 4) defines each filter, response and scope. These resources describe recovery state; they are not payment-retry endpoints.

- Due work is scanned per account and channel. A bounded pass advances only over work actually handled and continues on a later tick; `incomplete` does not mean failed or fully processed. Empty account-wrap work no longer consumes a tick.
- `skipped_not_yet` and quiet-hour waits can schedule a per-channel next attempt. These internal timestamps defer eligibility; they are not terminal states or merchant-write scheduling fields. The worker bounds a saved wait to one minute through 24 hours and reevaluates eligibility when due. A deferred cart is not evidence that the sender stopped.
- The configured late-touch grace applies to every touch, not just the first. Quiet hours, opt-outs, bounce/suppression, contact reservations and paid-cart checks still apply. The `late_touch_grace` counter replaced `first_touch_grace`; do not combine them as identical historical populations.
- Paid carts are excluded before the candidate-page limit and checked again before a send is claimed. Repair also expires still-live recovery links for paid carts, including old approved orders. Missing a recent notification does not make a paid cart eligible again.
- A contact reservation, unknown transport result or incomplete pass is not permission to create another send. Read the durable send result and its notification status first; use only the documented retry operation for the specific failed stage.


#### Reporting axes update (2026-10-28)

See *Reporting views and attribution* in Part 2 for the report ownership matrix, new breakdowns, parameters, response fields, examples and interpretation rules. The endpoint reference (Part 4) contains the expanded contracts.

#### V5 attribution, money and delivery (2026-10-30)

- **No store and No affiliate are different dimensions.** No store identifies a canonical standalone order. No affiliate means no attributed affiliate; it does not mean that an order was standalone. Do not infer either from a blank URL, current checkout owner or current affiliate assignment. Keep the exact unified filter keys and response identities documented in the endpoint reference.
- **Use captured facts for revenue.** An initial order and an accepted post-sell capture are separate payment facts. A selected multi-offer basket has one capture containing all selected lines. Declines and uncertain outcomes are not sales; transaction inventories can include genuine declines without increasing captured revenue. Preserve each row's currency and integer minor-unit fields. Do not divide every monetary field by 100 or mix decimal major-unit refund inputs with minor-unit reports.
- **Keep post-sell cohorts and accounting dates separate.** `/v1/metrics/postsells` observes the selected initial paid-order cohort through `window.asOf`, while event revenue follows actual capture/refund/chargeback dates. Its page cohorts overlap. Captured AOV includes shipping and tax; free additions are not paid conversions; pending/unknown outcomes are not automatically retryable. Pre-intent rejected requests are absent from its confirmation count, so consult sanitized flow-action logs when zero attempts conflict with a buyer report. Never sum different currencies or equate the legacy dispatcher CRM with the actual provider.
- **Cuts are a separate immutable ledger.** Percent cuts apply to eligible captured initial/upsell amounts including shipping and excluding tax. Fixed cuts apply once to the eligible initial capture in the configured supported account currency. Rebills, tests, declines and unconfirmed payments do not earn a cut. Partial refunds reverse cuts cumulatively; replay cannot duplicate the reversal. Chargeback corrections are signed ledger events, not another new sale. Do not sum incompatible currencies or infer an exchange rate.
- **Affiliates is an affiliate/currency report.** `GET /v1/affiliates/report` requires the documented date range and supports the unified filters. The native report has one affiliate view; older API `groupBy`/daily compatibility data does not imply additional current UI tabs. Captured revenue uses capture dates; transactions and refund/chargeback incidence use their documented creation-date cohorts; refund and cut movements use their event dates. Use the affiliate reporting definitions in *Affiliates* (Part 2) rather than dividing unlike populations or averaging rates. Do not infer visitor conversion from transaction counts.
- **Recover before retrying payments.** Post-sell acceptance uses the original stored credential, MID and provider binding, never a default ATRI fallback or a newly supplied card. Its immutable selected basket is server-priced. For timeouts, lost replies and concurrent clicks, read the existing flow/payment state and follow the documented action contract rather than creating another order or changing selected offers. A pending/unknown response is not a confirmed decline.
- **Delivery is not ingestion.** Saved-link browser pixels support seven documented networks; server Purchase delivery is limited to Meta, TikTok and Snapchat, the pinned link revision and its winning acquisition network. Tokens remain write-only. No version enrollment or account feature activation is required; owned active integrations, destination configuration, permissions and running operational workers still matter. Link webhooks additionally recheck current creator access and follow the originating link when a flow selects another checkout. Inspect actual delivery status/logs; a configured destination or completed local fixture is not proof of acceptance by a live advertising network or payment processor.

For operational endpoint examples, lifecycle/CAS errors and own-link webhook routes, see *Commerce workflows*, *Standalone checkouts and saved offer links*, *Pages and flows*, *Affiliates* and *Checkout webhooks* in Part 2. The historical `v5` segment in addresses such as `/v1/v5/flows` is a stable API contract, not a feature switch. Publication, owned integrations, access checks and operational worker readiness remain separate requirements; a visible UI does not establish live payment or delivery readiness.

### Reporting

Read-only access to everything the dashboard displays — transactions and the reports —
over an **API key of your account** with the read scope each endpoint needs
(`transactions.read` for the transaction list, `reports.read` for the reports).

Built for automation: agents, scripts, BI. It calls the *same* modules the dashboard calls,
so matching account, period, filters, integration visibility and calculation freshness should produce matching figures. Cached results from different windows are not comparable.

**Base URL** `https://api.kontrolcheckout.com`

```
Authorization: Bearer <YOUR_API_KEY>
```

The key resolves to its account. Every response is restricted to that account's data — and
to *all* of its keys, so a report matches the UI even when traffic is split across several.

> **Read-only by design.** Charging, refunds and chargebacks keep their own idempotent,
> audited endpoints (`/v1/charge`, `/v1/refund`). There is deliberately no second way to
> move money.

---

#### Current reporting contracts (2026-10-22)

See *Operations, reporting and current behavior* in Part 2 for the current bounded transaction-count contract (`total:null` with `count=0`, lower bounds with `totalExact:false`), Friendlies visibility and inclusive approval-rate calculation, current `subs.activeSubs`, schedule transaction drill-downs and report-job recovery. Last orders All includes Friendlies when the integration is active; the standard financial KPI totals still exclude them.

Use the endpoint index (Part 3) and the endpoint reference (Part 4) for the exact parameters accepted by each operation. The range and filter descriptions below concern report readers, not every API endpoint.

#### The time window

The report readers described here accept an explicit range or a trailing window:

| param | meaning |
|---|---|
| `from`, `to` | ISO-8601 instant, e.g. `2026-08-01T00:00:00Z`, or a bare day `YYYY-MM-DD` — v3.9.15: a day is read in `tz` (UTC when `tz` is absent), `from` its first instant, `to` its last; `to` before `from` is a **400** |
| `hours` | trailing window when `from`/`to` are omitted (default `24`, max `8760`) |
| `tz` | IANA zone for hour/day bucketing and bare days, e.g. `America/New_York` — an unknown zone is a **400** |

---

#### Filters

**The parameter names are identical to the dashboard's.** Copy the query string out of a
`/transactions` URL and it works here unchanged. All are optional, all accept a
comma-separated list (`brand=Visa,Amex`; a value holding a comma travels double-quoted,
`issuer="JPMORGAN CHASE BANK, N.A."`).

**v3.9.15 — one catalog, every key on every endpoint, strictly.** The four `/v1/reports/*`
endpoints accept the dashboard's whole filter catalog (the table below and the keys after it —
the full list is the *Filters — the unified catalog* section of the API reference) and apply
every key they accept, on every endpoint: `/transactions`, `/gateways` (see its
`unfilteredFields` below), `/products` and `/segments`. Nothing is silently dropped any more:

- an **unknown parameter** (a misspelt filter, a retired name) is a **400** —
  `{ "error": "Invalid request", "details": { "formErrors": ["Unrecognized key(s) in object: 'bogus'"], "fieldErrors": {} } }`;
- an **unknown value of a closed vocabulary** (`status`, `source`, `pass`, `population`, `refund`,
  `refunded`, `threeDs`, `pricePoint`, `ipType`, an id that is not a UUID, …) is a **400** naming it
  under `details.fieldErrors.<key>` — e.g. `{ "status": ["unknown value: approvd"] }`;
- `hour` without a valid `tz` is a 400 (`details.fieldErrors.tz`); a reversed pair (`amountMin` >
  `amountMax`, `to` before `from`) is a 400 naming its second key.

Open vocabularies (issuer, storefront, country, product…) stay free text: an unknown value narrows
to zero rows. Before v3.9.15 an unknown parameter was stripped and the call answered the
**unfiltered** figures — a script that relied on that now gets a 400 and must drop the parameter.

| param | values |
|---|---|
| `status` | `approved`, `declined`, `error`, `failed` (declined+error — the decline definition, v3.9 §1), `completed`, `chargeback`, `rdr`, `ethoca` |
| `source` | `sale`, `recovery`, `rebill`, `pre-auth`, `friendlies`; aliases `straight` = sale + recovery and `subscription` = rebill. Comma-separated values are ORed. Friendlies requires the active integration. Pre-auth verification is a separate source, not a merchandise sale. Use an explicit source set when reproducing a dashboard widget. |
| `pass` | `initial`, `cascade` — a cascade is a cascade-pass attempt that was not skipped (v3.9.9) |
| `atri` | ATRI (trip) ids — the order's own, or a pool one of its (non-skipped) attempts reached |
| `accountId` | MID ids, or `none` — a charge that ended on no gateway (no MID, no wallet provider; v3.9.9) |
| `gatewayType` | `nmi`, `convesio`, … |
| `category` | category ids |
| `processor` | processor ids (`GET /v1/processors`) — the PROCESSOR behind the gateway: a card charge matches through its final MID, a wallet charge through its wallet provider. Applied on every `/v1/reports/…` endpoint (v3.9.15 — `/products` and `/segments` read it too; on `/gateways` it narrows `perMid` / `perWallet` / `noGateway`) |
| `acquiringBank` | acquiring-bank ids (`GET /v1/acquiring-banks`), resolved the same way — final MID, else wallet provider; same endpoints as `processor` |
| `company` | company ids (`GET /v1/companies`) — the legal entity the gateway is boarded under (v3.9.2 §0), resolved the same way — final MID, else wallet provider; same endpoints as `processor`. `processor`, `acquiringBank` and `company` also take `none`: a gateway without that reference, the reports' `(unset)` row (v3.9.9) |
| `brand` | `Visa`, `Mastercard`, `Amex`, `Discover`, `Apple Pay`, `Google Pay` — a wallet charge is its wallet, whatever card is behind it (v3.9.8); a card is its stored network, else the mask's BIN ranges; `Other` = a card with no recognised network |
| `cardType` | `DEBIT`, `CREDIT`, `CHARGE CARD` — `bin_info` of the card's first six digits, raw (prefer `funding` on the account API) |
| `issuer`, `cardLevel` | issuing bank / card level — `bin_info` of the card's first six digits; `GET /v1/transactions/facets` lists them |
| `country` | ISO country code, upper-cased on both sides — the payload's root `country`, else a wallet charge's `billingAddress.country`; a subscription charge inherits its originating sale's (v3.9 §2) |
| `storefront` | store host, e.g. `shop.example.com`, or `(direct)`; a subscription charge inherits its sale's |
| `traffic` | `tiktok`, `meta`, `(direct/organic)`; a subscription charge inherits its sale's |
| `product` | product name, slug or id |
| `device` | `Mobile`, `Tablet`, `Desktop` — read off the user agent (a subscription charge: its sale's); a row without one has no value, there is no `(unknown)` |
| `os` | `iOS`, `Android`, `Windows`, `macOS`, `ChromeOS`, `Linux` — no `Other` / `(unknown)` |
| `paysource` | `APPLEPAY`, `GOOGLEPAY` |
| `amountMin`, `amountMax` | **cents**, inclusive |
| `ip` | client IP (a subscription charge: its sale's) |
| `refunded` | `true`, `false` — the charge's state (fully refunded, a chargeback included), on the **charge** date (v3.9.9) |
| `refund` | `refund`, `chargeback`, `rdr`, `ethoca` — the refund **event**: a successful, non-test refund of that kind; `from` / `to` (or `hours`) then read the **refund** date (v3.9.9, `/v1/reports/transactions`) |
| `refundBasis` | `refund` (default), `charge` — with `refund`, `charge` keeps the window on the charge date (the window's sales, refunded at any date) |
| `population` | `live`, `test`, `imported` — `live` = the rows every report counts (no test card, no import) (v3.9.9, `/v1/reports/transactions`) |
| `q` | free text: order id, supplier id, email, phone |
| `first6`, `last4`, `email` | card / customer lookup |

The Traffic report's own dimensions — `hour` (0-23, read in `tz`, which is then **required**),
`ipType` (`IPv4`, `IPv6`), `bin` (six digits), `funding` (`Prepaid`, `Debit`, `Credit`,
`Charge card`), `browser` (`Edge`, `Opera`, `Samsung Internet`, `Firefox`, `Chrome`, `Safari`),
`gatewayMcc`, `gatewayBin`, `pricePoint` (`1. < $25` … `7. $200+`) — and the rest of the catalog
(the routing, client, subscription, schedule and refund-row keys: `atriFinal`, `walletProvider`,
`credentialMode`, `customerEmail`, `clientLtvMin`, `subStatus`, `cycle`, `entryStatus`, `refundStatus`,
`refundTest`, …) are accepted and applied on every `/v1/reports/*` endpoint since v3.9.15, by the
same names as on the **account API** (`GET /v1/transactions`, `/v1/metrics`,
`/v1/metrics/traffic`, `/v1/metrics/bins` — see *Reports › Traffic and Bin & Issuers* below).
A key a report's rows cannot carry answers an empty result (zeros), never the unfiltered figure.
`refundTest` is a modifier of `refund` / `refundStatus`: alone it filters nothing.

Two behaviours worth knowing, because they are what make the API agree with the UI:

- **A charge we refused before any MID is not a transaction** (v3.9 §1). Blacklist, filter /
  velocity guard, BIN scrub, card pre-check, card cooldown and 3DS policy refusals are
  *rejections* (`results[].rejected` on `POST /v1/charge`, listed by `GET /v1/rejections`):
  they never appear in this list nor in any approval rate, and the former `status=cooldown`
  value is gone. A decline is a MID verdict (`declined`) or a technical error (`error`) —
  `status=failed` is exactly that. The list shows every live row plus the flagged test-card
  and CSV-imported rows, and never a 3DS park (a `pending` row the checkout re-opens).
- **Refunds and chargebacks are counted on the REFUND date** (v3.9.9), and a refund count never
  includes a chargeback. On `/v1/reports/transactions`, `refund=refund` (or `chargeback`, `rdr`,
  `ethoca`) lists the charges whose successful refund of that kind was booked in the window — the
  window reads the refund's date, the sale may be older. `refunded=true` is the charge's own state
  (fully refunded, a chargeback included) on the charge date; add `population=live` to count what the
  reports count. The list reads the account's whole tenancy, its own charges included (a subscription
  charge declined before any MID carries no key and no gateway).

---

Direct `/v1/reports/*` reads support at most 92 days; direct account API report reads
support at most 400 days (Flows retains its 366-day limit). A larger range returns
400 with guidance to use report jobs. These direct analytics reads use the isolated
reporting pool and a 25-second request budget, including time waiting for a connection.
Client disconnection cancels outstanding SQL; a deadline asks the caller to retry
or use a report job. Durable report jobs retain their existing range contracts.

#### `GET /v1/reports/transactions`

The transaction list, with every filter above. Paginated: `limit` (max 500, default 100)
and `offset`. Sorted over the **whole** result set, not the page:

| param | values |
|---|---|
| `sort` | `created_at` (default), `completed_at`, `amount`, `status`, `order_id`, `email` / `customer`, `mid`, `atri`, `crm`, `country`, `storefront`, `traffic`, `decline_reason`, `card`, `three_ds`, `method`, `source`, `product`, `processor`, `acquiring_bank`, `company` (the reference names each row carries as `processor_name` / `acquiring_bank_name` / `company_name`) |
| `dir` | `asc`, `desc` (default) |

Every key other than `created_at` tie-breaks on `created_at desc`, nulls last. An unknown
key — or a direction passed as the key, `sort=asc` — is a **400** whose `details` list the
allowed values; it is never silently ignored.

```bash
curl -H "Authorization: Bearer $KEY" \
  "$BASE/v1/reports/transactions?hours=24&status=failed&brand=Visa&sort=amount&dir=desc&limit=50"
```

```json
{
  "total": 1342, "limit": 50, "offset": 0, "count": 50,
  "transactions": [
    {
      "order_id": "…", "amount_cents": 6197, "currency": "USD",
      "status": "declined", "is_success": false,
      "masked_card": "446614..8906", "method": "Visa", "email": "…",
      "final_account_name": "CAT CORNER CONVESIO/ADYEN", "atri": "Main",
      "processor_name": "CONVESIO PAY", "acquiring_bank_name": "ADYEN", "company_name": "STELLAR TIDE LLC",
      "decline_reason": "Do Not Honor",
      "refunded": false, "charged_back": false,
      "traffic_source": "tiktok", "storefront_url": "https://…",
      "created_at": "2026-08-26T09:21:31Z"
    }
  ]
}
```

#### `GET /v1/reports/gateways`

The Per gateway report and the dashboard KPIs in one payload: `totals`, `perMid`, `perAtri`,
`finance`, `perStore` / `perTrafficSource` / `perCardBrand` / `perSource`, `declineReasons`.
Add `bucket=hour|day` for the time `series`.

Per MID you get `charges`, `approved`, `declined`, `approvalRate`,
`approvalRateMidFixable` (the **real** MID AR — excludes declines no MID could win, like
NSF or a stolen card), `routedCents` (what it *attempted*, cascade retries included) and
`grossCents` (what it *captured*). Every `perMid` and `perWallet` row also names its
`processorId` / `processorName`, `acquiringBankId` / `acquiringBankName` and — since v3.9.2 §0 —
`companyId` / `companyName` (null when the gateway carries none), so a per-processor, per-bank
or per-company rollup is one `groupBy` on your side — and the `processor` / `acquiringBank` /
`company` filters above narrow both breakdowns to one of them.

**v3.9.13 — a change to `finance` under a filter.** The dimension filters and `pass` narrow the
per-gateway rows only, never `totals` or `finance`. `finance.transactionFeeCents`, and so
`finance.netCents`, now follows that rule. Before, a filtered call or `pass=initial` summed only the
filtered MIDs' attempt fees, which put a filtered fee into an otherwise unfiltered ledger. Now it is
the window's whole per-attempt fee (plus the wallet providers' per-charge fee), whatever the filters.
A call without a filter returns the same value as before.

**v3.9.15 — `unfilteredFields`.** Only `perMid`, `perWallet` and `noGateway` follow the filters.
Whenever a filter is applied, the response names the fields that stay account-wide in
`unfilteredFields` — `totals`, `declineReasons`, `requestOutcomes`, `perAtri`, `authFailures`,
`finance`, `refunds`, `chargebacks`, `perStore`, `perTrafficSource`, `perCardBrand`, `perSource`,
`subs`, `series` — so a filtered call is never read as a filtered total. Without a filter the field
is absent and the payload is unchanged. For a filtered total, sum the `perMid` / `perWallet` /
`noGateway` rows, or read `/v1/reports/transactions` with the same filters.

#### `GET /v1/reports/products`

Per-product performance. `groupBy=product` (default) or `store`.

Money is allocated **pro-rata across a basket's lines**, so a multi-product order is never
counted twice, and quantity never scales a stat: an order for 3 units is **one** sale.
`units` is reported separately. Rows are ranked by straight volume, then by subscription volume
(v3.9.13), then key.

**v3.9.13 — the money adds up exactly.** By product, each money column (`volumeCents`,
`rebillVolumeCents`, `grossCents`, every fee, `refundCents`, `chargebackCents` and their fees) is
allocated to the rows by **largest remainder**. Every row takes the floor of its exact pro-rata
share, then the rows with the largest fractions take one more cent until the column adds up.

- Summed over every row, plus the charges no basket names, a money column equals the account's
  figure for the window, to the cent. Those charges are not a row here; the dashboard shows them as
  its "(no product basket)" row.
- Each row is within 1 cent of its own exact share.
- `netCents` is `grossCents` minus its parts, so the rows' Net adds up exactly too.
- The allocation covers every row, including any past the 500-row cap, so the returned rows add
  up only when none is cut.

A row's money column can differ by 1 cent from what v3.9.12 returned, when each row was rounded on
its own and the rows did not quite add up. Its `netCents` can differ by the sum of its parts'
changes. With `groupBy=store` nothing changes: a store row holds whole charges.

#### `GET /v1/reports/segments`

Seventeen dimensions — price point, initial order value, source, card brand, product, store,
geo, hour, device, OS, traffic, card type, issuing bank, card level, since v3.9 the
gateway's **processor** (`dim: "processor"`) and **acquiring bank** (`dim: "acquiring_bank"`),
and since v3.9.2 the gateway's **company** (`dim: "company"`). For those three the segment
key is the reference name as the list spells it (`PRIORITY`, `SYNOVUS`, `STELLAR TIDE LLC`),
resolved through the charge's final MID or its wallet provider; a gateway without that
reference lands in `(unset)` and — v3.9.12 — a charge that ended on no gateway at all in
`(no gateway)`. Their rows carry `ref`, the reference id (`none` on `(unset)` — the filter's own
`none` —, `nogw` on `(no gateway)` — `accountId=none` on the list).

v3.9.12 — `mode=rebill` adds five dimensions (22 there): `subscription` (the charge's
subscription product; `(none)` = a charge no subscription produced), `cycle` (`Cycle N`), `mid`
(the gateway: the MID's name, or `<provider> · <wallet>` for a wallet charge), `category` (the
MID's primary category) and `mcc` (the MID's MCC). Their rows carry `ref` too — the value of the
dashboard list's filter behind the name (a product id, N, a MID id or `wallet:<provider id>:<wallet>`,
a category id); `/v1/reports/transactions` takes `accountId`, `processor`, `acquiringBank` and
`company`, the other four are dashboard-list filters.

- `mode=rebill` → approval rate per segment (the window's subscription charges — the list's `source=rebill`)
- `mode=refunds` → the window's **approved sales**, and the refunds and chargebacks **booked in the
  window** (dated by the refund, whatever the sale's date; a chargeback is never a refund; a test
  refund is none) — v3.9.9. The rates are events of the period ÷ sales of the period, so a
  segment can hold a refund of an earlier sale with no sale of its own (rate `0`).

Every figure is per transaction, and each segment key is the value of the transactions filter
that lists its rows (`brand`, `storefront`, `source`…): `/v1/reports/transactions` with
`refund=refund` (or `chargeback`) + `population=live` + the segment's filter returns exactly the
refunds (chargebacks) the segment counts (v3.9.9). A basket with two products sits on two
`product` rows.

```bash
curl -H "Authorization: Bearer $KEY" \
  "$BASE/v1/reports/segments?mode=refunds&hours=168"
```

---

#### Notes for an agent

- **Rates are ratios, not percentages** — `0.44` means 44 %.
- **Money is always integer cents.** Never parse a formatted string.
- **Never average the rates across rows.** Recompute from the components
  (`Σapproved / Σcompleted`: completed = approved + declined + error + unknown, the one
  approval base since v3.9 §1); averaging is wrong whenever rows carry different volumes.
- A wallet charge (Apple / Google Pay) carries no PAN: in every card dimension — brand,
  funding, level, issuer, BIN, card type — it reads its wallet, `Apple Pay` / `Google Pay`
  (v3.9.8), a bucket of its own that the same filter value reproduces; a transaction row names
  it in `method` (`masked_card` is null). `(unknown)` / `(unset)` / `(none)` / `(no gateway)` stay
  real buckets on the segment reports for what nothing resolves. The Traffic and Bin & Issuers reports never
  show such a row: an order without a value for a dimension is left out of that table and
  counted in `excluded[dim]` (the "n orders without …" footnote).
- Rate-limited per key. A 429 means back off and retry.

---

#### Account API: everything a human can do

The four endpoints above are read-only. For **full parity with the dashboard** — create and
edit ATRIs and MIDs, refund, blacklist, manage wallet providers, BIN rules, filters, users —
point your agent at the **`/v1/*` account API with the same kind of API key**.

This is not a second, parallel API. It is *the same handlers the dashboard itself calls*, so
anything you can do by clicking (apart from a few dashboard-session-only actions), an agent can
do by requesting — and the two can never drift apart.

#### Keys and scopes

There is one type of API key. Every key of the account can call every endpoint its scopes
allow. Scopes are set per key in **More → API Keys** (or with `POST /v1/keys`): a read and a
write scope per category, e.g. `checkouts.read`, `checkouts.write`; `scopes: null` is
unrestricted and `[]` grants nothing.

Give the agent a key of its own, with only the scopes it needs, and leave the checkout key
alone. A checkout key leaks from somewhere you do not fully control; if it also carried every
scope, the same leak would mean refunding your entire volume, creating MIDs and reading every
customer's PII.

Two caps apply to every key that no setting lifts:

- The role is pinned to **`admin`** (the account administrator), never `super_admin` — a key
  cannot reach platform-global config (Exify, PlatformPay) or the other-accounts overview.
- It is scoped to **its own account**, exactly like a human member of that account; another
  account's id answers 404.

Every mutation is written to the action log, attributed to the key.

#### Discovering the endpoints

The endpoint index (Part 3) lists every address a key can call, with its scope. The pattern is
uniform.

```
GET    /v1/trips                     list ATRIs
POST   /v1/trips                     create an ATRI
PATCH  /v1/trips/:id                 edit one
PUT    /v1/trips/:id/accounts        set its MID membership + weights
POST   /v1/trips/:id/default         make it the default

GET    /v1/accounts                  list MIDs (gateways)
POST   /v1/accounts                  create a MID
PATCH  /v1/accounts/:id              edit one

GET    /v1/transactions              transaction list (every filter)
GET    /v1/transactions/:id/details      one transaction + its attempts + basket
POST   /v1/refund                    refund (transactionId in the body)
POST   /v1/transactions/:id/chargeback-refund   refund and mark as chargeback

GET    /v1/blacklist                 list
POST   /v1/blacklist                 add an entry
DELETE /v1/blacklist/:id             remove one

GET    /v1/metrics                   dashboard KPIs + breakdowns (?side= — the dashboard's tab)
GET    /v1/metrics/series            the dashboard chart narrowed (?source=straight|subscription, ?atri=)
GET    /v1/metrics/products          products report
GET    /v1/metrics/segments?mode=    rebill / refund & CHB reports
GET    /v1/metrics/traffic           Traffic report (?dims=&tz= + every filter)
GET    /v1/metrics/bins              Bin & Issuers (?axis=issuer|bin[&dim=…]; no dim = every issuer / BIN)
GET    /v1/transactions/facets       free-form filter values (countries, storefronts, issuers, …)

GET    /v1/wallet-providers          wallet MIDs   (+ POST / PATCH)
GET    /v1/categories                categories    (+ POST / PATCH / DELETE)
GET    /v1/keys                      API keys      (+ POST / PATCH / DELETE)
GET    /v1/filters                   order filters (+ PATCH /v1/filters/:key)
GET    /v1/bin-profiles              BIN routing profiles (+ their /rules)
GET    /v1/audit-logs                action log
```

```bash
curl -H "Authorization: Bearer $KEY" "$BASE/v1/trips"

curl -X POST -H "Authorization: Bearer $KEY" -H "content-type: application/json" \
  -d '{"name":"Agent pool","tripType":"classic","dispatchStrategy":"round_robin"}' \
  "$BASE/v1/trips"
```

**403** means the key's scopes do not cover the action (`insufficient_scope`), or the action is
super_admin-only and out of reach for any key, by design.

#### Dashboard › Straight · Subscription · Both

Right under the ATRI activity strip and the Data cards, the dashboard has three tabs:

- **Straight**: the straight sales, meaning new sales and recovered carts.
- **Subscription**: the subscription charges.
- **Both**: everything. This is the default.

The three tabs show the same tables, sections and columns; the figures change, and so do the rows. The breakdowns
grouped from the charges (Store, Traffic source, Card brand, Top decline / error reasons) list the values the tab's
charges carry, so a row can be on one tab and not on another. On top of that, these rows are shown or hidden by the tab:

- Under Straight or Subscription, the Source breakdown keeps that side's row only (Both shows every row).
- Under a side, the Product breakdown hides a product row with no charge on that side (a Straight row whose Pilot
  spend shows stays), and shows "(no product basket)" only when it holds a charge on that side.
- The Pilot reconciling rows ("(ad spend on no store)" on the Store table, its twin on the Product table) appear under
  Straight and Both only, never under Subscription.
- The MID breakdown lists a MID only when it holds an approved or declined charge on the tab (a MID with only
  subscription volume is a row under Subscription and Both, not under Straight), and "(no gateway)" only when it holds
  a charge on the tab.
- The ATRI breakdown lists a cascade ATRI, and the "Wallet / no ATRI" row, only when it holds a charge on the tab (a
  classic ATRI stays on every tab).
- The Wallet breakdown lists a wallet only when it holds a charge on the tab.
- The 3D Secure breakdown lists a row (the 3DS flows, "No 3DS · A/B holdout", "No 3DS · network excluded", "No 3DS
  (not run)") only when it holds a charge on the tab.

The choice is kept in the URL (`?side=straight` or `?side=subscription`; nothing for Both) and
remembered for your user, so the dashboard reopens on it.

**Every block below the tab follows it.** That covers the Sales chart, Last orders, the Finance
breakdown, the ATRI, Store, Traffic source, Card brand, Source, Wallet, Product and MID breakdowns, the
Top decline / error reasons, Request outcomes and 3D Secure.

- Each block's scope icon names the side: straight, subscription or all.
- Every linked figure opens the /transactions list of that side (the link carries the side's `source`).
- Straight + Subscription = Both, exactly, for every table total that adds up and for every row listed on all three
  tabs. The capped lists add up only as totals (their rows plus the "(other)" row), not row by row: the Store and
  Traffic source breakdowns (the top 50) and the Top decline / error reasons (the top 10). Each tab ranks its own top
  rows, and its "(other)" row closes on that tab's own totals, so a store can be a row on one tab and part of
  "(other)" on another, and the "(other)" rows do not add up across the tabs either.
- The Wallet breakdown stays on every tab while the period has wallet traffic. A side with no wallet
  charge shows "No wallet charge."
- The Sales chart has no Source parameter any more: the tab narrows it. Its approval rate is approved ÷
  completed on every tab, like the cards.

**What does not follow the tab:**

- **The ATRI activity strip and the Data cards**, above the tab. They always show both sides, so
  under Both the tables below add up to the cards.
- **Alerts** are account-wide on every tab: a MID credential failure or a cap at 95 % never hides
  behind a tab.
- **The MID breakdown's Cap usage (UTC month) and ATRI tags** belong to the MID, so they are the same
  on every tab.
- **The Request outcomes' request rows** read "—" under Straight and Subscription, because a request
  carries no side. The Timeouts (review) and NMI latency p95 rows do follow the tab.
- **Pilot ad spend has no side.** Under Straight and Subscription, the Finance breakdown's "Ad Spend
  Pilot" and "Net after ad spend" read N/A (see Both). The Store and Product Pilot columns (Pilot
  Spend, Straight ROAS, Ad Accounts, Campaigns) show under Straight and Both, with the spend
  attributed once, on the straight sales. Under Subscription they show dashes.

**Customize** lists the ATRI activity strip and the Data cards first, above a fixed "Straight ·
Subscription · Both tabs" separator. No block can be moved across that separator.

**Through the API**, one `GET /v1/metrics` call carries the tab as `side=straight|subscription|both`:

- The card fields (`totals`, `finance`, `split`, `refunds`, `chargebacks`, `pilot`, `series`…) stay
  unsided.
- The block fields (`perAtri`, `perStore`, `perTrafficSource`, `perCardBrand`, `perWallet`, `perMid`,
  `noGateway`, `declineReasons`, the two latency totals) are the side's.
- `sideTotals` and `sideFinance` are the side's counts and ledger (Straight + Subscription = Both, to
  the cent).
- `walletTraffic` gates the Wallet block.
- Without `side` the payload is unchanged.

The other blocks read these endpoints:

- The chart: `GET /v1/metrics/series?source=straight|subscription`.
- The 3D Secure block: `GET /v1/integrations/3ds/metrics?side=straight|subscription|all`.
- Last orders: `GET /v1/transactions?source=…&count=0` (`count=0` skips the total).
- The products report is read once, without `source`, and split on the page; `rebillUnits` is the
  Subscription tab's Units.

The full contract of each parameter is in the endpoint reference (Part 4).

#### Reports › Traffic and Bin & Issuers

Two read-only report endpoints under `/v1/metrics` back the dashboard's Traffic and
Bin & Issuers tools (v3.9 §2/§3/§4; two tools of their own in Reports since v3.9.1). They
take the **same filter names as the table above** plus the Traffic
dimensions' own (`hour` + `tz`, `ipType`, `bin`, `funding`, `browser`, `gatewayMcc`,
`gatewayBin`, `pricePoint`), and every filter narrows every breakdown *and* the summary.

v3.9.9 — every count equals the /transactions list its link opens: Refunds / CB are the refund and chargeback EVENTS of the
period (successful, non-test refunds rows dated by the refund, per transaction, attributed to the refunded charge's values —
a chargeback is never a refund) with their own count columns; the rates are events of the period ÷ sales of the period. The
ATRI dimension groups on the order's FINAL pool (`atriFinal`), Category on the MID's primary category (`primaryCategory`), the
Gateway dimension gives a wallet charge its wallet provider's row (`accountId=wallet:<id>`), and `accountId` takes MID ids,
`wallet:<id>` and `none` together as a union. A capped dimension returns its `tail` ("Other (n)") and the Totals / Shares read
`axisTotal`; `excludedEvents` carries the refunds / CB of the orders without a value (the table's note).

`GET /v1/metrics/traffic?from=&to=&tz=&dims=` — every dimension of the window, cut from
the same live rows in one call. `dims` is a CSV of `source` (the order origin: `sale` /
`rebill` / `recovery`), `traffic` (the traffic source), `storefront`, `device`, `browser`,
`os`, `ipType`, `hour`, `brand`, `funding`, `level`, `issuer`, `bin`, `gateway`,
`gatewayType`, `category`, `atri`, `processor`, `acquiringBank`, `company`, `gatewayMcc`,
`gatewayBin`, `threeDs`, `geo`, `pricePoint` (omitted = all 25; ask for one tab's worth) — the dashboard's
own keys, no alias. `tz` is the IANA zone the Hour rows and the `hour` filter are read in — send
the one you built `from`/`to` with (default: the account's timezone). Response
`{ byDimension: { <dim>: [row] }, excluded: { <dim>: n }, summary, tz }`; a row carries
`key` (the `/v1/transactions` filter value of that dimension — a MID / category / ATRI /
processor / bank / company id, the label itself otherwise), `name`, `charges`, `approved`, `declined`,
`completed`, `refunds`, `chargebacks`, `grossCents`, `approvalRate`, `refundRate`,
`chargebackRate`, `aovCents`. There is **no `Unknown` row**: `excluded[dim]` counts the
orders without a value for that dimension, so a table's total is the rows it shows.

Approved counts and gross volume include Friendlies. Rates use ordinary sales:
`approvalApproved` is the non-Friendlies approved count, and `approvalGrossCents`
is their gross volume. Refund and chargeback rates divide by `approvalApproved`;
AOV divides `approvalGrossCents` by that same count. The summary, tail and table
totals use these bases as well. The UI shows an empty rate when its base is zero.
Segment reports use the same ordinary-sale rate base. Their refund-mode product
volume allocates the actual charged amount across the basket, with exact cents;
renewals never reuse the original sale's line amounts as revenue. Transactions
without a basket appear as `__no_product_basket__` and remain in product totals.

`GET /v1/metrics/bins?from=&to=&tz=&axis=issuer|bin&limit=&offset=&sort=&dir=` — **every**
issuing bank (`axis=issuer`) or six-digit BIN (`axis=bin`) of the window, one row each, no cap
(v3.9.1 — the page's Group by = All), sorted and paged server-side →
`{ rows (axis = key = name), total, totals, summary, excluded: { [axis] }, dim: null, axisLimit: null, … }`.
Add `&dim=gateway` (any `dims` key above) for the cut: the top issuing banks / BINs by orders
(`axisLimit`, default 100), each broken down by that dimension →
`{ rows (each with axis + key), total, totals, summary, excluded: { [dim], [axis] }, … }`.
`excluded[axis]` counts the orders with no BIN / issuing bank at all (a card nothing resolves),
outside the list either way; a wallet charge is a row of the list, its issuer / BIN being its
wallet (`Apple Pay` / `Google Pay`, v3.9.8).

**Drill-down rule.** A cell reproduces on `GET /v1/transactions` with the applied filters
(the whole catalog, `from`/`to` + `tz`) INTERSECTED with the row's params (`<filterKey>=<row.key>` — `level→cardLevel`,
`gateway→accountId`, `geo→country`, every other dimension under its own name: `source`, `traffic`, `acquiringBank`,
`company` included; on Bin & Issuers add `issuer=<axis>` or `bin=<axis>`) and the column's (Approved `status=approved`,
Declines `status=failed`). A key on both sides keeps only the common values (the Status aliases and the 3DS umbrellas
`applied` / `none` / `not-run` expanded first); an empty intersection means no link — the count is 0. `population` is
intersected with `live`. Refunds / CB add `refund=<refund|chargeback>&refundStatus=approved&refundTest=exclude`
(refund-dated, never `refundBasis`); the charge cells add `refundBasis=charge` when `refund` or `refundStatus` is applied. A
CSV filter value that contains a comma (an issuer such as `JPMORGAN CHASE BANK, N.A.`) is sent
double-quoted (RFC 4180). Two filters are supersets of their row: `category` (any of a MID's
categories) and `atri` (cascade-aware); a 3DS row is never one (a cryptogram sent with no
recognised flow is its own `applied-other` bucket and filter value).

```bash
curl -H "Authorization: Bearer $KONTROL_API_KEY" \
  "$BASE/v1/metrics/traffic?from=2026-09-24T04:00:00Z&to=2026-09-25T03:59:59Z&tz=America/New_York&dims=hour,device&brand=Visa"
```

The full parameter list, response fields and gotchas of both routes are in the endpoint
reference (Part 4).

#### Checkout engagement metrics

Checkout performance combines traffic and transaction statistics for the selected period and account. An empty ATRI scope applies no additional route filter; it never removes account scoping.

- **CVR** is converted visitors divided by checkout visitors.
- **Completion** is visitors who opened the checkout, clicked Pay and completed payment, divided by visitors who opened the checkout and clicked Pay.
- **AOV** is approved revenue divided by approved transactions. Totals are weighted by approvals; different currencies are not combined.
- **Avg. time** measures foreground time per checkout page view, capped at 30 minutes. Background tabs and previews are excluded. Measurement starts with this release; unavailable historical measurements display a dash.

Repeated cumulative engagement beacons are deduplicated by page-view identity. Known test-payment carts and events marked as tests are excluded from traffic metrics. Visitor and engagement totals are counted once per checkout, even if its payments use multiple currencies.

### Reporting views and attribution

Updated 2026-10-28. All reads retain account scope, dates, timezone and unified filters. These are analytical reads, with no new mutation endpoints.

#### Report ownership

| Report | Views and axes |
| --- | --- |
| Traffic | Acquisition: source, origin, store. Devices & browsers: device, browser, OS, IP type. Geography & time: country, hour. |
| Payment / Per gateway | Gateways with company/processor/acquirer grouping. Routing: category, ATRI, gateway type, processor, acquirer, MCC, acquirer BIN. Authentication: 3DS. Detailed gateway fees stay here. |
| BIN & Issuers | Exhaustive server-paged BIN/issuer analysis with cross-breakdowns. Card profiles: brand, funding, level. |
| Products | Product/store financial breakdown. Winners. Pricing & currency. Basket amounts retain pro-rata allocation. |
| Subscription | Subscription products/cycles/prices/hour/currency. Routing. Cards. Traffic including historical checkout. Profiles. Subscription charges only. |
| Refund & CHB | Sales & products. Routing including company/gateway/category/MCC/3DS. Cards. Traffic including checkout. Profiles. Refund events use their own dates. |
| Per checkout | Conversion. Payments. Breakdowns: checkout crossed with store, gateway, company, category, MCC, 3DS, subscription product, source, payment method or country. Day by day. |
| Financial | Overview, Breakdown, Daily. Breakdown/drill also accepts category, MCC, 3DS, checkout and subscription product. Owns net, fees and reconciliation. |
| Cart recovery | Overview. By shop. Touches. Templates. Audience: language/channel/currency. Failed sends. |

`/reports/rebill` remains an alias for Subscription. Old Traffic links with `tab=routing`, `tab=cards` or `tab=price` redirect to the owning report while preserving filters. Generic gateway, card and price tables no longer appear in Traffic. Domain reports retain shared axes because refund rates, subscription approval and financial reconciliation answer different questions. Cross-breakdowns in BIN and Checkout are distinct from generic single-axis summaries.

Exports contain the active view's tables, respecting columns and sort. Never sum totals across different breakdown tables: each partitions the same population again.

#### API examples

Authenticate as described in Part 1, with an API key of the account (`Authorization: Bearer <key>`) that holds the matching read scope. The following GET paths are relative to `https://api.kontrolcheckout.com`. Substitute owned UUIDs. Validation failures return 400, auth/scope failures 401/403.

```text
/v1/metrics/segments?mode=refunds&from=2026-10-01&to=2026-10-28&tz=America/New_York
/v1/metrics/segments?mode=rebill&from=2026-10-01&to=2026-10-28&checkout=CHECKOUT_UUID
/v1/metrics/traffic?from=2026-10-01&to=2026-10-28&dims=category,threeDs
/v1/metrics/bins?from=2026-10-01&to=2026-10-28&axis=bin&dim=checkout
/v1/metrics/checkouts?from=2026-10-01&to=2026-10-28&groupBy=gatewayMcc
/v1/metrics/financial?from=2026-10-01&to=2026-10-28&groupBy=checkout&top=20
/v1/recovery/report?from=2026-10-01&to=2026-10-28&tz=UTC
```

For heavy reads use the existing report-job lifecycle (see *Operations, reporting and current behavior* in Part 2). Checkout jobs preserve groupBy in execution and cache identity. Results predating this change are marked obsolete and recalculated.

#### Response additions

- Segments: `segments[]` adds checkout, three_ds, currency. Refunds also exposes subscription product, MID, primary category and MCC. Cells retain counts, rates, ref for drill-down and volumeCurrencies. Missing attribution stays visible.
- Generic dimensions: checkout, subscription, currency use the existing dimension response; existing API dimensions remain supported.
- Checkout: optional groupBy accepts store, gateway, company, category, gatewayMcc, threeDs, subscription, source, method, country. Rows and daily series add stable group_key and group_name. Each remains partitioned by checkout and currency. Grouped reads omit visitor statistics (funnel=null, funnel_error=null); use ungrouped reads for conversion/completion/time. A visitor cannot be assigned a payment gateway before paying.
- Financial: groupBy and drill[].dim accept category, gatewayMcc, threeDs, checkout, subscription in addition to existing axes. Attempt fees use the attempting MID's category/MCC; charge/refund figures use the final MID. Pre-gateway 3DS fees remain unattributed, so breakdowns reconcile.
- Recovery: by_audience[] contains language, channel, currency, sent, carts, recovered, recovered_cents, discount_cents. Carts are distinct within each group. Recovered value is cart subtotal; discounts are offers across sends, not redeemed discounts. A cart can appear in multiple channels; there is no additive audience grand total. Missing target price contributes zero offered discount.

#### Interpretation

The unified checkout filter accepts comma-separated UUIDs and none. It reads coalesce(checkout_id_at_sale, checkout_id), not the store's current checkout. Checkout visitor selection follows it too. checkoutId remains the existing single-checkout selector for checkout analytics.

Subscription attribution selects one product per charge, preferring its rebill entry, then originating attachment. Creation time and ID make duplicate records deterministic. A charge does not multiply grouped financial amounts.

3DS describes the counted transaction. Its disjoint buckets are `frictionless`, `challenge`, `attempt` (network stand-in), `data-only`, `applied-other`, `reserved` (proof saved for rebill, not applied to this charge), `attempted` (authentication attempted but not applied) and `none` (no recorded authentication or a deliberate skip). Missing legacy booleans/statuses are included. Each bucket is an exact `threeDs` filter. `applied` remains an umbrella over the five applied flows. Customer Single/Double 3DS describes the customer's proof inventory, not two proofs applied to one transaction. Wallets without a 3DS stamp appear under No 3DS; use `method=card` for a card-only comparison.

Example: `/v1/metrics/segments?mode=refunds&from=2026-10-01&to=2026-10-28&threeDs=reserved,none` selects only saved-for-rebill and no-3DS sales/refund events. Use `threeDs=applied,attempted,reserved` to inspect authentication-fee-bearing transaction populations; rejection fees have no transaction and remain separate.

Gateway rows use MID IDs or wallet-provider/wallet identities, never ATRI IDs. Checkout wallet `group_key` uses `wallet:<provider UUID>:<Apple Pay|Google Pay|Wallet>`, consistent with generic and segment reports. Same-named gateways remain separate. Financial ATRI rows and their `atriFinal` drill links use the final cascade ATRI; pre-gateway rejection fees use their recorded ATRI. The Financial 3DS label `No transaction · Rejection fees` does not mean a sale without 3DS.

Refund and chargeback events must be successful and non-test; counts are distinct refunded transactions. Test/import exclusions and date semantics are unchanged. Different currencies must never be summed as one monetary amount. Friendlies sales stay outside gateway approval-rate denominators.

#### Validation

PostgreSQL tests cover all 28 generic dimensions, both segment populations, all ten checkout cross-breakdowns, all 16 Financial axes and all four financial fact populations. A 468-case 3DS matrix proves exhaustive classification and exact filter membership. Cases include distinct same-named gateways under an ATRI, wallets, all eight 3DS buckets, refund dates, currency boundaries, tenant-isolated recovery messages and repeat sends. A report ownership test prevents duplicate generic dimension assignments. Local browser verification uses sample transactions aggregated by the real PostgreSQL query, with desktop/mobile checks and CSV/PDF downloads; it is not a production data audit.

### Status tracker

For the team operating the **external status tracker** that monitors the payment
dispatch API. This is the daily health snapshot: what to poll, what each metric
means, and **what to do when one goes red**.

The tracker is "dumb" by design - all grading happens server-side. You poll one
endpoint, read `overallSeverity` for the top-line light, and render
`metrics[]` / `providers[]` / `alerts[]`. You do **not** compute thresholds.

---

#### 1. The endpoint

```
GET https://api.kontrolcheckout.com/v1/status/daily
Header:  Authorization: Bearer <API key of the account>
```

- **Auth:** an API key of the account with the `reports.read` scope, sent as
  `Authorization: Bearer <key>`. The snapshot covers that key's account only.
  Keep the key out of logs and client-side code. Existing trackers may still
  send a legacy platform status key in `X-Status-Key`.
- **Window:** every metric covers the **last 24h**, compared against **D-1**
  (the previous 24h) and the **7-day daily average**.
- **Cadence:** designed for a **daily** pull. Hourly polling is safe too
  (response is `cache-control: private, no-store`: every poll is re-authorized).
- **Responses:**
  - `200` - snapshot body (below).
  - `401` - missing/invalid key.
  - `403` - the key lacks `reports.read` (`insufficient_scope`), or the account
    is suspended.
  - `503` - the key lookup or the DB query failed. A `503` is itself an
    incident: treat it like a heartbeat failure.

##### Quick test

```bash
curl -s -H "Authorization: Bearer $KONTROL_API_KEY" \
  https://api.kontrolcheckout.com/v1/status/daily | jq '.overallSeverity, .alerts'
```

---

#### 2. Response shape

```jsonc
{
  "generatedAt": "2026-06-16T12:00:00.000Z",
  "window": "24h",
  "overallSeverity": "critical",          // worst of all metrics → your top-line light
  "metrics": [
    {
      "key": "approval_rate",
      "label": "Overall approval rate (AR)",
      "tier": 1,
      "value": 0.41,                       // current 24h
      "unit": "ratio",                     // ratio | count | cents | ms | minutes
      "dMinus1": 0.62,                     // previous 24h
      "avg7d": 0.64,                       // 7-day daily average
      "deltaVs7d": -0.23,                  // value − avg7d (pts for ratios)
      "severity": "critical",              // ok | warn | critical | not_instrumented
      "threshold": "warn: <0.55 ... crit: <0.5 ...",
      "hint": "..."                        // human guidance, safe to show in the UI
    }
    // ... one object per metric
  ],
  "providers": [
    { "mid": "uuid", "name": "MID-A", "charges": 88, "approvalRate": 0.05,
      "capPct": 0.97, "severity": "critical",
      "issues": ["AR 5% with 88 charges - MID likely frozen/dead, pause it",
                 "cap 97% - about to stop routing, raise cap/provision"] }
  ],
  "alerts": [                              // only warn+critical, critical first - page off this
    { "source": "metric", "label": "Overall approval rate (AR)",
      "severity": "critical", "hint": "..." }
  ],
  "declineReasons": [ { "reason": "DECLINE", "count": 412 } ]   // top 10, context for AR moves
}
```

**Rendering rule:** color each row by `severity`. `not_instrumented` = grey
"not wired yet" (see §5), never an alert. Page only on `alerts[]`.

`unit` decoding: `ratio` is 0-1 (show as %). `cents` ÷ 100 for dollars.
`minutes` / `ms` as-is. `count` is a raw number.

---

#### 3. Metrics & what to DO (the important part)

Severity is computed for you. This table tells the on-call person what each red
light **means** and the **first action**. Tiers: **1 = urgent/page**,
**2 = investigate same day**, **3 = trend only, never alerts**.

##### 🔴 Tier 1 - urgent, act now

| key | Means | First action |
|---|---|---|
| `approval_rate` | Overall AR dropped hard or below floor | Open `providers[]` - is it ONE MID or all? One → pause that MID (next row). All → suspect gateway/network; check `error_rate` + NMI/Convesio status. |
| `provider_ar_collapse` | A specific MID with real volume is approving almost nothing → likely **frozen/dead** | In the dashboard, **pause that MID in its ATRI** so the cascade skips it. Confirm with the provider. |
| `mid_cap_usage` | A MID is near its monthly `$` cap and will drop out of routing | Raise the cap or provision another MID **before** it hits 100%, or volume/risk piles onto the rest. |
| `unknown_rate` | Ambiguous timeouts - these **never auto-failover** (double-charge guard) | Manually reconcile those orders against the provider. Do **not** blindly retry. |
| `order_volume` | Order count fell off a cliff vs the 7d average | Usually **not** payments - check upstream traffic source / the checkout integration / the caller's API key. |
| `heartbeat` | Minutes since the last order is too high (or zero orders ever) | During business hours = system or all traffic down. Check `/healthz`, the API logs, and whether the tracker itself got a `503`. Account for known off-hours. |

##### 🟠 Tier 2 - investigate same day

| key | Means | First action |
|---|---|---|
| `error_rate` | Gateway/network errors (not declines) rising | Check NMI/Convesio status + API error logs. |
| `duplicate_rate` | Client retry storm / reused `orderId` | Idempotency is catching it; tell the caller to stop double-sending. |
| `auth_failed_rate` | Requests failing auth | A key was rotated/leaked or a caller is on the wrong env. Identify the caller (`charge_request_logs.key_prefix`). |
| `invalid_body_rate` | Malformed payloads | A caller shipped a broken integration - get them the schema. |
| `p95_latency_ms` | Attempt latency ≥2× the 7d baseline | Gateway degradation; rising latency often precedes timeouts/unknowns. |
| `request_conversion` | Orders-per-inbound-request dropped | A checkout/validation break upstream. (This is requests, **not** page visits - see §4.) |

##### 🟢 Tier 3 - context only (never paged)

| key | Use |
|---|---|
| `order_amount_cents` | Approved `$` volume (÷100). Revenue trend. |
| `traffic_requests` | Inbound request count = "traffic". |
| `declineReasons` | Top 10 decline/error reasons - explains *why* AR moved. |

---

#### 4. What "traffic" and "conversion" mean here ⚠️

The API only sees **inbound charge requests**, not landing-page visits. So:

- **Traffic** (`traffic_requests`) = count of requests hitting `POST /v1/charge`.
- **Conversion** (`request_conversion`) = orders ÷ inbound requests - **not**
  orders ÷ page visits.

Do not label it "visit conversion" in the UI. True page-visit conversion needs
frontend instrumentation that does not exist yet (would be a future phase).

---

#### 5. Not instrumented yet (Phase 2)

These appear in `metrics[]` with `severity: "not_instrumented"` so the tracker
can show a placeholder. They are **not** failures and never alert:

| key | Why it's grey | To turn it on |
|---|---|---|
| `external_api_forward_failures` | No order-forwarding/postback layer logs this yet | Add a `forward_attempts` table written wherever orders are pushed to the CRM/fulfillment. |
| `pixel_failures` | Pixel/CAPI fires aren't logged | Add a `pixel_events` log (from the checkout frontend or a CAPI worker). |

When wired, they become real Tier-1/Tier-2 metrics with no tracker change.

---

#### 6. Tuning thresholds

All thresholds live in **one** file on the API:
`api/src/lib/statusThresholds.ts` → `STATUS_THRESHOLDS`. Current defaults:

| Metric | Warn | Critical |
|---|---|---|
| Approval rate | <55% or drop >8pts | <50% or drop >15pts vs 7d |
| Order volume | drop >30% | drop >50% vs 7d avg |
| Conversion | drop >25% | drop >40% vs 7d |
| Unknown/timeout rate | >1% | >3% |
| Error rate | >2% | >5% |
| Duplicate rate | >2% | >5% |
| Auth-failed rate | >1% | >5% |
| Invalid-body rate | >1% | >5% |
| p95 latency | >2× 7d p95 | >3× 7d p95 |
| Heartbeat | >60 min | >180 min or never |
| Provider AR (≥20 charges) | <40% | <20% |
| MID cap usage | ≥85% | ≥95% |

Changing a number there re-grades the next snapshot automatically - no tracker
change, no schema change.

### Subscriptions engine

How recurring billing works on this platform and which calls drive it. Every route below is
under `/v1/subscription/*`, scoped to your account (a foreign id is a `404`), and takes an
API key of the account (`Authorization: Bearer ck_…`). Money is integer cents; days are New York
calendar days (`YYYY-MM-DD`); instants are ISO-8601 UTC.

**Monitoring membership.** A subscription enrolled in a schedule counts immediately, including before its first charge is attempted. First-payment success is a payment fact, not an activation step. Collection pauses retain membership; an ending keeps its actual cause. Monitoring and exports no longer show activation or failed-activation categories.

**Retry OFF.** The existing account setting disables automatic ladder retries, technical retry-soon, processor-duplicate requeues and duplicate-card next-day retries. Previously queued retries are refused at dispatch while OFF. Normal recurring charges after a successful cycle continue to follow the product interval.

#### Current schedule operations (2026-10-22)

*Operations, reporting and current behavior* in Part 2 documents `transactionTotal`, the paginated `GET /v1/subscription/schedules/:id/transactions` reader and its Analytics-cell filters, processing versus partial status, and force-bill `dripDelaySeconds` (0–86,400). A positive delay serializes dispatch; it is not a new subscription interval. Subscription counts and transaction counts are different. Use returned transaction and gateway IDs for drill-downs.

For every current read/write operation and its exact body, use the endpoint index (Part 3) and the endpoint reference (Part 4). UI comma-separated price syntax is not a generic API payload.

#### 1. Three objects

**New sales after a cancellation.** A cancelled schedule keeps its old charges and history. New subscriptions use another non-cancelled schedule for the same product and billing date, or create an additional pending schedule if none exists. The additional schedule has a numbered name, so several schedules can share a date. Paused schedules remain paused; this fallback does not turn on automatic dispatch or restore cancelled charges.

| object | what it is | table |
|---|---|---|
| **Subscription** (product) | The offer: `VIP — $69.99 every 30 days, first charge 3 days after the sale`. Carries the attach rules (which sales get it: storefronts, approved/declined, a percentage), the ATRI split, the retry profile, the max cycles. | `rebill_subscriptions` |
| **Sub** | One customer's subscription: the order it came from, its product, the agreed amount, its cycle, its next charge, its status (`active` · `paused` · `completed` · `failed` · `cancelled` · `expired`) and why it ended (`end_cause`). | `rebill_subs` |
| **Schedule** (a day) | The product's charges of one New York day. It is a *view*: it carries no setting of its own — name, ATRI split and retry profile mirror the product. Its rows are **entries**, one per charge. | `rebill_schedules`, `rebill_entries` |

A sale never *is* a sub. A **card sale on NMI** that matches an active product's attach rules
gets a sub the second it settles (`attachToSale`); wallet sales (Apple / Google Pay) never do —
there is no card on file to charge again.

**Opt-in products** (v3.9.17). A product's `attachMode` is `auto` (the attach rules above) or `optin`: an opt-in product is
NEVER attached by the rules, the minute sweep or a bulk attach (`422`) — a checkout's Subscription product block attaches it,
when the customer ticks it (`POST /v1/charge` `subscription_optin`), and an operator may still attach it to ONE order by hand
("Add subscription" in the transaction modal: an explicit decision, source `manual`). A sale whose customer opted
in gets THAT product (source `optin`, an auto or an opt-in product alike) and none of the account's auto products; Law (a)
holds as for any attach (a customer with a live sub is skipped `exists`, a never-paid recovery sub is superseded). The
targeting rules (storefronts, attach %) do not apply to an opt-in; the product's own outcome (`attachOn`) does.

##### Fixed and Dispatch amounts

In **Subscriptions → Add / Edit subscription → Offer**, choose the amount mode:

- **Fixed** keeps the existing single amount.
- **Dispatch** lets you add and remove price-point tags. Each new subscription receives one of the configured amounts with an equal allocation probability. The selected amount is saved on that subscription and remains its recurring amount; renewals and retries do not select another price. Explicit introductory-cycle and retry-profile amounts still apply when configured.

Dispatch supports 1–50 distinct prices from $0.01 to $10,000.00. Changes to the product's prices affect new enrollments only. Advanced plans dispatch their recurring amount after the fixed introductory cycles. Select a price point in Simulation to preview that outcome.

Product writes accept `amountMode: "fixed" | "dispatch"` and `amountOptionsCents`, an array of integer cents. For example, `amountMode: "dispatch", amountCents: 2999, amountOptionsCents: [2999, 3999, 4999, 5999]` configures four prices. The legacy scalar `amountCents` mirrors the first dispatch option; it is not the amount assigned to every customer. Product reads return `amount_mode` and `amount_options_cents`.

Send all three pricing fields together when changing the mode or prices. Unrelated partial edits leave pricing untouched. To return to Fixed, send `amountMode: "fixed"`, the chosen `amountCents`, and `amountOptionsCents: []`. Existing clients that omit the new fields still create fixed products.

Moving a customer to another product selects that product's price unless **Keep amount** is enabled. Selecting the same Dispatch product again keeps the existing amount. An explicit amount on a manual attachment remains an override.

#### 2. The loop

1. **Attach** — an approved (or, for the decline products, a declined) NMI card sale matches a
   product → a sub is created with `next_charge_at = sale + first delay` (an **Advanced** product: cycle 1's
   delay, and the sub keeps a copy of the product's plan — see "Simple and Advanced plans"). The customer's card,
   IP, user agent, currency and billing details are replayed at every charge.
2. **Materialise** — the sub's next charge is written into the product's schedule of that day at
   once, however far ahead. A day that did not exist is created; a day that was already
   **finished** (its New York day over, or force-billed through) and done **reopens as Partial** —
   see §5. A day still running simply grows and stays Processing.
3. **Dispatch** — on the day, the engine claims each entry at its slot (spread over the New York
   day, never a burst) and charges it through the ATRI split of the schedule, under the rebill routing constraints
   (Settings) — or through a route override of the charge or of the day (v3.9.15, "Change ATRI / Gateway" below). **Force bill** runs the whole day now, as a job you can follow live, on the
   route you choose (§4). **Pause** stops a day until you resume it.
4. **Result** — approved → `cycle + 1`, next charge = the plan's next cycle (Simple: slot + interval;
   Advanced: the next intro cycle, then slot + interval) or `completed` at max cycles. Declined → the **decline engine** decides: `retry` once through the product's retry
   profile (its amount, its delay), `retry_soon` for a transient problem (same amount, 1–4 h
   later, never spends the retry), or the sub ends (`failed` / `expired` / `cancelled`).
5. **Lifecycle hooks** — a refund, chargeback or dispute alert on the order, a blacklisted
   customer, a BIN scrub → the sub ends with that cause and is never re-attached.
6. **Safe-Guard** — per account: a day whose approval rate falls under X % once N charges are
   decided is cancelled automatically (its subs paused; *Resume* restores exactly what it stopped).

#### 3. Common tasks

| task | call |
|---|---|
| Create a product | `POST /subscriptions` `{ name, amountCents, firstAfter:{value,unit}, interval:{value,unit}, attachOn, attachPct, storefronts, atriSplit, retryProfileId, maxCycles, active, autoAttach, planMode?, planSteps? }` — `planMode: 'advanced'` + `planSteps` = the intro cycles (see "Simple and Advanced plans"); a refused plan is a 422 whose `error` names the cycle |
| Edit a product | `PUT /subscriptions/:id` — reaches every charge **not yet sent**: name / ATRI split / retry profile are copied onto the pending days at once; the interval applies from the next paid cycle; **the amount a sub agreed to is kept** (change it on the sub). **A plan edit reaches NEW subs only — live subs keep the plan they took.** `active:false` cancels the pending charges (subs stay active) — `true` re-plans them |
| Simulate a plan | `POST /plan/preview` `{ planSteps, amountCents, interval, maxCycles?, saleAt?, cycles?, retries? }` — the engine's own dates and amounts for a draft (nothing is written); an invalid plan answers `valid: false` with the errors |
| Attach past sales | `POST /subscriptions/:id/attach` `{ from, to, storefronts?, dryRun }` — dry run first, it tells you how many would attach and why the rest would not |
| Attach one sale | `POST /subs/attach-sale` `{ transactionId }` |
| List subs | `GET /subs` — filtered by **the unified catalog** (v3.9.15, the same keys as /transactions and every report): the sub keys `subStatus`, `attachedBy` (was `source` — `source` is now the charge's Straight / Subscription), `subscription`, `subCreatedFrom/To`, `subEndedFrom/To`, `due`, the quick search `q`, and every other catalog key through the sub's charges (a sub matches when at least one of its charges matches); the range `from` / `to` = "had a charge in the range"; `sort` / `dir` / `limit` / `offset`. An unknown key is a 400. The filter values come from `GET /v1/filters/facets` (`/subs/facets` is gone) · `GET /subs/ids` (the same query) for "select all matching". The /subs page opens on `subStatus=active` written in its address; Clear keeps an empty `subStatus=` (every status) |
| One customer | `GET /subs/:id/customer` or `GET /customer?orderId=…` / `?email=…` — the sale, the card, every sub and every charge |
| Pause / resume / cancel a sub | `POST /subs/:id/pause` · `POST /subs/:id/resume` · `DELETE /subs/:id` `{ reason }` |
| Force bill one sub now | `POST /subs/:id/charge-now` `{ atriId? \| midId? }` — charges the sub synchronously on the route you choose (none = *Use original*) and returns the verdict with the refreshed sub (see below) |
| Change a sub's product or amount | `PATCH /subs/:id` `{ subscriptionId?, keepAmount?, amountCents?, nextChargeAt?, resetFrequency? }` — the pending charge is re-planned, an in-flight one is never dropped; `resetFrequency: true` puts the sub back on its product's frequency (a Rebill Flow can give a sub its own) |
| Many subs at once | `POST /subs/bulk` `{ ids[], action: pause \| resume \| cancel \| change_subscription \| amount, subscriptionId?, keepAmount?, amountCents?, reason? }` (≤ 10 000 ids) |
| The calendar | `GET /schedules/calendar?from&to` — one row per day and product with its stats (sources of the subs, decided, success, approved / planned cents, `first_pending_at`, `reopened_at`) |
| A day | `GET /schedules/:id` (counts, active job, next due, the open `stop`) · `GET /schedules/:id/entries` (its charges, filterable) · `GET /schedules/:id/analysis` (every approval breakdown) · `POST /schedules/analysis` `{ ids[] }` for several days together |
| Run a day now | `POST /schedules/:id/jobs` `{ kind: 'force' \| 'sample', atriId?, midId? }` → `202 { job }` then poll `GET /jobs/:jobId` (progress, live `logs[]`) · `POST /jobs/:jobId/pause` / `resume` / `cancel` |
| Edit a day | `POST /schedules/:id/override` `{ field: 'run_day', to: 'YYYY-MM-DD' }` (move / merge the day) or `{ field: 'amount_cents', to }` (its pending charges) — the day shows "(edited)" with the history |
| Pause / resume / cancel a day | `POST /schedules/:id/pause` · `POST /schedules/:id/resume` · `POST /schedules/:id/cancel` — see "Pause, resume, cancel a day" below |
| Retry a decline reason | `POST /schedules/:id/retry-reason` `{ reason }` — the declined charges with that reason go back to pending (a done day reopens) |
| Charges of a day, in bulk | `GET /schedules/:id/entries/ids?<the list's filters>` → `{ ids, capped }` then `POST /schedules/:id/entries/bulk` `{ entryIds[], action: pause \| resume \| cancel \| change_subscription \| amount \| cancel_charge \| credential_mode \| route, credentialMode?, route?, … }` |
| Several days, in bulk | `POST /schedules/bulk` `{ ids[] (≤ 1 000), action: pause \| resume \| cancel \| route, route?, preview? }` — see "Pause, resume, cancel a day" |
| Route overrides | `POST /schedules/:id/route` `{ route }` (a day) · `entries/bulk` action `route` (charges) — see "Change ATRI / Gateway" |
| Retry profiles | `GET/POST /profiles`, `GET/PUT/DELETE /profiles/:id` (scope: all declines or insufficient funds only; delay; amount) · `POST/DELETE /decline-map` (which decline strings count as insufficient funds) |
| Settings | `GET/PUT /settings` — dispatch on/off, retry on/off, Safe-Guard (`safeguardEnabled`, `safeguardMinCharges`, `safeguardMinArPct`), the stored-credential wire (`mitEnabled`, `mitPct` 0..100 — the share of subscription charges sent MIT, fixed per order; a charge whose sale was not an NMI card sale stays CIT; one charge is forced with `entries/bulk` action `credential_mode`), timezone display; `PATCH /routing-constraints` + `GET /routing-constraints/feasibility` — the rebill routing constraints (v3.9.2 §3): five dimensions (MID · gateway category · acquiring bank · processor · company) × three states (no constraint · never the same as any previous charge · always the same as the initial charge), the order the rules are dropped in when nothing is left (a rebill is never refused by them), the pool size the page warns under; the outcome of every constrained charge is on `transactions.rebill_routing` and in the customer Logs (`rebill.routing.constrained` / `rebill.routing.relaxed`). The former Same-MID toggle is the MID dimension in state "always the same as the initial charge" |
| Monitoring | `GET /monitoring?period=1m\|3m\|6m\|1y\|2y\|all` — active subs, new / lost per day, monthly churn (lost ÷ sub-months, payment vs voluntary), approval, MRR (Σ active amount × 43200 / interval_minutes) and expected MRR (× 1 − churn), revenue net of refunds and chargebacks, expected LTV / lifetime / paid charges per sub (ARPU ÷ churn, lifetime capped at 60 months), retention by cycle among the subs at risk, why subs end, revenue by product, the legacy engine apart |

#### Simple and Advanced plans

A product's **Plan** switch (Offer tab) is **Simple** — one price, the first charge N after the sale, then every M (what every
product was before v3.9.15) — or **Advanced**: a list of intro cycles, then the recurring price.

- **A cycle** = an amount, a delay and what the delay counts from: **the sale** or **the previous cycle** (the previous paid
  charge). Cycle 1 always counts from the sale. **× repeat** charges the same cycle several times, each one the same delay after
  the one before. Add, remove and reorder cycles freely (up to 24 cycles, 60 charges).
- **Then** = the recurring price every interval, after the last intro cycle — the sub's own amount (the "Recurring amount" on a
  sub). **Max cycles** counts every paid charge, the intro included (empty = forever).
- **Simulation** — under the builder, the first 12 charges for a sale made now: the day, the date, the amount, the rule that
  placed it and the running total. It is the engine's own calculation, so what you see is what will be charged.

The operator's three examples (a sale on 2026-09-29 at 10:37 New York):

| Plan | Charges |
|---|---|
| $19 after 3 days of the sale, then $49 every 30 days | Oct 2 $19 · Nov 1 $49 · Dec 1 $49 … |
| $19 after 2 days of the sale · $29 after 6 days of the sale, then $49 every 30 days | Oct 1 $19 · Oct 5 $29 · Nov 4 $49 … |
| $19 after 6 days of the sale · $39 after 6 days of the previous cycle, then $49 every 30 days | Oct 5 $19 · Oct 11 $39 · Nov 10 $49 … |

What to know:

- **Live subs keep their plan.** A sub copies the product's plan when it is created; editing the product's plan changes new
  subs only (like its price). Moving a sub to another product gives it that product's plan — its cycle count continues.
- **Retries keep the cycle.** A declined intro cycle is retried at that cycle's amount (a retry step with no amount = "The
  cycle's amount"); a fixed down-sell step keeps its own amount.
- **Never two charges too close.** A cycle counted from the sale never lands less than 24 hours (or the gap you set between
  the two cycles, if shorter) after the previous paid charge — a retried or late cycle pushes the next one.
- **A pause.** A sub paused across several cycles counted from the sale gets them back to back after the resume, 24 hours apart
  (e.g. $19 after 2 days · $29 after 6 days · $39 after 12 days, all of the sale: $19 paid Oct 1, paused, resumed Oct 21 →
  $29 Oct 21, $39 Oct 22, then $49 every 30 days).
- **Max cycles** cannot cut a plan's intro: a value below the intro, or one that would end live subs inside the intro they took,
  is refused.

#### 4. Reading a day's status

| status (API) | chip (dashboard) | meaning |
|---|---|---|
| `pending` | **Scheduled** — or **Starts HH:MM** on the day itself while the first slot is ahead | nothing decided yet. A past day whose charges never went out reads **Partial** |
| `dispatching` | **Processing** | a Force bill / Sample job is running |
| `partial`, the day still running | **Processing** | its New York day is not over and no Force bill ran through it — whatever happened so far: charges decided and charges pending, a lull between two charges, a technical error the engine re-planned, a Sample that ended |
| `partial`, the day finished | **Partial** | its New York day is over, or a Force bill ran through it (`stats.force_ended`), and it is not complete: charges still pending (subs added meanwhile — §5), **unresolved technical errors** (`stats.errors` — timeout, no eligible MID, gateway 5xx, unresolved outcome, and no later attempt of the same charge), charges never dispatched (`stats.missed`) |
| `done` | **Done** | every charge was decided by the gateway on a finished day — a subscription day closes once its New York day is over or a Force bill ran through it; an unresolved technical error or a missed charge keeps it Partial: retry the reason (`POST /schedules/:id/retry-reason`) or let the dispatcher finish, and it becomes done |
| `paused` | **Paused** (orange) | stopped by an operator: nothing of the day is sent — its charges stay planned, its subs active; *Resume* sends it again |
| `cancelled` / `error` | **Cancelled** / **Error** | stopped by an operator or Safe-Guard; *Resume* restores exactly the charges and subs the cancel stopped |

##### Force bill twice

A Force bill never re-charges what was already sent. The job only claims charges that are
**pending**, that are the sub's **current** charge, and that **existed when the job started**;
paid, declined, scrubbed, cancelled and missed charges are not even considered, and every charge
carries an idempotency key so a replay of the same charge is never a second payment. Running Force
bill on a day that already ran charges exactly: the subs added since, the declines you reset with
*retry reason*, nothing else.

##### Force bill one sub

`POST /subs/:id/charge-now` (admin+) charges **one** sub right now through the dispatcher's own
claim-then-charge path: a paused / failed sub is resumed first, a charge planned for later is
re-planned at now (the old entry is cancelled, the next cycle counts from today), the entry is
claimed atomically (never under a manual job, never while a charge is in flight) and the verdict —
`kind` success / failed / rejected / cancelled / requeued / reverted / flow_paused / flow_cancelled /
flow_postponed / flow_skipped / flow_ended, `reason`, `midName`,
`transactionId`, `amountCents` — comes back with the refreshed sub; the day's history records
`force_bill_sub`. Refused (423) while the account's dispatch switch is off, and (422) while the
sub's charge sits in a paused day. The customer view's **Force bill** opens a modal — the charges,
the card, the route — and calls it once per live sub, one after the other.

The five `flow_` kinds are the answer for a product in the Rebill Flow mode (see "Routing modes and Rebill
Flows" below) whose flow settled the charge without sending it: `flow_paused` (the flow paused the sub),
`flow_cancelled` (the flow cancelled the sub), `flow_postponed` (the charge is planned again later, its action
"Retry later" or "Change the bill date"), `flow_skipped` (the charge moves to the next billing date and keeps
its cycle number, its action "Skip this cycle"), `flow_ended` (the sub ended as declined: its action "End as
declined", or the limit of 15 failed attempts in a cycle). Nothing was sent: `midName` and `transactionId` are
null, and `reason` is the reason written on the charge, one of six: `Rebill Flow: paused`,
`Rebill Flow: cancelled`, `Rebill Flow: retry later`, `Rebill Flow: bill date changed`,
`Rebill Flow: cycle skipped`, `Rebill Flow: ended as declined`. They are answers, not errors. A Force bill
with an ATRI or a MID route skips the flow, and so does a route override of the charge or of its day: the flow
decides only when "Use original" reaches the product. With "Use original" and a confirmed amount, that amount
is charged: a price block of the flow does not change it.

##### The route of a Force bill

Every Force bill — one sub (`POST /subs/:id/charge-now`), a day (`POST /schedules/:id/jobs`, Force
bill or Sample) or several days (the bulk Force bill) — takes a route:

| route | body | the charge goes |
|---|---|---|
| **Use original** (default) | nothing | the charge's own route: its route override, else its day's, else its schedule's ATRI split — the product's — or the account's default ATRI: exactly what the engine would do (see "Change ATRI / Gateway" below). The modal shows it: each sub's ATRI split (`product_atri_split` on the sub rows), its original order's MID and its last charge's MID |
| **ATRI** | `{ "atriId": "…" }` | through that ATRI — its routing chooses the MID |
| **MID** | `{ "midId": "…" }` | on that MID only — the only attempt, no cascade (like a Retry on a MID), inside the ATRI that holds it (the product's own first) |

A wrong route is refused before anything is charged (`422`: unknown or inactive ATRI, unknown or
disabled MID, a MID in no active ATRI, both given — and since v3.9.15 a wallet (ConvesioPay) MID or an
ATRI whose only MIDs are wallets: a card-on-file rebill never goes to a wallet; the pickers do not offer them). A chosen MID still obeys the rebill routing
constraints, its monthly cap and the card's brand: when they rule it out the charge is not sent —
a technical error, no cascade. The route is for this Force bill only: a retry the engine plans
afterwards takes the original route. `charge-now` answers the route it took in `route`; a job
keeps it on `job.route` and its console's first line names it.

##### Pause, resume, cancel a day

| action | call | what happens |
|---|---|---|
| **Pause** | `POST /schedules/:id/pause` — a pending / partial day, no job running | The day stops sending and nothing else changes: its charges stay planned, its subs stay active and pinned to them, nothing is marked missed, Safe-Guard waits. A charge already in flight finishes. The chip reads **Paused**. A Force bill or a Sample on a paused day is refused: resume it first |
| **Resume** | `POST /schedules/:id/resume` — a paused, cancelled or errored day | A paused day sends again. A cancelled day gets back **exactly** what its cancel stopped: the charges it cancelled and the subs it paused — a sub you resumed, moved or cancelled since keeps its own state, and one subscription per customer still applies (a refused sub stays paused, listed in `refused`). Never a burst: the slots already past are spread over the rest of today, an older day's charges move into today (into the product's day of today when it exists), a future day waits for its day → `{ status, restored, resumed, refused, respread, moved }` |
| **Cancel** | `POST /schedules/:id/cancel` — no job running (`cancel-processing` stops the job too) | Its planned charges are cancelled and the subs pinned to them paused — both **recorded**, so *Resume* puts back exactly them. A charge in flight finishes and keeps its result |

`GET /schedules/:id` returns `stop` — who stopped the day, when, and for a cancel how many charges
and subs it stopped; the day's Details show the same line. `POST /schedules/:id/uncancel` is the
older name of *Resume*, for cancelled days only. In the dashboard: **Pause** / **Resume** /
**Cancel** in the day's Actions, the list's row menu and the /subscriptions/schedules bulk bar; the Resume
toast says what came back and where the day's charges went.

**Several days at once** (v3.9.15): `POST /schedules/bulk` `{ ids (≤ 1 000), action: pause | resume | cancel | route, route?, preview? }`
→ `{ results: [{ id, ok, skipped?, error?, detail?, … }], summary }`. Each day runs the single call's
own rules and audit (the row menu's eligibility: a done day is skipped, a day with a running job is
skipped for pause / cancel / route); `preview: true` writes nothing and says which days are eligible
and why the others are skipped — the bulk modal shows it before you confirm, then lists every day
once in its Report (done · skipped · failed). Several past days resumed together keep today's rule:
each merges into today, the oldest first. A Resume's preview counts the charges it would put back
(a cancelled day's charges wait as cancelled until then) — at most: the Report gives the exact
count. *Change date* and *Change amount* show the same Eligible / Skipped count before you apply
(a finished day, a day being sent or with a running job, a day already on that date is skipped).

##### Change ATRI / Gateway — the route overrides (v3.9.15)

A **route override** makes charges go to an ATRI (its pool, its cascade) or a MID (the only attempt,
like a Force bill on a MID) until you change it — the chip reads *Route: Main Rebill* / *MID: Acme 3*.

| level | call | scope |
|---|---|---|
| a **day** | `POST /schedules/:id/route` `{ route: { atriId } \| { midId } \| null }` · or `POST /schedules/bulk` `{ ids, action: 'route', route }` | every charge of the day (unless it has its own). Refused on a done / errored day and while a job runs (`409 A job is running`). The answer says how many charges keep their own route (`keepOwn`) |
| a **charge** | `POST /schedules/:id/entries/bulk` `{ entryIds, action: 'route', route }` (the Subs tab's *Change ATRI / Gateway*, or the *Route* field of its Edit) | the selected charges still scheduled. It follows the charge's own cycle — its retry, a re-plan after an amount / product change — never the next cycle |

`route: null` = **Use original** = clear that level (a charge then takes its day's route, a day its
ATRI split). Admin only. At each charge the most specific level wins — a Force bill's route, then
the charge's override, then the day's, then the ATRI split — and it is checked again then: a MID
deactivated or out of every active ATRI since, an ATRI disabled or left with only wallets, falls back
to the next level; the charge's pipeline (Transaction → Pipeline → *rebill rules*) says so.

A MID override is still the only attempt: a charge over the MID's monthly cap, of a card brand it
does not accept, or excluded by a rebill rule **errors** — it never falls back — and the same cycle's
retry keeps the override, so change or clear it when the MID is full (the picker shows the MID's cap
usage and brands and warns). Transaction → Pipeline → *route* names the cause. Moving a day onto
another (Resume of an older day, Change date) keeps every charge's route; a charge whose former day
had no route and several ATRIs takes the target day's route and is counted in the Report.

#### 5. A finished day that grows — "Partial"

A day can be finished — force-billed through, or its New York day over — and *then* receive
charges: a sale whose first charge falls on that day, a declined charge you reset to pending, a
re-run. Nothing is lost and nothing runs twice:

- the charges already sent keep their result; the new ones are **pending** on the same day;
- the day flips to `partial` and stamps `reopened_at` (`reopened_count` counts the reopenings);
  the dashboard shows it as **Partial** (violet), the hover and the day's Details say when. A day
  still running that receives a charge is not reopened — it stays **Processing** and goes on;
- the new charges go out **at their slot** by the automatic dispatch (the day is today or
  yesterday) or with the next **Force bill** — whose budget is *the charges that exist when it
  starts*, so a retry the engine plans during the run keeps its own slot;
- once nothing is pending the day reads **Done** again. Its history carries a `reopened` line.

#### 6. What never happens

- A wallet sale never becomes a sub; a customer refunded, charged back or blacklisted is never
  re-attached; a sub that ended on purpose stays ended.
- An opt-in product (v3.9.17) is never attached to a customer who did not tick it at checkout — unless an operator attaches
  it to that one order by hand.
- A charge is only sent while it is the sub's **current** charge — an orphan entry (re-planned,
  edited, paused) is never charged: one cycle, one charge.
- A product edit never rewrites a sub's agreed amount; a schedule override never rewrites the
  product.
- A day never bursts when it resumes: what is past is spread over the rest of today.

#### 7. Where the numbers are

- **A day's Analytics** (`GET /schedules/:id/analysis`, the day's Analytics tab; several days:
  `POST /schedules/analysis` `{ ids[] }`, the bulk Analytics) — every approval breakdown of the
  day's charges, in five tabs (`?view=` on the day's page): **Subscription** (subscription
  product, cycle, price point, original sale price, hour) · **Routing** (MID, gateway category,
  MCC, acquirer, processor, company — read from the charge's own MID; `(no gateway)` = a charge
  refused before any MID or that ended on none) · **Cards** (bank = the issuer, brand, type,
  level, BIN) · **Traffic** (the original sale's traffic source, store, product, country, device,
  OS) · **Declines** (per decline category, and the decline reasons with their Retry).
- **Reports → Subscription → Charges** (`GET /v1/metrics/segments?mode=rebill`) — the same
  families over a date range, in tabs in the filter bar (`?view=`): **Subscription** (Per
  Subscription Product, Per Cycle, Per Price Point (order), Per Initial Order Value, Per Hour) ·
  **Routing** (Per MID, Per Gateway Category, Per MCC, Per Acquirer, Per Processor, Per Company) ·
  **Cards** (Per Bank (issuer), Per Card Brand, Per Type of Card, Per Card Level) · **Traffic**
  (Per Traffic Source, Per Store, Per Original Product, Per Geo, Per Device, Per OS) · **Profiles**
  (the best and the worst value of every table). Every count opens the `/transactions` list of
  the rows it counts; `(unset)` = a MID without that reference, `(no gateway)` = a charge that
  ended on no MID.

#### 8. Filters on the subscription pages (v3.9.15)

`/subscriptions/subscribers`, `/subscriptions/schedules`, a day's Subs tab, Logs → Subscription charges and Reports → Subscription use **the one filter bar** of
every report: the whole catalog, grouped and searchable, the same keys as `/transactions` (see *Filters* in *Reporting*,
Part 2). A key a row cannot carry itself reaches it through its charges — **a sub, a day or a charge matches when at least one
of its charges matches** — and a filter that contradicts the page (Source = Straight on a subscription page) gives zero rows, never
an ignored filter. The filters and the range stay in the address.

- **/subs** — the range is *had a charge in the range*, **All time** by default; the page opens on `subStatus=active` (written in
  the address — Clear keeps an empty `subStatus=`, every status). *Attached by* is the old *Source* of a sub; *Source* is now the
  charge's Straight / Subscription, as everywhere.
- **/schedules** — the bar drives both tabs: the List (its range = run days) and the Calendar (its month). Under a filter each
  day's Success · Declined · Blocked · Pending (and the Total row) count **the day's matching charges** and open exactly them; the
  Calendar's chips stay the whole day and say so ("Whole day").
- **A day's Subs tab** — the charges of the day (the quick search = e-mail, name or order id; a charge-date range, All time by
  default). Details reads the matching charges too; *Volume per hour* and Analytics stay the whole day (the "not filtered" mark).
- **Logs → Subscription charges** — the same bar; its KPI cards open their `/transactions` list under every filter.
- A figure's link carries every applied filter, intersected with its own; a quick search on a charge, a sub or a cart has no
  `/transactions` equivalent, so those figures are plain text while it is set.

#### 9. Routing modes and Rebill Flows

A subscription product routes the charges of its subs in one of three modes, the body key `routingMode` of
`POST /v1/subscription/subscriptions` and `PUT /v1/subscription/subscriptions/:id`:

| mode | where a charge goes |
|---|---|
| `atri` | the product's ATRI split (`atriSplit`), else the account default ATRI. Every product created before Rebill Flow is in this mode |
| `gateway` | the gateway of `routingGatewayId`, as the only attempt |
| `rebill_flow` | the Rebill Flow of `rebillFlowId` decides each charge |

The mode is read when a charge is dispatched: a switch applies to the next charge of every sub of the product, and nothing
planned is rewritten. `atriSplit`, `routingGatewayId` and `rebillFlowId` are stored side by side, so switching back restores
what was there. A Force bill route, a charge override and a day override still win over the product.

`atriSplit` also counts outside the `atri` mode. A pinned gateway is charged under an active ATRI of the split that holds
it, else under the account default ATRI when it holds it, else under the oldest active ATRI that does. And a flow can send
a charge to the split with its action `charge_product_atri`.

A Rebill Flow is a graph: an Entry point, condition blocks (outputs matched and unmatched), switch blocks (cases checked in
order, then "Otherwise"), split blocks (weighted branches) and action blocks. A charge block sends the charge and has three
optional outputs: "If unavailable" (its target cannot be used), "If approved" and "If declined" (followed after the bank
answered: the flow then decides the retry, a new date, a pause, a cancel or the end as declined, in place of the retry
profile). "Change the price", "Change the frequency" and "Add a note" change the subscription and let the walk go on: what
they change before a charge or after a decline is kept for the cycle and saved when a charge of the cycle is approved.
"Retry later" and "Change the bill date" plan the charge again and can go on from their "Then" output at that try. The other
blocks end a path: skip the cycle, use the retry profile (after a decline only), pause, cancel, end as declined. A cycle has
at most 15 failed attempts in this mode: the 15th ends the subscription as declined.

A flow is edited as a draft and takes effect when it is published; the engine always runs the published version. The ids a
graph names (a gateway, an ATRI, a product) are written in lower case, as the API answers them: an id in upper or mixed case
is refused at save (400).

A price a flow keeps for a cycle belongs to the amount it was computed from. When you set another amount meanwhile (on the
sub with `PATCH /v1/subscription/subs/:id`, or on its planned charge), your amount is charged and stays; the kept price is
not applied over it. A frequency a flow gave a sub is cleared with `PATCH /v1/subscription/subs/:id` `{ "resetFrequency": true }`.

| task | call |
|---|---|
| List or create | `GET /v1/subscription/flows`, `POST /v1/subscription/flows` `{ name }` |
| Read the choices of the pickers | `GET /v1/subscription/flows/options` |
| Edit | `GET /v1/subscription/flows/:id`, then `PUT /v1/subscription/flows/:id/draft` `{ graph, baseRevision }` (409 when another save came first) |
| Publish | `POST /v1/subscription/flows/:id/publish` `{ baseRevision, note? }` (422 names the block to fix) |
| Test without charging | `POST /v1/subscription/flows/:id/preview` `{ source?, graph?, subId?, facts?, at?, startAt?, pending?, result?, resultFacts? }`: `startAt` and `pending` test the next attempt of a cycle, `result` (`approved` or `declined`, with `resultFacts`) also answers what the engine would do after the bank's answer (`after`) |
| Route a product through it | `PUT /v1/subscription/subscriptions/:id` `{ "routingMode": "rebill_flow", "rebillFlowId": "<id>" }` |
| See what it decided | `GET /v1/subscription/flows/:id/activity` |
| Resume what it paused | `GET /v1/subscription/flows/:id/paused`, `POST /v1/subscription/flows/:id/resume-paused` |
| Go back to a version | `GET /v1/subscription/flows/:id/versions`, `POST /v1/subscription/flows/:id/versions/:version/restore`, then publish |
| Copy, rename, archive | `POST /v1/subscription/flows/:id/duplicate`, `PATCH /v1/subscription/flows/:id`, `DELETE /v1/subscription/flows/:id` |

Moving a product away from its flow resumes the subs that flow had paused, unless the body says `"resumeFlowPaused": false`.

The last resort of the `gateway` and `rebill_flow` modes is the account default ATRI: a charge that cannot use its target
is sent there. On an account with no active default ATRI that charge fails, and the API says so beforehand: a product save
in one of these two modes answers `warnings`, and the publication of any flow answers the warning `default_atri_missing`.

### Bulk operations, Retry and Add charge

#### Configuration tables — 5.2 beta

Select records, then **Actions → Edit**. Only checked fields are applied. Every table also offers selected-row CSV/PDF export; reports, logs and simulations do not offer invented edits to derived figures.

| Configuration | Editable together | Existing endpoint |
| --- | --- | --- |
| Email / SMS providers | Enabled, weight, daily/monthly caps | `PUT /v1/messaging/{email|sms}-providers/:id` |
| Recovery templates | Enabled | `PUT /v1/recovery/templates/:id` |
| Recovery sending profiles | Reach %, delay, link validity, minimum cart, quiet hours | `PUT /v1/recovery/profiles/:id` |
| Recovery store/channel bindings | Sending ON, OFF or store default | `PUT /v1/recovery/bindings` |
| Retry profiles | First-attempt delay in hours and amount in cents | Read `GET /v1/subscription/profiles/:id`, then full `PUT` of the current profile; later steps and routing stay intact |
| Members | Role, excluding yourself and the main account | `PUT /v1/users/role` with `{email, role}`, one member per call; only a key whose scopes are unrestricted |
| BIN profiles | Enabled, description | `PUT /v1/bin-profiles/:id` |
| Gateway categories | Add a prefix/suffix to each existing name | `PATCH /v1/categories/:id` |
| Refund search results | Add a note to selected charges | `POST /v1/transactions/:transactionId/note` with `{ "note": "..." }`, trimmed 1 to 2,000 characters |
| Refund log | Chargeback/dispute classification or cancel active test refunds | `POST /v1/refund/chargeback` with `{ "refundId": "...", "chargeback": true/false }`; `POST /v1/refunds/:id/dispute` with `{ "kind": "rdr"/"ethoca"/null }`; `POST /v1/refund/cancel-test` with `{ "refundId": "..." }` |

Example: setting a provider's daily cap and disabling it sends `{"daily_cap":1000,"enabled":false}` to its existing PUT endpoint. Credentials, counters and unselected fields are absent. These operations do not send test messages or initiate charges.

Refund classification validates the whole selected population before the first request and asks for confirmation. Only successful refunds may be reclassified; existing chargebacks must be unmarked before changing dispute labels. RDR is selected for Visa and Ethoca for Mastercard. Marking chargeback changes report buckets and blacklist reason; dispute labels retain refund accounting and blacklist the customer for the alert. Cancelling test refunds rejects real refunds and already-cancelled rows. The server checks ownership and current eligibility again. Monetary refunds retain their individual amount/reason confirmation form.

Item writes run with at most six concurrent requests. Successful writes remain applied when another item fails. The result report lists each selected ID and its outcome; refresh the data and retry only failures. An API error does not become a successful bulk operation. Existing per-item roles, scopes, ownership and validation apply unchanged.

For **draft tables** (ATRI membership, API-key permissions and Friendlies costs), bulk Edit updates the enclosing form's draft. Use that modal's **Save** to persist all changes; closing without saving does not write them.

Selection is limited to loaded/filter-matching records unless that inventory has an explicit all-matching ID endpoint. A generic selected-row export must not be interpreted as fetching an unbounded server dataset.

What the dashboard's bulk bar does, as API calls — so an automation can do the same. Every route
is account-scoped and takes an API key of the account. Ids are UUIDs, at most **10 000** per call.

#### 1. The pattern: `ids` then `bulk`

Selecting "all N matching" in the dashboard is two calls: the **ids** endpoint with the same
filters as the list, then one **bulk** call with those ids. The list and the ids endpoint share
one filter parser — v3.9.15: THE unified catalog, the same keys on every list (see *Filters* in *Reporting*,
Part 2; an unknown key is a 400) — so what you see is what you act on.

| entity | ids | bulk action |
|---|---|---|
| Transactions | `GET /v1/transactions/ids?<same filters as GET /v1/transactions>` → `{ ids, capped }` | `POST /v1/transactions/bulk` `{ ids[], action: blacklist \| attach_subscription \| cancel_subs \| note, reason?, subscriptionId?, note? }` |
| Subs | `GET /v1/subscription/subs/ids?<same filters as GET /subs>` → `{ ids, capped }` | `POST /v1/subscription/subs/bulk` `{ ids[], action: pause \| resume \| cancel \| change_subscription \| amount, subscriptionId?, keepAmount?, amountCents?, reason? }` |
| Charges of one day | `GET /v1/subscription/schedules/:id/entries/ids?<same filters as GET …/entries: the catalog — entryStatus, entryReason, q, every other key>` → `{ ids, capped }` | `POST /v1/subscription/schedules/:id/entries/bulk` `{ entryIds[], action: pause \| resume \| cancel \| change_subscription \| amount \| cancel_charge \| credential_mode \| route, credentialMode?: mit \| cit \| auto, route?: { atriId } \| { midId } \| null, … }` (`route`: admin only — the charges' route override) |
| Schedules (days) | `GET /v1/subscription/schedules/ids?<same filters as the list: the catalog — q, scheduleStatus, scheduleType, subscription (CSV), from, to (run days), every other key through the day's charges>` → `{ ids, capped }` | `POST /v1/subscription/schedules/bulk` `{ ids[] (≤ 1 000), action: pause \| resume \| cancel \| route, route?, preview? }` → `{ results, summary }` (`route`: admin only; `preview: true` = the eligibility, nothing written) · one call **per day** for the rest: `POST /schedules/:id/override` (date, amount) · `POST /schedules/:id/jobs` (force bill, `{ kind: 'force', atriId? \| midId? }` — the route) · `POST /schedules/analysis` `{ ids[] }` (one analysis over several days) |
| Clients (v3.9.15) | `GET /v1/customers/ids?<same filters as GET /v1/customers>` → `{ ids (the e-mails), capped }` | `POST /v1/customers/bulk` `{ emails[], action: blacklist \| unblacklist \| pause_subs \| resume_subs \| cancel_subs \| allow_multi \| forbid_multi, preview?, reason?, subscriptionId? }` → `{ results, summary }` (blacklist / unblacklist: admin only; `preview: true` = the counts, nothing written) |
| Gateways, ATRIs, wallet providers, API keys, stores, BIN rules, subscription products | the list rows | one `PATCH` / `PUT` per id with the same body — the dashboard fans the calls out (a few at a time) and reports each result |

`capped: true` means the ids endpoint stopped at 10 000: narrow the filters.

Every bulk response lists what happened per id (`ok` / refused with the reason) — a refused id is
never a partial write: the others still applied.

#### 2. Retry declined sales

`POST /v1/transactions/:id/retry` `{ atriId? | midId? }` — re-charges the declined **card**
sale `:id` with the card on file, as the account itself (the new attempt is recorded under the account, not under an API key): the original
customer, IP, user agent and currency travel with it. Choose an ATRI (the normal routing, with
its cascade) or a single MID (stays on that MID, no cascade). The response is
`{ ok, approved, midName, amountCents, declineReason, transactionId }` — the id of the new
attempt. The dashboard's bulk Retry is
this call, one id at a time, with a live console and a summary (retried / recovered / amount /
declined / errors).

Only NMI card sales that are declined can be retried; a wallet sale, an approved sale or a
subscription charge is refused with `422`.

#### 3. Add charge

`POST /v1/transactions/charge` — a sale from the dashboard (the **Add charge** button of /transactions — v3.9.15, was *New charge*): the same customer / order /
attribution fields as `/v1/charge` plus a **required card** (`ccnumber`, `ccexp` MMYY, `cvv`)
and the route (`atriId` or `midId`, never both). Card fields are validated as digits and never
echoed or logged. The charge is attributed to your account (`transactions.owner_email`) and
attaches subscriptions exactly like a checkout sale would.

#### 4. Where the dashboard puts these

Every table with checkboxes shows one fixed bar while something is selected: `N selected` ·
*Select page* · *Select all N matching* · one orange **Actions ▾** menu listing every bulk action
of that table (Edit, Retry, Force bill, Pause, Resume, Change ATRI / Gateway, Change date, Change amount,
Analytics, Cancel, Remove… — v3.9.15: *Change status* is gone) · ✕. Each action opens its own modal or confirmation — the menu itself never does the
work.

#### 5. The card in clear — admins only

An **admin** (admin / super_admin) sees the card in clear in the Order view (the transaction
modal: Customer tab *Card*, Payment tab *Card* — *Card on file* on a subscription charge) and in
the Customer view (Details *Card*): number · expiry · holder, with Copy. One call per charge:
`GET /v1/transactions/:id/card` → `{ card: { number, expiry, holder, brand, last4, source:
'charge' | 'card_on_file', transactionId } | null }` — the charge's own card, else its order's
card on file (a subscription charge carries none of its own); `null` for Apple Pay / Google Pay.
Only a person signed in as an admin gets it: an API key and the user / refund roles get `403`.
The answer is never cached and every reveal is a row of the Action logs (`view_secret`, the fields
named, never a value). The security code is never shown.

Every other role receives the card numbers masked `first6..last4` — in every account API answer and
in the transactions CSV — and no security code. Nothing changed in what is stored.

### Clients

**Customers** (`/customers`) lists every client of the account: one row per e-mail, with its figures, its
subscriptions and its blacklist state. It is filtered like every report, every figure opens the transactions behind it, and the
bulk bar pauses, resumes or cancels subscriptions and blacklists clients. A row opens the **customer view**.

The page and the calls behind it are the `GET /v1/customers*` endpoints (the endpoint reference, Part 4, group **Clients**).

#### 1. What a client is

- A client is **one e-mail** of the account (`lower(email)`), with at least one **live** charge (not a test card, not an
  imported order). Two orders with the same e-mail are one client, whatever the card.
- Charges without an e-mail are **not clients**. Neither is an e-mail value without an `@`: it could never be opened in
  Transactions by its exact e-mail.
- The list is keyed by e-mail. The **customer view** is wider: it merges the e-mail **and** the card, so its Subscription tab can
  show a sub of another e-mail that paid with the same card.
- The scope is the account's, like `/transactions` (the ATRI view included). The customer view's History uses the account scope,
  so in rare cases one row can differ from the list.

#### 2. The columns

| Column | What it counts |
|---|---|
| Customer | The client's latest name, and its e-mail |
| Country, Card, Last storefront | From the client's **latest live charge** (or the latest charge of the applied Population). They are lifetime facts: a Storefront filter does not change "Last storefront" |
| Orders | The distinct orders of the matching charges |
| Charges · Approved · Declined · Approval % | The matching charges: completed ones, approved, declined (declined + error), approved ÷ completed |
| Gross | The approved amount of the matching charges |
| Refunds · Chargebacks | **Refunded charges** and **charged-back charges**. An RDR / Ethoca alert is a refund. Two partial refunds of one charge count once |
| Refunded $ · Charged back $ | The sum of the refund **events**. Two partial refunds add up. Charged back $ is hidden by default and always exported |
| Net | Gross − Refunded $ − Charged back $, **before fees** (not the Finance report's Net) |
| Subs | Live subs / all subs of the e-mail (live = active or paused), lifetime |
| Tags | **Blacklisted** (its e-mail, or a card it paid with, is on the blacklist) · **Manual** (several subscriptions allowed) |
| First seen · Last seen | The client's first and latest live charge, lifetime |
| Email · Phone · Latest order | Hidden, always exported. Phone is the one column you cannot sort: its value lives only inside each charge |

- The **Total** row is the whole filtered list, never the page. Approval % is recomputed from the totals.
- Every column sorts on the server (default: Last seen, newest first). The pager goes up to **All** (10 000 rows a page).
- The "i" mark says which charges the figures count; it follows the Source and Cycle filters, like `/transactions`.

#### 3. Filters

The bar is **the one filter** of every report: every key of the catalog, grouped and searchable.

- A **charge filter** (MID, Source, Status, Storefront, dates…) keeps the clients with **at least one matching charge**, and the
  figures (Orders → Net) then count only those charges. Refund figures count the refund events of those charges.
- The **Client** group filters the clients themselves, on lifetime live facts: Client e-mail (exact), Blacklisted, Live
  subscription, Lifetime orders min / max, Lifetime value min / max ($), First seen, Last seen. These keys work on every other
  report too: `/transactions?clientOrdersMin=2` lists the charges of repeat clients.
- There is **no date picker**: the list is lifetime. A link that carries `from` / `to` (a range) applies it; **All time** removes it.
- The quick search matches the e-mail, the name, an order id, a phone (6 digits or more) and the last 4 digits of a card.
  It starts at **3 characters**, 400 ms after you stop typing. A last 4 or a phone number is searched when you press **Enter**.
- The filters and the search stay in the address: a link opens the same list.

#### 4. Drill-through

Every count and amount opens `/transactions` in a new tab. The link carries:

- the client's **exact** e-mail (`customerEmail`, never the "contains" e-mail filter);
- the applied filters;
- the figure's own status or refund kind, intersected with an applied one;
- the applied Population, else **live**.

The range runs from the day of the client's first counted charge (`drill_from`) to today, or uses the page's range when one is
applied. The list then shows exactly the rows the figure counts. A figure that no row of the applied filters can match (Declined
under Status = Approved) is plain text, not a link.

The quick search only picks the clients: a row's figures never depend on it, so the links stay live under a search and do not
carry it (the exact e-mail already names the client).

#### 5. Bulk actions

Select rows (or **Select all N matching**, up to 10 000). The **Actions** menu offers:

| Action | Who | What it does |
|---|---|---|
| Pause subs | admin, user | Pauses every **active** sub of each client |
| Resume subs | admin, user | Resumes every **paused or failed** sub, if the one-live-sub rule allows it |
| Allow / Forbid several subscriptions | admin, user | Sets the client's flag for that rule |
| Blacklist | **admin** | Adds the e-mail and every card the client paid with (up to 10). Its live subs end |
| Remove from blacklist | **admin** | Removes every active blacklist row of the e-mail and of its cards |
| Cancel subs | admin, user | Cancels every active, paused or failed sub. Their pending charges are dropped |

Each action opens a modal that first asks the server what it would do, without writing anything. It shows the Eligible and
Skipped clients with the reasons counted, and what lies behind them:

- the subs it touches, and how many of them are **on other products** than the Product filter;
- for Resume, the subs the one-live-sub rule refuses;
- for Blacklist, the rows it adds and the subs that end.

**The actions are client-level:** they touch every sub of each e-mail, whatever the list's filters.

The button says exactly what runs ("Cancel 37 subs of 12 clients — 4 on other products"). After the run, the **Report** lists
every selected client once: done, skipped or failed, with the reason.

Skip reasons you may see: `No active sub` · `No paused or failed sub` · `No sub to cancel` ·
`Holds another live sub — allow several subscriptions first` · `Already blacklisted` · `Not blacklisted` · `Already allowed` ·
`Already forbidden` · `Not changed` · `Not found` (no charge of that e-mail in your scope).

The same calls, for an automation:
`GET /v1/customers/ids?<the list's filters>` → `{ ids, capped }`, then
`POST /v1/customers/bulk { emails[], action, preview?, reason?, subscriptionId? }`.

#### 6. The customer view

Click a row (or any Customer entity) to open the customer view. It has five tabs:

- **Details** starts with the KPI strip: **LTV** (gross, with Net under it), **Orders**, **Approval**, **Refunds**,
  **Chargebacks**. The figures are the client's lifetime live figures, the same as its list row, and each card opens its
  transactions. Below it, the client's fields, including **Blacklist**: the badge for everyone; for an admin, one line per
  blacklist row (e-mail or card ··1234, date, source, by — the reason on hover).
- **Subscription** lists every sub of the client.
- **History** shows the latest **300** charges. When there are more, a notice says so and links to **Open in Transactions**.
- **Notes** lists every transaction note of the client, newest first. A row opens its transaction; an admin can delete a note.
- **Logs** is the client's timeline.

The Actions menu offers:

- **Force bill**.
- **Blacklist customer** (admin): the same preview and Report as the bulk, for this one client.
- **Remove from blacklist** (admin, when blacklisted).
- **Allow / Forbid several subscriptions**.
- **Add note**: pick one of the client's orders, write the note. Not for the `user` role.
- **Open in Transactions**: every charge of the client's e-mail.
- **Delete subs**.

#### 7. Export

**Export ▾ → CSV** downloads the whole filtered list, up to 150 000 rows. The dates are in the account's timezone, which the
header names. The card is masked for every role but admin. **PDF** prints the whole list when it has 10 000 rows or fewer, else
the page on screen; its subtitle says which.

A text cell that starts with `=`, `+`, `-` or `@` gets a leading apostrophe in the CSV, so a spreadsheet never runs it as a
formula. Numbers and amounts (a negative Net) are left as they are.

#### 8. Speed

The figures are computed live from the charges (no snapshot), so every figure equals its Transactions list.

- The default page takes about 2–3 s.
- Sorting by Card, Country or Last storefront, the Source and Country filters, and **All** take 3–6 s.
- A search by e-mail, name or order id takes about 1 s. A phone or last-4 search takes 1.5–2 s, which is why it runs on Enter.
- The full CSV takes about 10 s.

### BIN Intelligence

Three tools decide, per card, what happens BEFORE any MID is tried: **Mapping** (steer the card to a
pool of MIDs, a processor, an acquiring bank, an MCC or another ATRI), **Scrubbing** (refuse the charge
outright — a rejection, never a transaction) and **3DS** (force or skip the inline authentication). Each tool
is a set of **profiles**; a profile is an **ordered list of rules**; an ATRI selects at most one profile per
tool (ATRI › BIN tab, or `binMapProfileId` / `binScrubProfileId` / `binThreedsProfileId` on
`POST|PATCH /v1/trips`). Nothing fires until an ATRI selects the profile. Every route below is
account-scoped and takes an API key of the account; a foreign profile id is a `404`.

#### 1. Profiles

| call | what |
|---|---|
| `GET /v1/bin-profiles?kind=mapping\|scrubbing\|threeds` | the tool's profiles with `used_by` (the ATRIs selecting each), rule counts |
| `POST /v1/bin-profiles` `{ kind, name, description?, criteria?, enabled?, is_default? }` | create (`201`; `409` on a duplicate name for the kind) |
| `PUT /v1/bin-profiles/:id` · `PUT …/:id/default` · `DELETE …/:id` | edit · make it the default of its kind · delete (detaches it from its ATRIs, drops its rules) |
| `GET /v1/bin-profiles/:id` | the profile + `assignments` (when it was attached to which ATRI) |

A disabled profile is the tool switched off on the ATRIs that select it. A new **scrubbing** profile inherits
the account's RB-synced BIN list (`PUT /v1/scrub-bins` keeps replicating into every scrubbing profile) unless
its `criteria.rb_sync` is `false`. `criteria` are the Generate rules settings, never the live behaviour.

#### 2. Rules

A rule = **what it matches** + **what it does**, in a position. `GET /v1/bin-profiles/:id/rules` lists
them in evaluation order with the names the table shows (`targets`, `issuers`); `POST …/rules` appends one,
`PUT …/rules/:rid` edits, `PUT …/rules/order { ids }` reorders, `POST …/rules/bulk` enables / disables /
deletes a selection, `POST …/rules/:rid/duplicate` copies.

##### What a rule matches — `match_type` · `match_value`

| type | editor tab | matches | value stored |
|---|---|---|---|
| `bin` | BIN | the first 6 digits of the card | the 6 digits |
| `issuer` | Issuer bank | the card's issuing bank | the canonical issuer key (`CAPITAL ONE`, `JPMORGAN CHASE`) — any spelling you send is folded to it |
| `issuer_country` | Issuer country (3DS profiles) | the country that issued the card (the BIN's country) | the ISO-2 code (`VE`); a name or an alpha-3 code is folded (`Venezuela`, `ven` → `VE`) |
| `country` | Country (3DS profiles) | the customer's country on the order (`country`, else `billingAddress.country`) | the ISO-2 code (`US`) |

The two country types are accepted by the API on every tool; the dashboard editor offers them on **3DS
profiles** in this release. The value pickers are the account's own catalogue ranked by its volume
(`GET /v1/bin-catalog?kind=bin|issuer|issuer_country|country&q=`): every BIN and issuer the account saw
on a live charge, and for the country kinds one row per ISO code with the account's 90-day order count
(0 = not seen yet — still selectable). A BIN the account never saw can still be typed (a pre-emptive scrub).

##### What a rule does — `actions` per tool

| tool | `actions` | effect |
|---|---|---|
| mapping | `{ targets: [{ type: mid \| processor \| acquirer \| atri \| mcc, id }] }` (1..50) | the classic pass runs on the pool the targets resolve to (one MID = a pin; an `atri` target re-routes the whole pass there); cap, brand and cascade rules still apply |
| scrubbing | `{ action: 'refuse', scope: initial \| rebill \| both }` | the charge is refused before any MID on the flows in scope (a rejection, family `bin_scrub`); gated by the account's master switch and a schedule's bypass |
| threeds | `{ mode: challenge_requested \| challenge_mandated \| no_3ds }` | overrides the inline 3DS policy: request / force a challenge, or never authenticate the card |

##### Precedence

Within a profile the engine takes ONE rule: the first enabled **BIN** rule by position, else the first
**Issuer bank** rule, else **Issuer country**, else **Country** — a narrower match wins whatever its position;
position only ranks rules of the same type. The Rules tab states it under its filter line:
`Precedence BIN › Issuer bank › Issuer country › Country · order = priority`. Profiles run in the order
scrubbing → mapping → 3DS; a scrubbing refusal ends the order (no mapping / 3DS row).

Example on a 3DS profile: `issuer_country VE → challenge mandated` (position 40) and `country US → no 3DS`
(position 1) — a Venezuelan card bought from the US IS challenged: the card's country is the narrower match.
The editor and the import warn when a rule is shadowed (same value earlier in the list, a BIN whose issuer
already has a rule).

##### Explicit 3DS sessions

`POST /v1/3ds/sessions` with `atri` applies that ATRI's 3DS profile to the session's challenge preference —
the customer `country` of the session body feeds the Country rules, the card's BIN feeds the rest — so a
country rule applies to a hosted checkout that starts its own session, not only to inline authentication.

#### 3. Decision log and Analytics

Every evaluation writes one row (match or not) — `GET /v1/bin-profiles/:id/decisions` (Decision log tab):
the rule, the BIN, the issuer key, the customer `country`, the `issuer_country` the rules could match, the
decision (`applied` or not, and why), the outcome of the charge (approved / declined / rejected / gone…) and
the pipeline run. Filters: `rule_id`, `outcome`, `result`, `flow`, `bin`, `country=<ISO-2>`; `format=csv` for the
page. `GET …/analytics?from&to&tz` (Analytics tab) gives, per rule, the orders it was applied to, their
approval rate, the same value's rate before the rule (for a country rule: the same customer country on the
same ATRIs, card orders only) and the profile headline (AR with / without, lift, approvals and revenue gained).

#### 4. CSV — export, template, import

One format for the three tools:

```
order,input_type,input_value,action,targets,enabled,notes,names
```

- `order` — evaluation position (1-based). `input_type` — `bin` · `issuer` · `issuer_country` · `country`.
  `input_value` — 6 digits · the bank in any spelling · a country code or name. `action` — mapping `map`;
  scrubbing `refuse:initial` · `refuse:rebill` · `refuse:both`; 3DS `challenge_requested` ·
  `challenge_mandated` · `no_3ds`. `targets` (mapping) — `mid:<uuid>|processor:<uuid>|acquirer:<uuid>|atri:<uuid>|mcc:<4 digits>`,
  ids only. `enabled` — `true` / `false`. `notes` — free text. `names` — written by the export for the reader,
  ignored on import.

| action | where | call |
|---|---|---|
| export one profile | profile › Rules tab › Export ▾ › CSV | `GET /v1/bin-profiles/:id/rules/export.csv` |
| export every profile of the tool | list page or Rules tab › Export ▾ › **All … profiles (CSV)** | `GET /v1/bin-profiles/export.csv?kind=` (a leading `profile` column) |
| get a template | Export ▾ › **CSV template**, or the Import modal's File tab | `GET /v1/bin-profiles/csv-template?kind=` |
| preview a file | profile › Rules tab › Actions ▾ › **Import CSV** › Preview | `POST /v1/bin-profiles/:id/rules/import/preview { csv }` |
| import | the same modal › Import | `POST /v1/bin-profiles/:id/rules/import { token, mode }` |

**Preview first, always.** The preview validates every row without writing anything — unknown BIN / issuer /
country / MID / processor / bank / ATRI / MCC, an action of another tool, duplicates and contradictions in the
file, conflicts with the existing rules, precedence shadowing — and answers a row-by-row report (Report tab:
errors block, warnings inform), the resulting rule list under each mode (Preview tab) and a token valid 15
minutes. **Import** posts the token with the mode; it stays off while a row has a blocking error or the text
changed since the preview, and the API refuses the same cases with a `409` ("run the preview again"): a
blocking row, an expired or spent token, rules changed in the profile since the preview.

| mode | existing rules | positions |
|---|---|---|
| **Append** (default) | kept — an existing rule with the same value fires first (warning) | after the last one, the file's order kept |
| **Replace** | ALL deleted, RB-synced and generated rules included — the file becomes the profile (a danger confirm names the count) | the file's `order`, renumbered 1..n |

A Replace on a scrubbing profile removes its `rb_sync` rules: the next `PUT /v1/scrub-bins` re-inserts the
account's current RB list at the head of the profile (unless the profile opted out with `criteria.rb_sync:
false`). Imported rules carry `source = import`; after an import the Rules tab filters on that source.

**Round trip**: export → import in Replace mode → the same rules (order, type, value, action, targets,
enabled, notes). The export writes ids and codes, the import reads them back; the names column is for humans.

### Refunds, disputes and the blacklist

For a CRM or refund team: search charges, issue refunds, mark refunds/chargebacks you processed yourself, sync
transactions, and manage the blacklist.

#### Auth

Base URL (prod): `https://api.kontrolcheckout.com`

##### Your account API key

```
Authorization: Bearer <your account API key>
```

The account API key is the credential for every route of this guide. Create a key in the dashboard
(API keys) or with `POST /v1/keys`, with the scopes you need. An account can hold several keys (for
example one per team or service), each revocable on its own.

- The key needs **explicit scopes** on these routes: `refunds.*`, `transactions.*` and `customers.*`
  (the endpoint index, Part 3, gives the exact scope of each route). A key with `scopes: null` is
  refused here, and so is a key without an account owner.
- A call outside the key's scopes is refused with **403** and `"code": "insufficient_scope"`, never
  silently narrowed.
- The account is **the key's own account**, for the refund, transaction, blacklist and scrub BIN
  routes alike. A supplied `clientId` must match it or the call answers **403**.
- An account API key always runs live operations; test mode is only reached with the test token
  (below).
- A missing or invalid credential answers **401**.
- Card numbers are **never** returned beyond `first6……last4`.

Consult the endpoint index (Part 3) and the endpoint reference (Part 4) for each operation.

##### Legacy shared token

Older integrations may still send `X-Refund-Key: <token>`, a platform-wide shared token that is
being retired; the account is then named in the request (`clientId`). New integrations use their
account API key. Request and response formats are the same. Every call made with the shared token
is flagged on our side, and a cut-off is agreed once your services have moved (no date is imposed).
If the shared token is not configured on our side the routes answer **503**.

The **test token** (sent in the same `X-Refund-Key` header) runs refunds, mark-as-refunded and
chargebacks in test mode: the full flow (validation, a persisted refund row tagged **TEST**, the
transaction shown as refunded / charged back in search, `GET /v1/transactions/:id` and our
dashboard) but **no payment provider is ever called and no customer is blacklisted**. The response
carries `"testMode": true`; a test never touches a LIVE refund. Undo a test with
`POST /v1/refund/cancel-test` (by `refundId` or by `transactionId`), or, for a test chargeback, send
`chargedBack: false` to the same endpoint: the transaction returns to its pre-test state. Blacklist
add/remove is accepted but does nothing (`"testMode": true`). Use it to validate an integration
end-to-end against production without moving money.

---

#### 1. Search transactions — `POST /v1/refund/search`

Find charges to refund or to match a dispute. Provide **at least one** of: a date range,
an amount, `first6`+`last4`, `authCode`, `gatewayTxnId`, `email`, `orderId`, or
`descriptor`.

**Request body** (all optional, combinable)

| Field | Type | Notes |
|---|---|---|
| `from` / `to` | ISO-8601 datetime | date range, e.g. `"2026-06-01T00:00:00Z"` |
| `amount` | number | major units (e.g. `14.98`), exact match |
| `currency` | string(3) | e.g. `"USD"` |
| `first6` / `last4` | string | 6 / 4 digits |
| `email` | string | cardholder email |
| `orderId` | string | your order id |
| `gatewayTxnId` | string | the gateway transaction id (the practical **ARN substitute** — a true ARN is a settlement artifact no gateway returns to us) |
| `authCode` | string | NMI card charges only (wallet charges have none) |
| `descriptor` | string | case-insensitive contains match on the billing descriptor |
| `limit` | int | 1-200, default 50 |

```bash
curl -X POST https://api.kontrolcheckout.com/v1/refund/search \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"from":"2026-06-01T00:00:00Z","to":"2026-06-18T23:59:59Z","first6":"411591","last4":"6461"}'
```

**Response** (per-transaction shape identical to `/v1/transactions` and `GET /v1/transactions/{id}`)

```jsonc
{
  "count": 1,
  "transactions": [
    {
      "transactionId": "3ed5c88e-…",   // ← use this to refund
      "orderId": "95f2b6f9-…",
      "amount": 14.98,
      "currency": "USD",
      "status": "approved",
      "approved": true,
      "actionType": "straight_sale",   // straight_sale | rebill | rebill_legacy | imported (see §2)
      "operation": "SALE",             // SALE | REFUND | VOID | CHARGEBACK — the record's type, predefined for you
      "customerId": "cus_3f9c1e7a2b6d4081", // stable id derived from the customer email
      "refundStatus": "none",          // none | partial | refunded
      "createdAt": "2026-06-18T11:25:13.278Z",
      "mid": "GARDEN HUB …",
      "gatewayTxnId": "12199611306",
      "card": "411591……6461",          // first6 + last4 only
      "cardExpiration": "0629",
      "gatewayType": "nmi",            // nmi | convesio | wallet
      "email": "buyer@example.com",
      "descriptor": "GARDENHUB.COM",
      "refunded": 0.00,
      "refundable": 14.98,             // remaining you can refund
      "chargedBack": false,
      "billing": { "address1": "…", "city": "…", "state": "…", "postalCode": "…", "country": "US", "phone": "…" },
      "shipping": { "firstName": "…", "lastName": "…", "city": "…", "state": "…", "postalCode": "…", "country": "US" }
    }
  ]
}
```

> Only **approved** transactions (`approved: true`, `refundable > 0`) can be refunded.

---

#### 2. Get a transaction by id — `GET /v1/transactions/{transactionId}`

The direct lookup: no search parameters, no ambiguity. Returns the **same per-transaction
object as search / sync** plus a `refunds` array — every refund attempt on it, newest
first, with its `refundId`, `isChargeback` and `isTest` flags.

Optional **query** identifiers let you assert you hold the right transaction before
acting on it: `cardLast4` (4 digits), `cardBin` (6 digits), `amount`, `email`,
`orderId`. Any mismatch → **422** `{ "error": "Transaction identifiers do not match",
"mismatched": ["cardLast4", …] }` (nothing else is returned).

```bash
curl "https://api.kontrolcheckout.com/v1/transactions/3ed5c88e-…?cardLast4=6461&cardBin=411591" \
  -H "Authorization: Bearer $KONTROL_API_KEY"
```

```jsonc
{
  "transactionId": "3ed5c88e-…", "orderId": "…", "amount": 14.98, "approved": true,
  "refundStatus": "refunded", "chargedBack": true, "disputeKind": null,   // … all search fields …
  "refunds": [
    { "refundId": "a1b2c3d4-…", "status": "approved", "success": true, "method": "external",
      "amount": 14.98, "fee": 13.00, "isChargeback": true, "disputeKind": null, "isTest": false,
      "requestedBy": "agent@partner.com", "reason": "chargeback received",
      "createdAt": "2026-09-02T10:11:12.000Z", "completedAt": "2026-09-02T10:11:12.300Z" }
  ]
}
```

| Code | Meaning |
|---|---|
| 200 | Found |
| 404 | No such transaction |
| 422 | One or more identifiers don't match (see `mismatched`) |
| 400 | `transactionId` is not a UUID / bad identifier format |

##### Field reference — `actionType`, and why some fields are `null`

**Every row is one SALE.** We charge in a single step (authorization + capture together);
there is no separate AUTHORIZE / CAPTURE row, and a refund, void or chargeback is
**not** a separate row either — it is a *dimension* of the sale (`refundStatus`,
`refunded`, `refundedAt`, `chargedBack`, `disputeKind`). If your model has one row per
operation, derive them like this:

**Predefined for you — one field, one value, nothing to derive:**

| Field | Values | Meaning |
|---|---|---|
| `operation` | `"SALE"` \| `"REFUND"` \| `"VOID"` \| `"CHARGEBACK"` | the current type of the record. `SALE` until a refund lands; then the type of its latest successful refund: a same-day unsettled refund executed as a void → `VOID`, a refund marked as chargeback → `CHARGEBACK`, anything else → `REFUND`. Amount refunded = `refunded`, date = `refundedAt`. |
| `refunds[].operationType` (`GET /v1/transactions/{id}` only) | `"REFUND"` \| `"VOID"` \| `"CHARGEBACK"` | the same classification per refund row, if you keep one record per refund |

Store `operation` as your Action Type. `AUTHORIZE` and `CAPTURE` never occur (we authorize and capture in one step). Declined attempts read `operation: "SALE"` with `approved: false` and are never refundable.

**`customerId`** — a stable, opaque id (`cus_` + 16 hex) derived from the customer's normalized email: the same shopper gets the same id on every order, sale and rebill. `null` when the transaction carries no email. There is no separate customer entity in our system, so this is the identifier to group by (`email` + `card` remain available).

**`actionType` is a different axis** — *where the sale comes from*:

| `actionType` | Meaning |
|---|---|
| `straight_sale` | initial customer checkout (card, or Apple/Google Pay when `gatewayType: wallet`) |
| `rebill` | card-on-file recharge of an existing order (subscription/rebill), routed through our engine |
| `rebill_legacy` | same, via the legacy rebill path |
| `imported` | a card-on-file order **backfilled from a CSV** (the original sale happened on another platform). **No charge was processed here**, so it carries no gateway data — see below — and `POST /v1/refund` rejects it (use `POST /v1/refund/mark` instead). Its rebills are real charges. |

**Why a field can be `null`** (we return only what we actually store — nothing is invented).
Since v3.9 §1 a charge we refused **before any gateway** (blacklist, BIN scrub, transaction
filters, card pre-check, card cooldown, 3DS policy) is not a transaction at all and never
appears here — the former `preGateway` field is gone, and every decline you get is a gateway
verdict or a technical error:

| Situation | Fields that are `null` | Why |
|---|---|---|
| `actionType: imported` | `mid`, `midNumber`, `gatewayTxnId`, `authCode`, `avsResponse`, `cscResponse`, `descriptor`, `responseText`, `storefrontUrl`, `trafficSource`, `productId` | no charge happened on our side |
| any decline | `authCode` | gateways only issue an auth code on approval. Descriptor / AVS / CSC / shipping come from the last attempt when one was made |
| `gatewayType: wallet` (Apple/Google Pay) | `card`, `cardExpiration`, `authCode`, `avsResponse`, `cscResponse`, `descriptor`, `midNumber`, `responseText` | tokenised wallet payment — the network never exposes the PAN, and ConvesioPay returns no auth code / AVS / CSC; use `gatewayTxnId` (the ConvesioPay payment id) |
| `gatewayType: convesio` (card via ConvesioPay S2S) | `authCode`, `avsResponse`, `cscResponse` | ConvesioPay does not return them |
| `rebill` / `rebill_legacy` | `productId` (sometimes), `storefrontUrl` / `trafficSource` (older rebills) | inherited from the original sale when we have it; legacy rebills whose original sale is not in our DB have none |
| any | `midNumber` | the MID's number was not filled in on our side (data gap, not a processing issue) |

Not available at all (no equivalent in our system): ARN, CAVV / 3-D Secure results,
campaign / affiliate ids, card fingerprint. Identify a shopper by `email` + `card`;
identify the MID by `mid` / `midNumber` / `paymentGatewayId` (= the **MerchantId** of the
blacklist listings, §11); identify the account that charged it by **`clientId`** (= the
**ClientId** of the blacklist listings — the account's owner email; every MID that account
charges through sits under it).

---

#### 3. Transactions sync — `POST /v1/transactions`

Paginated date-window listing of **every** transaction (card + wallet) for a periodic
DB sync. Same per-transaction shape as search.

**Request body**

| Field | Type | Required | Notes |
|---|---|---|---|
| `from` / `to` | ISO-8601 datetime | ✅ | window bounds |
| `status` | string | optional | `approved` \| `declined` \| `error` \| `unknown` \| `pending` \| `duplicate` |
| `page` | int | optional | default 1 |
| `pageSize` | int | optional | 1-500, default 200 |

Stable order (`createdAt` asc, then id) — walk `page` 1..`totalPages` to mirror the window.

```jsonc
{ "page": 1, "pageSize": 200, "totalItems": 4210, "totalPages": 22,
  "count": 200, "transactions": [ /* … */ ] }
```

---

#### 4. Refund — `POST /v1/refund`

Refunds the **full remaining amount** on the original MID. (Partial amounts are **not**
supported — any `amount` sent is ignored and the whole remaining balance is refunded.)
Card (NMI) **and** wallet (Apple/Google Pay via ConvesioPay) charges are refundable.

**Request body**

| Field | Type | Required | Notes |
|---|---|---|---|
| `transactionId` | uuid | ✅ | from the search result |
| `idempotencyKey` | string (8-128) | ✅ | **your unique id per refund attempt** — prevents double-refunds |
| `amount` | number | optional | **ignored** — refunds are always full-remaining |
| `requestedBy` | string ≤128 | optional | who/what initiated it — free text (e.g. agent email or ticket ref). Stored; also used as the blacklist author. |
| `reason` | string ≤512 | optional | why — free text (e.g. `"customer request"`, `"fraud"`, `"duplicate"`). Stored; also the blacklist reason. |

```bash
curl -X POST https://api.kontrolcheckout.com/v1/refund \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"transactionId":"3ed5c88e-…","idempotencyKey":"crm-ticket-48291","requestedBy":"agent@partner.com","reason":"customer request"}'
```

**Success (200)**

```jsonc
{ "refundId": "…", "status": "approved", "success": true, "method": "refund",
  "amount": 14.98, "fee": 0.00, "nmiRefundId": "12199700000", "message": "SUCCESS" }
```

**Declined by the gateway (422)**

```jsonc
{ "refundId": "…", "status": "declined", "success": false,
  "amount": 14.98, "message": "<gateway reason>", "error": "<gateway reason>" }
```

**Idempotent replay** — re-sending the **same `idempotencyKey`** returns the original
result with `"replayed": true` and does **not** refund again.

##### Status codes

| Code | Meaning |
|---|---|
| 200 | Refund approved (or idempotent replay of a prior result) |
| 422 | Declined, or not refundable — not a card/wallet charge, not approved, nothing left to refund (see `error`) |
| 404 | `transactionId` not found |
| 409 | A refund with this `idempotencyKey` is still in progress — retry shortly |
| 401 / 503 | Missing or invalid credential / shared token not configured (legacy) |
| 502 | Gateway/network error — safe to retry with the **same** `idempotencyKey` |

> **Test token:** the same call returns `"method": "test"` and `"testMode": true`, marks
> the transaction refunded in our dashboard, but makes no provider call. Undo it with
> `POST /v1/refund/cancel-test`.

---

#### 5. Mark as refunded — no gateway call — `POST /v1/refund/mark`

Use this when **you already handled the money** (refund or void done directly at the
MID / bank, or a chargeback you lost) and only want our record to match **and the
customer blacklisted**. Nothing is sent to any payment provider.

What it does, in one call: books a refund of the full remaining amount with
`"method": "external"`, sets the transaction's `refundStatus` / `refunded` /
`refundedAt` (visible in search, sync and our dashboard), **blacklists the customer's
email + card**, and — with `chargeback: true` — reclassifies it as a chargeback
(same as `POST /v1/refund/chargeback`). Works on any approved order, including
`actionType: imported` ones that `POST /v1/refund` cannot reach.

**Request body**

| Field | Type | Required | Notes |
|---|---|---|---|
| `transactionId` | uuid | ✅ | from search / sync |
| `idempotencyKey` | string (8-128) | ✅ | your unique id per mark — re-sending it replays the first result |
| `chargeback` | boolean | optional | `true` = record it as a **chargeback** instead of a refund (default `false`) |
| `requestedBy` | string ≤128 | optional | who/what initiated it — free text; stored, also the blacklist author |
| `reason` | string ≤512 | optional | free text; stored, also the blacklist reason (default `"Refunded by partner"` / `"Chargeback (partner)"`) |

```bash
curl -X POST https://api.kontrolcheckout.com/v1/refund/mark \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"transactionId":"3ed5c88e-…","idempotencyKey":"crm-cb-48291","chargeback":true,"requestedBy":"agent@partner.com","reason":"chargeback received"}'
```

**Response (200)**

```jsonc
{ "refundId": "…", "transactionId": "3ed5c88e-…", "status": "approved", "success": true,
  "method": "external", "amount": 14.98, "fee": 15.00, "isChargeback": true,
  "blacklisted": true, "message": "Marked as refunded externally — no gateway call made" }
```

| Code | Meaning |
|---|---|
| 200 | Marked (or idempotent replay — `"replayed": true`) |
| 404 | `transactionId` not found |
| 422 | Not an approved charge, or nothing left to refund |
| 409 | Same `idempotencyKey` still in progress — retry shortly |

> **Refund vs mark:** `POST /v1/refund` **moves money** (we call the gateway) and then
> blacklists. `POST /v1/refund/mark` **moves no money** — it records what you did and
> blacklists. Never call both for the same transaction.
>
> **Test token:** same flow, persisted as a **TEST** refund (`"testMode": true`, visible
> with `isTest: true`, no blacklist). Undo with `POST /v1/refund/cancel-test`.

---

#### 6. Mark / unmark a chargeback by TRANSACTION id — `POST /v1/transactions/{transactionId}/chargeback`

The chargeback endpoint keyed by the **transaction** (no `refundId` needed).

- `chargedBack: true` → the transaction becomes **charged back**. **This call never
  performs or triggers a refund at the payment provider — no money moves.** It only
  records/reclassifies: if the transaction already has a successful refund, that refund
  is reclassified as a chargeback; if it was **never refunded**, we first book an
  **external refund record** (the dispute itself already moved the money on the card
  network side — we make no provider call) and then mark it. The transaction then reads
  `refundStatus: refunded`, `chargedBack: true`, `operation: "CHARGEBACK"`. The
  customer is blacklisted (not with the test token). Idempotent: marking twice is a no-op success.
  If you want **us** to actually refund the customer, use `POST /v1/refund` instead.
- `chargedBack: false` → **unmarks** it (back to a plain refund). With the **test token**
  this also cancels the test refund, so the transaction returns to exactly its
  pre-test state.

Optional identifiers (`cardLast4`, `cardBin`, `amount`, `email`, `orderId`) are checked
**before** anything is written — any mismatch → 422 and nothing changes.

**Request body**

| Field | Type | Required | Notes |
|---|---|---|---|
| `chargedBack` | boolean | ✅ | `true` = mark, `false` = unmark |
| `cardLast4` / `cardBin` / `amount` / `email` / `orderId` | | optional | validation only — must match the transaction |
| `requestedBy` | string ≤128 | optional | who/what initiated it — free text; stored, also the blacklist author |
| `reason` | string ≤512 | optional | free text (default `"Chargeback"`); stored, also the blacklist reason |
| `idempotencyKey` | string 8-128 | optional | for the external refund booked when the transaction was not yet refunded (default `chargeback:<transactionId>`) |

```bash
curl -X POST https://api.kontrolcheckout.com/v1/transactions/3ed5c88e-…/chargeback \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"chargedBack":true,"cardLast4":"6461","cardBin":"411591","reason":"chargeback received","requestedBy":"agent@partner.com"}'
```

**Response (200)** — includes the resulting transaction state so no second call is needed

```jsonc
{ "transactionId": "3ed5c88e-…", "refundId": "a1b2c3d4-…", "isChargeback": true,
  "refundBooked": true,          // true = we booked the external refund in this call
  "fee": 13.00, "chargedBack": true, "refundStatus": "refunded" }
```

Unmark → `{ "transactionId": "…", "isChargeback": false, "refundIds": ["…"], "reverted": false,
"chargedBack": false, "refundStatus": "refunded" }` (`reverted: true` + `refundStatus: none`
under the test token).

| Code | Meaning |
|---|---|
| 200 | Marked / unmarked (idempotent) |
| 404 | Transaction not found |
| 422 | Identifiers don't match · not an approved charge · `chargedBack:false` on a transaction that isn't charged back · nothing left to refund |
| 400 | Invalid body |

> **Test token:** same call, `"testMode": true`. The mark is persisted as a **TEST**
> refund + chargeback — `GET /v1/transactions/{id}` shows `chargedBack: true`,
> `refundStatus: refunded` and the refund with `isTest: true`. Send `chargedBack: false`
> (or `POST /v1/refund/cancel-test` with the `transactionId`) to revert. A test never
> reclassifies a LIVE refund.

---

#### 7. RDR and Ethoca alerts by TRANSACTION id — `POST /v1/transactions/{transactionId}/rdr` · `.../alert`

Two dispute kinds, two different things happening to the money. Both label the resulting
refund so your figures and ours agree on **why** it exists — which is what a free-form note
cannot do.

| | `/rdr` | `/alert` |
|---|---|---|
| What happened | Visa (RDR) already took the money back | Ethoca warned you; refunding is **your** decision |
| Does money move here? | **No** — `moneyMoved: false` | **Yes** — the refund engine runs |
| `idempotencyKey` | not needed | **required** |
| What we book | an **external** refund (no gateway call) + the `rdr` label | a real refund + the `ethoca` label |

##### Mark an RDR

```bash
curl -X POST https://api.kontrolcheckout.com/v1/transactions/{transactionId}/rdr \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{ "reason": "Visa RDR 1234", "requestedBy": "refund-team" }'
```

```json
{ "refundId": "9ccd7a16-…", "status": "approved", "success": true, "method": "external",
  "amount": 19.98, "fee": 0, "nmiRefundId": null, "disputeKind": "rdr",
  "message": "Marked as refunded externally — no gateway call made",
  "moneyMoved": false, "refundStatus": "refunded" }
```

The charge becomes refunded on our side because an RDR means it already was on yours. If the
charge was **already** refunded we label that refund instead of booking a second one.

##### Mark an Ethoca alert (this one refunds)

```bash
curl -X POST https://api.kontrolcheckout.com/v1/transactions/{transactionId}/alert \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{ "idempotencyKey": "ethoca-55821", "reason": "Ethoca alert 55821", "requestedBy": "refund-team" }'
```

- `idempotencyKey` (8–128 chars) is **required**: this endpoint moves money, so the same key
  always replays the same refund instead of making a second one. Omit it and you get
  `400 { "details": { "idempotencyKey": "required: this endpoint refunds" } }`.
- `amount` is optional — omit it to refund the **whole refundable balance**, or pass a smaller
  decimal amount for a partial.
- The response carries `moneyMoved: true` when the refund actually went out.

##### Unmark either one — `{ "marked": false }`

```bash
curl -X POST https://api.kontrolcheckout.com/v1/transactions/{transactionId}/rdr \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{ "marked": false, "requestedBy": "refund-team" }'
```

```json
{ "refundId": "9ccd7a16-…", "disputeKind": null, "unmarked": 1,
  "moneyMoved": false, "refundStatus": "refunded" }
```

> **Unmarking removes the LABEL, not the refund.** The money stays where it went — exactly as
> `chargedBack: false` reclassifies without unwinding (§6). `unmarked` is how many refund rows
> lost the label. `refundStatus` therefore still reads `refunded`, which is correct and is the
> answer to "did the customer get their money".

A dispute label and a chargeback are **mutually exclusive**: a refund marked `rdr` or `ethoca`
is not counted as a chargeback, and marking it a chargeback (§6, §9) clears the dispute label.

##### Optional identifier check (all three endpoints)

Any of `orderId`, `email`, `cardLast4`, `cardBin`, `amount` may be sent alongside. We validate
them against the transaction **before** doing anything and answer
`422 { "error": "Transaction identifiers do not match", "mismatched": ["cardLast4"] }` if one is
wrong. Send what your own record has — it is a cheap guard against acting on the wrong charge.

##### Status codes

| Code | Meaning |
|---|---|
| `200` | marked / unmarked |
| `400` | bad payload — `transactionId` is not a uuid, or `idempotencyKey` missing on an alert mark |
| `404` | no such transaction for your key |
| `422` | identifiers do not match, or there was no dispute label to remove |

##### With the test token

Both work on `isTest` rows and answer `testMode: true`; no provider is called and nothing is
blacklisted. **One caveat worth knowing before you loop on one test charge:** `/rdr` books a
refund, and `POST /v1/refund/cancel-test` afterwards cancels that refund row but leaves the
charge reading `refundStatus: "refunded"` (it answers `reverted: false`). So a test round trip
does not return the charge to its original state — use a fresh test charge per scenario. This is
a known gap on our side, already logged for repair.

---

#### 8. Notes on a transaction — `POST /v1/transactions/{transactionId}/note` · `GET .../notes`

A free-form thread on a charge: the alert id you were given, what the issuer said, what the
customer was told. It is the same thread our dashboard shows, so anything you write here is read
by whoever handles the dispute next.

Notes are **context, not classification**: they do not move money and they do not feed any
financial figure. Use `/rdr`, `/alert` (§7) or `/chargeback` (§6, §9) for what a refund *is*, and a
note for what you *know* about it.

##### Write a note

```bash
curl -X POST https://api.kontrolcheckout.com/v1/transactions/{transactionId}/note \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{ "note": "Ethoca alert 55821 — issuer confirmed fraud, customer refunded in full.",
        "author": "refund-team" }'
```

```json
{ "noteId": "5c6fdcd2-…", "transactionId": "81d8d7e1-…",
  "note": "Ethoca alert 55821 — issuer confirmed fraud, customer refunded in full.",
  "author": "refund-team", "createdAt": "2026-10-07T09:16:20.274Z" }
```

- `note` — 1 to 4000 characters, trimmed. Required.
- `author` — up to 128 characters. Optional; defaults to your `clientId`, else `partner-api`.
- Returns **201**. Notes are append-only: there is no edit and no delete.

##### Read the thread

```bash
curl "https://api.kontrolcheckout.com/v1/transactions/{transactionId}/notes" -H "Authorization: Bearer $KONTROL_API_KEY"
```

```json
{ "transactionId": "81d8d7e1-…",
  "notes": [ { "noteId": "5c6fdcd2-…", "note": "Ethoca alert 55821 — …",
               "author": "refund-team", "createdAt": "2026-10-07T09:16:20.274Z" } ] }
```

The identifier check of §7 applies here too, as query parameters on the GET
(`?orderId=…&cardLast4=1234`).

##### Status codes

| Code | Meaning |
|---|---|
| `201` | note written (POST) |
| `200` | thread returned (GET) |
| `400` | `transactionId` is not a uuid, or `note` is empty or over 4000 characters |
| `404` | no such transaction for your key |
| `422` | identifiers do not match |

---
#### 9. Mark / unmark a chargeback by REFUND id — `POST /v1/refund/chargeback`

Same as §6 but keyed by an existing **refund**. Reclassify it as a **chargeback** (or
back to a plain refund). Bookkeeping only — **no money moves**; the amount + fee shift into the chargeback
buckets in our finance reporting. Marking a chargeback also **blacklists** the customer
and clears any RDR/Ethoca dispute label on that refund.

**Request body**

| Field | Type | Required | Notes |
|---|---|---|---|
| `refundId` | uuid | ✅ | the refund's id (the `refundId` from a refund result / search) |
| `chargeback` | boolean | ✅ | `true` = mark as chargeback, `false` = unmark (back to refund) |

```bash
curl -X POST https://api.kontrolcheckout.com/v1/refund/chargeback \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"refundId":"a1b2c3d4-…","chargeback":true}'
```

**Response (200)**

```jsonc
{ "refundId": "a1b2c3d4-…", "isChargeback": true, "fee": 15.00 }
```

| Code | Meaning |
|---|---|
| 200 | Reclassified |
| 404 | `refundId` not found |
| 409 / 422 | Refund not in a state that can be (un)marked (see the body) |

> **Test token:** acts on **TEST** refunds only (`"testMode": true`). A LIVE `refundId`
> is acknowledged with `"noop": true` and left untouched.

---

#### 10. Cancel TEST refunds — `POST /v1/refund/cancel-test`

Undo refunds / chargebacks created with the **test token** (only `TEST`-tagged rows).
Reverts the transaction (un-refunds it, clears a test chargeback) and marks the refund
cancelled. No provider call. Send **one of**:

| Field | Type | Notes |
|---|---|---|
| `refundId` | uuid | cancel this one test refund |
| `transactionId` | uuid | cancel **every** test refund of the transaction (test chargebacks included) |

```jsonc
{ "refundId": "…", "status": "cancelled", "reverted": true }                       // by refundId
{ "transactionId": "…", "cancelled": ["…"], "reverted": true }                     // by transactionId
```

| Code | Meaning |
|---|---|
| 200 | Cancelled (or nothing to cancel — idempotent) |
| 404 | `refundId` / `transactionId` not found |
| 422 | Not a test refund (only `TEST` refunds can be cancelled here) |

---

#### 11. Blacklist — add / check / remove / list

Block a customer (email and/or full card) from ordering on any store.

- **Add** — `POST /v1/blacklist` `{ email?, cardNumber?, reason? }` → `{ "added": [ … ] }`
- **Check** — `POST /v1/blacklist/check` `{ email?, cardNumber? }` → `{ "blacklisted": bool, "matched": "email"|"card"|null, "reason": string|null }`
- **Remove** — `DELETE /v1/blacklist` `{ email?, cardNumber? }` → `{ "removed": <count> }`
- **List by client** — `GET /v1/blacklist/client/{clientId}` — blacklisted customers seen on **every MID** charged by that account
- **List by merchant** — `GET /v1/blacklist/merchant/{merchantId}` — blacklisted customers seen on **one MID**

##### Listing by client / merchant

The blacklist itself is global (one identity = one row, enforced on every store). A
customer is listed "under" a client or a merchant when their blacklisted **email** or
**card** (full-PAN hash) appears on a transaction charged through that scope — so the
same customer can appear under several MIDs, and a customer blacklisted from data you
hold that never transacted with us appears under none.

| Path parameter | What to send |
|---|---|
| `clientId` | the account, as returned in `clientId` on every transaction (its owner email — URL-encode the `@`, e.g. `admin%40example.com`) |
| `merchantId` | the MID: `paymentGatewayId` (uuid) **or** `midNumber` from any transaction |

| Query | Type | Default | Meaning |
|---|---|---|---|
| `dateStart` | ISO date or datetime | — | only customers **blacklisted at or after** this instant (a bare `YYYY-MM-DD` = start of that day, UTC) |
| `dateEnd` | ISO date or datetime | — | only customers **blacklisted at or before** this instant (a bare date covers its whole day) |
| `includeInactive` | `true`/`false` | `false` | also return entries that were removed from the blacklist since |
| `page`, `pageSize` | int | `1`, `100` (max 500) | paging; ordered newest blacklisting first |

```bash
curl "https://api.kontrolcheckout.com/v1/blacklist/merchant/572935700127043?dateStart=2026-09-01&dateEnd=2026-09-10" \
  -H "Authorization: Bearer $KONTROL_API_KEY"
```

```json
{
  "merchantId": "572935700127043",
  "dateStart": "2026-09-01T00:00:00.000Z", "dateEnd": "2026-09-10T23:59:59.999Z",
  "page": 1, "pageSize": 100, "total": 19,
  "customers": [
    {
      "blacklistId": "e7aee9b9-0f0c-4c7b-ad97-cd8298ad2c79",
      "email": null, "card": "411600……0873",
      "reason": "refund-team dashboard", "source": "refund", "createdBy": "crm@example.com",
      "createdAt": "2026-09-11T01:20:13.073Z", "active": true,
      "matchedBy": "card", "transactions": 1,
      "firstSeenAt": "2026-09-09T20:30:20.826Z", "lastSeenAt": "2026-09-09T20:30:20.826Z",
      "merchants": [ { "merchantId": "fe436943-…", "mid": "PADDLE GEAR SIGNAPAY/CHESAPEAK", "midNumber": "572935700127043" } ]
    }
  ]
}
```

| Field | Meaning |
|---|---|
| `email` / `card` | the blacklisted identity (one row per identity — a refund blacklists both, so the same person may appear as an email row and a card row); `card` is `first6……last4`, never the PAN |
| `source` | `refund` (auto-blacklisted by a refund / mark / chargeback), `manual` (API or dashboard), `csv` |
| `createdBy`, `reason` | who blacklisted them and why (your `requestedBy` / `reason` when it came through this API) |
| `matchedBy` | how the customer was tied to this scope: `email`, `card` or `both` |
| `transactions`, `firstSeenAt`, `lastSeenAt` | their charges (any outcome) inside the scope |
| `merchants` | every MID inside the scope they transacted on (one entry for a merchant listing; several for a client listing) |

Notes: Apple / Google Pay charges carry no card number, so they only match by email. The
date window filters on **when the customer was blacklisted**, not on their transaction
dates. `404` is never returned for an unknown client/merchant — you get `total: 0`.

Provide `email` and/or `cardNumber` (at least one). `cardNumber` must be the **full PAN**
(≥12 digits) — the blacklist identity is a full-PAN hash, so `first6……last4` won't match;
we hash it immediately and never store or log the raw number. `reason` is free text
(≤256, default `"Partner API"`), shown to us when a future charge is rejected.

```bash
curl -X POST https://api.kontrolcheckout.com/v1/blacklist \
  -H "Authorization: Bearer $KONTROL_API_KEY" -H "content-type: application/json" \
  -d '{"email":"abuser@example.com","reason":"chargeback risk"}'
```

---

#### After a refund

- The transaction's **`refundStatus`** becomes `refunded` (full) or `partial`, and
  `refunded` / `refundable` update — visible in search and on our Orders dashboard. The
  original charge `status` stays `approved` (so approval-rate history stays accurate —
  the refund is a separate dimension).
- Every refund attempt (approved, declined, or error) is recorded on our side.
- A successful (non-test) refund also **blacklists** the customer's email + card — so
  does `POST /v1/refund/mark`. You do **not** need a separate `POST /v1/blacklist` call
  afterwards (it is harmless if you do — the blacklist is idempotent); use it only for
  customers you want to block **without** a refund, or to block by an email/card you
  have that we do not.

#### Notes & limits

- **Always send a unique `idempotencyKey`** per intended refund. Reusing one is how you
  safely retry without double-refunding.
- **Full-amount refunds only** — partial refunds are not supported.
- Card **and** wallet (Apple/Google Pay) charges are refundable here.
- **Same-day, unsettled** NMI auths are automatically *voided* instead of refunded when
  needed — no action from you.
- We never return full card numbers — only `first6……last4`.

### Delete items individually or in bulk

Open an item's **Actions → Delete**, or select rows and choose **Actions → Delete** in the bulk bar. Both actions call the same account-scoped item endpoint. A confirmation describes the effect before anything changes.

Deletion is available for stores, store and standalone checkouts, pages, flows, links, affiliates, products, product images and reviews, discount codes, custom themes, pixels, Google Ads tags, webhooks, catalogs, messaging providers, recovery profiles/templates, retry profiles, subscription products, API keys, MIDs, ATRIs, reference lists and account members. Existing bank-account, payment-ATRI, monitoring-destination and customer-note removal actions remain available. Domain removal releases the Render registration; it does not delete the store.

Items in an unsaved draft, such as ATRI membership, catalog products and link pixels, are removed from that draft. Save the enclosing item to persist the change. Generated variants are changed through the product's options, rather than deleted independently from the variant matrix. External campaign inventories, predefined integration settings, transaction logs and historical reports are not independently deletable records.

#### Results and retry

- A cancelled confirmation leaves the selection untouched and sends no writes.
- Each selected item has its own result. Successful items leave the selection; failed items stay selected.
- **Bulk action results** shows the item, its outcome and the server's reason. Resolve the reason, close the result dialog and retry the remaining selection.
- Changing filters or account invalidates the selection. Paging preserves the selected records.
- A failed refresh does not claim that a completed deletion failed. Refresh the table to see the saved result.
- Built-in entries, the default virtual flow and memberships the caller cannot manage are protected. A mixed selection containing a protected item cannot silently delete only the other items.

#### History and dependencies

Stores are archived from the catalog. Their checkout route and recovery messaging are disabled; existing orders and subscriptions remain intact. A deleted store cannot be reactivated by a stale edit. Domain registration and historical identity are retained; release a domain from **Domains** before removing its store when required.

Public shop pages return an unavailable response after archival. Their HTML and navigation responses cannot be reused by a shared cache to bypass the live archive check; internal catalog caches remain in use. Disabling checkout serving alone is different from deleting a store and does not remove its browse-only shop pages.

Archived stores stop accepting new checkout, wallet and post-purchase offer payments, including from an already-open checkout. Inactive stores also reject new payments. Previously dispatched payments can still settle or reconcile, and their receipts, refunds and history remain available. Existing recurring subscriptions keep their own lifecycle. Storefront servers use the uncached `GET /internal/store-availability` check with existing server credentials to distinguish a retained archived store from an active one across historical store IDs and persisted domain routes; its response contains only `exists`, `archived` and `active` flags.

Store and standalone checkout deletion archives the catalog entry and disables new use. Unassign stores, A/B tests, live flow references and active saved links first. Standalone published configuration is disabled as part of the same transaction. Published versions, sessions, orders and payments are retained.

Pages and flows retain their versions. Assigned flows and pages referenced by live flows must be unlinked first. Links are archived and disabled while their statistics remain available.

Affiliate deletion removes the directory entry and revokes access and sessions. Existing attribution and commissions remain in historical reports. An archived affiliate cannot be reactivated through an ordinary settings update.

Deleting a subscription product cancels its live subscriptions and drops pending charges, as stated in its confirmation. Completed payments remain in history. Removing blacklist entries allows the affected customers on future charges. Deleting BIN profiles detaches them from ATRIs and disables that feature there.

References still used elsewhere can return **409 Conflict**. A permission failure returns **403**; a missing or out-of-account item returns **404**. None of these results is presented as a successful deletion.

### Affiliates

Affiliates have a separate account-specific login and see only their attributed activity and shared assets. Enable the affiliate feature for the merchant account before using Ecommerce → Affiliates. The feature starts disabled.

#### Create and manage an affiliate

Before activation, configure the same server-side `DASHBOARD_URL` on the dashboard and API deployments with the dashboard's public HTTPS origin (for example, `https://dashboard.example.com`, without a path, query or credentials). Put that origin first in the API's `CORS_ORIGINS`, which supplies invitation links and permitted browser access. The dashboard affiliate proxy rejects requests when this configuration is missing or invalid. Its reverse proxy must preserve the public `Host`; any forwarded host, protocol or port must agree with the configured HTTPS origin. An internal listener URL is never accepted as the browser origin.

Choose Add affiliate, enter the name, username, email and cut rule, then select access to Dashboard, Transactions, Checkouts, Funnels and Flow Builder. All five default to View and offer an explicit No access choice. Checkouts, Funnels and Flow Builder also support Edit. Merchant notes remain private.

The public Affiliate ID is the `affid` in distribution links. It accepts 1–32 letters, digits, underscores or hyphens and is unique within the merchant account without case sensitivity. You can preserve an existing provider's ID when creating the record. After its first attributed order, the ID is locked.

The default invitation lets the affiliate set a password through a single-use link valid for 72 hours. Alternatively, set a permanent password in Settings. The affiliate can sign in immediately without a forced password change; leaving Password blank on an existing record preserves the current password. Passwords are never emailed. Invitation delivery uses an enabled email provider belonging to the account. If delivery is unavailable, the editor reports that the invitation was not sent; configure the provider and resend.

The account-specific sign-in address is `/affiliate/login?account=<accountId>`. Reset links last one hour. Invitation and reset URLs exchange their token before loading the workspace and redirect to a clean URL. Existing MFA remains required through a password reset. Affiliates can manage their password and authenticator in Settings. Affiliate pixel management is retired: no affiliate pixel settings are exposed or rendered, and the old pixel mutation is denied. Merchant checkout pixels remain separate. An affiliate may configure multiple pixels on its own saved offer link; this does not restore profile-level pixel management. See *Standalone checkouts and saved offer links* in Part 2.

Disabling an affiliate prevents login and new eligible attribution while preserving historical sales and cuts. Editing access takes effect on the next request. Changing the email or password revokes existing sessions and all pending invitation/reset tokens. Sending a new invitation or reset also revokes an earlier unfinished bootstrap.

#### Links and attribution

Merchant link controls select an active affiliate. Copy affiliate link uses that record's public ID. Affiliates use Copy my link or Copy my short link in their permitted lists; the server always binds generated links to their own identity. A View grant on a shared, published standalone checkout permits managing their own saved offer links. Saved offers accept independent product names, prices, quantities, variant labels and images without a store or catalogue product. The link creator may set these commercial terms; the reusable checkout design and merchant payment routing remain protected. Signed links protect those commercial settings. Do not replace their signed product or price fields manually.

Tracking additions include `sub1` through `sub10`, `source_id`, conventional `utm_*` fields, supported ad click IDs and `_ef_transaction_id`. Each sub ID and `source_id` accepts up to 255 Unicode characters. Arbitrary query parameters, personal information, commercial overrides and session/payment secrets are not attribution extras. The parameter reference and URL builder use the same validation schema.

A new explicit `affid` replaces the earlier first-party attribution. Without one, the existing attribution retains its original expiry. The cookie lasts up to 30 days; large snapshots use an opaque cookie reference with the complete snapshot stored server-side. Signed hops exceeding 3,000 bytes use a short-lived opaque reference bound to the account, checkout and serving host, preserving the complete tracking snapshot. Owned affiliate assets take precedence over a different affiliate supplied in a link. Unknown or disabled IDs do not block checkout; they cannot earn a new cut.

For a saved offer link, the authenticated affiliate who created the link is the originating affiliate. The entry hierarchy is saved-link creator, then published flow owner, then checkout owner, then explicit tracking or the existing attribution cookie. A saved-link creator conflicting with a non-neutral flow owner is rejected. Without a saved offer link, owned entry assets still take precedence over supplied tracking. Existing entry sessions and order snapshots are never reassigned.

At entry, verified tracking is stored before pixels render. The immutable order snapshot carries attribution through declines, cascading attempts, accepted upsells and recurring rebills. Later URL or affiliate changes cannot rewrite an existing order's snapshot. Wallet payments use the same canonical order context and only earn a cut after a confirmed payment. They use an account-owned verified provider and enforce the countries allowed by the pinned checkout version before dispatch.

#### Cut rules

The cut consumer runs on the elected API job leader when `BACKGROUND_JOBS_ENABLED` permits jobs. Existing immutable accruals and reversals drain independently of new attribution. Account ownership, affiliate status and grants remain enforced.

Percent rules allow 0–100% with two decimal places. They apply to captured initial and accepted upsell amounts, including shipping and excluding tax. Rebills, declined attempts, tests and unconfirmed payments earn no cut.

Fixed rules earn one amount in the configured account currency at the first initial capture. Set the account currency in Affiliate settings before creating a fixed rule. It is locked after the first fixed rule is recorded. Fixed cuts use the checkout's supported two-decimal currencies: USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS and ZAR. Other currencies, including JPY and BHD, are rejected rather than rescaled or converted; an existing unsupported account setting cannot authorize a new fixed rule.

Every order freezes its rule. **Applies to new orders only** means a later rule edit never changes an earlier sale or its refund. Every entry rounds half up once in integer minor units:

| Event at a 30% rule | Cut entry |
| --- | ---: |
| Initial $54.99 without tax | +$16.50 |
| Accepted $29.00 upsell | +$8.70 |
| $20.00 refund on that upsell | −$6.00 |
| Chargeback after that refund | −$2.70 |
| $49.95 without tax | +$14.99 |
| $59.39 including $4.40 tax | +$16.50 |
| $29.70 refund on that tax-inclusive charge | −$8.25 |

Partial refund reversals use the cumulative refunded share of the gross captured amount, including tax and shipping. Three $10 refunds against a $30 charge with a $10 accrued cut reverse $3.33, $3.34 and $3.33. A chargeback reverses the remaining cut. Fixed cuts reverse only on a full initial refund or chargeback. Corrections create new entries; history is never edited.

#### Sharing and review

The affiliate editor Access tab lists authorized store and standalone checkouts using the exact same checkout Sharing permissions. Selecting a private checkout changes it to Selected affiliates; adding or removing this affiliate never changes another affiliate's selected share. All affiliates access is inherited and read-only in this selector; use the checkout Sharing control to change that visibility. No access on the Checkouts module blocks every checkout, including inherited and owned items. If standalone checkouts are disabled, their choices are hidden and existing shares are retained; the editor cannot create a new standalone share while the feature is disabled.

Assets start Private. Sharing can allow All affiliates or Selected affiliates, but the affiliate also needs the relevant module grant. View gives access to shared items. Edit additionally allows duplicating shared assets into owned drafts and editing permitted design/text fields. Shared template/page commerce, payment routing and publication stay under merchant control. Creating or editing an affiliate’s own autonomous saved offer is a separate View-authorized workflow; its product names and prices do not modify the shared template. Affiliates can assign flows only to their own checkouts.

Affiliate drafts require merchant publication. Editing a draft does not replace the live version. Landing links use a published flow on the checkout's verified domain. A store checkout requires its real cart entry, including its canonical checkout/flow assignment. Store landing links pass through a cookie bootstrap before opening the published flow. A preview/canvas link is not a distribution link, and post-sell pages are not standalone entry points.

#### Reports and exports

The merchant Affiliates table uses the selected period. Orders count captured initial orders; Revenue includes initial and accepted upsell captures. Rebills remain visible in history and earn zero cut. Top Affiliates uses the same revenue basis and ranks ten affiliates separately within each currency. Its row opens the affiliate record.

Affiliate cuts appear immediately before net in finance reports and dashboard financial figures, including each existing finance breakdown and their exports. Net uses the existing calculation minus the cut ledger once. Refund and chargeback adjustments belong to their event dates. The cut consumer may briefly lag the confirmed payment; it retries durably and cannot duplicate entries.

Totals remain separated by currency. There is no invented FX conversion: a net figure that would combine incompatible currencies is shown as unavailable while the individual cut amounts remain visible. The merchant can export the filtered period's table to pay affiliates. CSV/PDF exports use the visible columns, sorting and current figures; table totals preserve currencies.

The Affiliate report filter supports multiple affiliates and No affiliate. Disabled affiliates remain selectable for historical reports. No store identifies a canonical standalone order, rather than assuming that an empty storefront URL means standalone. Filters apply to synchronous reports, exports and queued report jobs under the effective account's permissions.

Affiliates see only orders, **Sales** and **Affiliate cut** in their dashboard. Their transaction projection exposes first name plus last initial, masked email, country, card brand, order amounts and their cut. It never exposes phone, address, IP, card details, merchant routing, raw payloads, merchant finance or another affiliate's data.


#### Per Affiliates

Open Reports > Per Affiliates for canonical V5 payment activity, including a No affiliate row when those payments have no attributed affiliate. Legacy transactions without a canonical V5 context are outside this report. Select at most 366 days, the calendar timezone and any unified filter. The report stays on affiliates, with a separate row for each currency and no checkout/store/daily tabs. Click an affiliate to narrow that same report. Click Transactions to open the exact intersecting affiliate, currency and charge-date population. Checkout/store filters still constrain that population. A refund filter remains a charge-cohort predicate on that link.

Transactions count completed live transactions at creation time; Approved, Declined (including terminal errors) and Unknown partition that count. Approval rate is approved divided by that completed count. Paid orders count captured initial contexts. Initial, upsell and rebill revenue use capture dates. AOV is initial plus upsell revenue divided by initial paid orders in the selected period, rounded half up to cents, with no AOV when there are no initial orders. It is not a lifetime order-cohort measure.

Refund rate is Refunded transactions divided by Approved. Chargeback rate is Charged-back transactions divided by Approved. These are creation-date cohorts: each approved transaction created during the selected period counts once if its captured payment has a positive refund or chargeback recorded by period end. Multiple partial refunds or repeated chargebacks count once; chargeback corrections do not erase historical incidence. A transaction may belong to both categories. Future reversals after period end are excluded. Totals divide summed counts, separately per currency, rather than averaging percentages. A cohort with no approved transactions shows a dash. The API retains its older groupBy and days response for compatibility; the UI only uses affiliate grouping.

Refunds and net chargebacks use their immutable event dates even when the original charge predates the period. Cuts earned, signed cuts reversed and corrections also use their ledger event dates. Net cuts is their signed sum. Net after refunds & cuts is gross capture volume minus refunds, net chargebacks and net cuts, before processing fees. Fixed cuts can create a separate currency-only liability row: no FX conversion is inferred. Tests, imported/pre-gateway rows and late server-classified test sessions are excluded.

The report uses the native CSV/PDF Export menu with its current visible columns, sort and currency-preserving totals. PDF sections repeat affiliate identity and currency so every metric remains readable; CSV stays one table. All merchant transaction tables, including recent orders, customer history, schedule/rebill charges, refunds/search and retry previews, show Originating affiliate when the feature is enabled. That column links to this report; missing attribution remains empty rather than being inferred from current links.

##### Expired sessions and sign-out

Affiliates work in their own affiliate workspace, with its own sign-in, session expiry and sign-out; it is not part of the client API.

### Account agreements

Verified against source on 2026-11-02. Base URL: `https://api.kontrolcheckout.com`. These operations create legal-document records; they do not charge a card, create a subscription, create a login or change payment routing.

#### Endpoints and access

| Method and path | Purpose | Access |
|---|---|---|
| `GET /v1/me/agreements` | List history and current template metadata | Account owner or administrator; key scope `settings.read` |
| `POST /v1/me/agreements` | Generate an immutable draft snapshot | Account owner or administrator; key scope `settings.write`; no impersonation |
| `GET /v1/me/agreements/:id` | Read complete saved terms and evidence | Account owner or administrator; `settings.read` |
| `GET /v1/me/agreements/:id/pdf` | Download complete PDF | Account owner or administrator; `settings.read` |
| `POST /v1/me/agreements/:id/sign` | Record the client's affirmative acceptance | Interactive dashboard JWT only; no API key or impersonation |

All responses are private/no-store. Foreign or missing agreement IDs return 404. The Statement tab is empty: there is no statement endpoint to call. There is no agreement PATCH or DELETE endpoint; generate a new draft for changed identity/terms and retain the prior record.

#### 1. Discover the template and history

```bash
curl --fail-with-body -sS -H "Authorization: Bearer $KONTROL_API_KEY" \
  'https://api.kontrolcheckout.com/v1/me/agreements?limit=25&offset=0'
```

Response: `{rows,hasMore,provider,pricing,version,canManage,canSign}`. Limit is 1–100 (default 25), offset starts at zero. API-key callers receive `canSign:false`. Current template `2026-11-02.1` identifies NOCOMP FZCO and charges USD 799/month with no sales percentage (`successfulVolumeBasisPoints: 0`). Saved records retain their own pricing and full terms; do not overwrite historical prices with current defaults. These document-management endpoints require a paid platform subscription; onboarding and billing recovery use the separate platform-subscription endpoints.

#### 2. Generate the agreement

Generate a fresh UUID for a new agreement. Reuse that exact UUID and identical body only to retry the same creation after an uncertain response.

```json
{
  "id":"11111111-1111-4111-8111-111111111111",
  "kind":"sub_account",
  "client":{
    "firstName":"Jane",
    "lastName":"Example",
    "company":"Example Commerce LLC",
    "address":"10 Example Road, Dubai, United Arab Emirates",
    "email":"legal@example.test",
    "title":"Director"
  }
}
```

```bash
curl --fail-with-body -sS -X POST -H "Authorization: Bearer $KONTROL_API_KEY" \
  -H 'Content-Type: application/json' --data-binary @agreement.json \
  'https://api.kontrolcheckout.com/v1/me/agreements'
```

HTTP 200 returns `{agreement}`. `kind` is `main` or `sub_account`, a history grouping only. Both receive the same independent contract, price and obligations, without a parent-company reference.

First/last name: 1–100 characters each; company: 1–250; address: 1–1500; valid email: up to 254. Optional title: up to 150, default empty. Strings are trimmed, control characters rejected, and unknown object fields rejected. Validation failure is 400; reusing a UUID with changed data is 409.

New snapshots include `providerSignature` for Gregory Bleich, Authorised representative, using a pre-applied electronic signature authorized on 2026-10-21. `agreement.signed_at` remains null until the **client** signs. Older snapshots without a provider mark do not gain one retrospectively.

#### 3. Review and download

Read `GET /v1/me/agreements/:id`. Preserve `content_hash`, the complete snapshot, client identity and version. Download the PDF as binary:

```bash
curl --fail-with-body -sS -H "Authorization: Bearer $KONTROL_API_KEY" \
  -o agreement.pdf "https://api.kontrolcheckout.com/v1/me/agreements/$AGREEMENT_ID/pdf"
```

Expected content type: `application/pdf`, with attachment disposition. The PDF embeds local Inter and handwriting-style signature fonts, a cost table, clickable contents, page numbers, an orange-to-white top strip and the kontrolcheckout.com footer. The contract text/evidence always comes from its saved snapshot; visual revisions do not re-sign it.

#### 4. Client acceptance is interactive

An agent may prepare and retrieve a draft, but must hand review/signing to the authenticated client in the dashboard. API keys cannot sign, even with `settings.write`.

The dashboard signing step (dashboard session only, not part of the client API) submits `{contentHash,signature,acceptAgreement:true}`. The hash is the exact 64-character lowercase hexadecimal `content_hash` from detail, the typed signature must match the client's saved full name (up to 201 characters), and acceptance must be explicit. Conflict/stale content or a conflicting repeat signature returns 409. A successful response contains `{agreement}` with acceptance timestamp, authenticated operator and evidence. Never synthesize these fields locally or treat the provider mark as client acceptance.

This records ordinary electronic acceptance, not an independently certified or qualified signature ceremony. Exact terms are in the generated document.

### Platform subscription

Configure Kontrol client offers in **Admin → Subscriptions**. These subscriptions are separate from merchants' customer subscription products and rebill schedules.

| Initial offer | Price | Stores | Monthly captured sales |
| --- | --- | --- | --- |
| Standard | USD 799 / month | 5 | USD 250,000 |
| Unlimited | USD 2,499 / month | Unlimited | Unlimited |

Both initial offers include every listed management tool. Other commercial quotas are unlimited. There is no percentage fee on sales. Configure the name, description, availability, price, billing interval, included tools, store limit, monthly sales limit and quota currency conversions.

Existing accounts receive no automatic plan assignment or price change. Every assignment and billing mandate records the exact offer revision. Editing or archiving an offer does not change an existing account's accepted price, quota, conversion rates or tools. Archiving prevents new signup and assignment. Apply revised terms to a manual grant through an explicit reassignment. Existing paid contracts cannot be silently replaced through onboarding.

#### Signup and plan selection

Start at `/onboarding`. Select an available offer, enter an email and password, then provide first name, last name, Telegram contact, company name, company postal address and estimated monthly volume. Accept the terms and automatic billing separately.

The onboarding page reads active `plans`, consent wording and password requirements from `GET /auth/signup` and submits the selected `planId` and `planRevision` with `POST /auth/signup` (public signup, not part of the client API). A changed or archived offer returns HTTP 409; refresh before accepting its current terms. The accepted price and cadence are snapshotted into the mandate and invoice. No access is granted by signup or an invoice preparation.

Signup creates a new login immediately, without a verification email, code or link. Passwords require at least 12 characters and at most 72 UTF-8 bytes. The API never accepts a client-selected role, parent account or paid status. Existing emails, including team logins and preprovisioned accounts, must sign in instead; signup cannot claim an existing account or change its password. After an interrupted response, try signing in.

Authenticated onboarding retains the account's existing role and ownership. Consent evidence includes the server timestamp, actor, Auth user ID, request IP and user agent, profile, exact offer revision, mandate text and evidence fingerprint. Repeated acceptance does not alter original mandate evidence. Legacy mandates without a plan snapshot retain their original amount and monthly cadence. New CRM agreement drafts likewise use the assigned offer amount, cadence and revision in their saved commercial schedule and PDF. Existing drafts and signed agreements retain their saved terms; selecting or granting a different plan does not rewrite or automatically sign them.

#### Account access

| Status | Meaning |
| --- | --- |
| `paid` | A verified provider payment or existing bootstrap entitlement grants access within the user's role and assigned offer. |
| `granted` | A platform administrator explicitly granted access. `source: manual` is not a provider payment. |
| `unpaid` | Sign-in, own identity/preferences, onboarding and subscription recovery remain available. Protected operations return HTTP 402 `subscription_required`. |

Every team login inherits its current main account's subscription. A grant or payment never raises a user's role, bypasses a ban or expands ownership to another account. Browser redirects, authorizations, pending invoices and posted status values cannot establish paid access. Signed private editor previews recheck current access; signatures do not preserve access after expiry.

The paywall does not mount a hidden usable dashboard or fetch its protected data. Completion and reconciliation of already submitted payments and refunds remain possible after expiry. A new manual refund requires active access.

#### Manual grants

Open **Users → Subscription → Actions → Grant access**, select an offer, choose an optional expiry and enter a reason. Assignment records `granted` access, never a paid invoice or gateway sale. It cancels future platform renewal and voids only unsubmitted preparations. Already submitted payments retain their settlement path.

Removal denies access immediately to the main account and its members, and stops renewal. Legacy accounts can be revoked directly, without assigning a fictitious offer: the revoked assignment has `plan: null`. Expired or revoked grants cannot be bypassed by resuming self-serve billing. Financial records remain unchanged. Main platform administrator accounts retain their protected existing access.

Only a signed-in human `super_admin`, outside impersonation, can manage plans or assignments. API keys and tenant administrators cannot. Children cannot receive independent grants. Optimistic revisions prevent overwriting concurrent edits, and every mutation records an audit event.

#### Included tools

Included tools govern their management endpoints. They never grant additional user permissions or interrupt customer payment completion, reconciliation or shared resource pickers. **API key management** controls key administration; it does not disable configured payment integrations or published customer checkouts.

#### Quota accounting

Store usage counts distinct owned, nonarchived stores, including inactive stores. Creation and linking a new store check the limit while holding the account lock. Concurrent creations cannot both consume the last available slot. Existing owned stores remain editable at the limit.

Sales usage covers the UTC calendar month, from its first day inclusive to the next month exclusive. Captured gross sales count once, including straight, recovery, upsell and rebill sales. Test transactions, imports and authorization-only operations are excluded. Refunds do not restore quota.

The sales limit stops new payment admission. Already submitted or authentication-pending payments and reconciliation can finish. Concurrent payments admitted before the threshold can therefore take the final total above it; it is not a reservation of future revenue.

Conversion rates are configured **only for quota accounting**, in USD per major currency unit. USD is fixed at 1. They do not change prices or settlement currency. Rates are pinned with the assigned offer revision. Only USD is seeded; no exchange rate is guessed. Unconfigured captured currencies return `usedUsdCents: null` and `missingCurrencies`. New admission on a sales-limited offer pauses until an administrator configures and reassigns the revision. Unlimited offers are not blocked by unused conversions.

#### Billing lifecycle and provider readiness

**The platform billing processor will be integrated separately.** Merchant gateways are exclusively for merchants' payments and are never selected to collect Kontrol subscriptions. The current screen reports collection as unavailable and renders no card entry fields. Platform billing endpoints never accept or store PAN or CVV.

The owner's dashboard checkout step (`POST /v1/platform-subscription/checkout`, dashboard session only, not part of the client API) accepts only `{idempotencyKey: UUID}` and prepares a durable invoice plus an `awaiting_provider` attempt. Retries reuse the outstanding invoice and active attempt. Its response contains `checkoutAvailable: false`; it does not charge or grant access.

A provider-verified successful payment activates the paid period. The accepted interval is 1–36 months and preserves the original UTC anniversary. A monthly January 31 anniversary renews on February's last day, then March 31. The preparation worker uses the existing leadership lease and development-machine background-job guard. It expires paid periods and prepares at most one outstanding renewal; it never calls a gateway.

Failed attempts remain recorded and confer no new access. Provider event and payment IDs are deduplicated. A late older settlement cannot shorten a newer paid period. Canceling renewal preserves an already paid period and stops future preparation. Unpaid, unsubmitted preparations can be canceled immediately. Resume uses the accepted mandate and grants no access itself.

Resuming before expiry preserves the anniversary. Restarting after effective cancellation begins a new period with the next verified payment, without billing canceled months. A submitted payment must finish before its invoice can be replaced. A manual grant or revocation prevents new billing dispatch while allowing a previously submitted payment to reconcile.

#### Manage a user's subscription

The user modal's **Subscription** tab contains **Overview**, **Access & limits**, **Invoices** and **History**. Overview displays the actual current plan snapshot, access source, access expiry, paid service period, next renewal date and amount, consent date and payment-provider readiness. A manually granted account has no fabricated paid period, payment or renewal date. The catalog price for a grant is explicitly labelled as a catalog price.

Use the shared **Actions** menu to grant or remove access, cancel or resume renewal, propose a different paid offer, or cancel a pending plan change. Canceling renewal preserves the existing paid period; removing access is immediate. Every management mutation requires a reason and the current version. A concurrent change returns HTTP 409 instead of overwriting it.

A paid-plan change records an immutable proposal. The main owner reviews its exact price, interval, tools, limits and recurring authorization in `/subscription`, then explicitly accepts both terms. Administrator actions never substitute for owner consent. Accepted changes take effect only when their next invoice payment is verified; they do not relabel the current paid period. No proration or immediate charge is performed. Withdrawals cancel only unsubmitted work; an already submitted payment returns a conflict and retains its reconciliation path.

Billing management uses an account-scoped UUID `requestId` plus `expectedVersion`. After a network interruption, retry the same request and ID; after a 409 stale-version response, reload and review before submitting a new decision. Do not generate a new request ID merely because the first response was lost.

#### Invoices

Admin and owner views share the same paginated invoice table, status filters, details modal and authenticated PDF download. The table supports current-page and selected-row CSV/PDF exports. The invoice modal shows the saved offer, service period, due/paid dates, provider reference, billing identity and payment attempts. These are read-only financial records; there is no bulk editing of payment status.

Each invoice is **open**, **paid** or **void**. An open invoice is not a receipt, and a void document is not payable. PDFs use recorded seller, buyer and offer snapshots; unavailable historical identity or tax breakdowns are identified as unrecorded rather than invented. Granting access does not issue a paid invoice. No public or administrator endpoint accepts a posted `paid` status.

The owner endpoints are `/v1/platform-subscription/invoices`, `/invoices/:id` and `/invoices/:id/pdf`. Only the non-impersonating main owner with a human session can use them. Members, API keys and impersonation cannot retrieve billing documents. Platform administrators use their own routes, which are not part of the client API. All invoice lookups enforce account ownership and return private, non-cacheable responses.

#### Platform administration

Offers, grants, renewals, plan-change proposals and per-account invoice views are managed by Kontrol platform administrators through platform routes that require a human platform administrator session. They are not part of the client API, and an API key cannot call them.

An offer lists its included tools as module identifiers, for example `stores`, `products`, `checkouts`, `flows`, `pages`, `affiliates`, `payments`, `subscriptions`, `reports`, `recovery`, `integrations`, `api` and `team`. Either limit (stores, monthly sales) can be unlimited; zero is a valid quota. A manually managed or revoked account cannot start self-serve billing (`billing_access_managed`).

#### Requirements before connecting billing

The settlement boundary is internal, with no public HTTP endpoint. A provider adapter must verify callback signatures, fetch authoritative capture data, and match the account, invoice, attempt, provider, amount and currency. It must claim a prepared attempt once and reuse its stable ID for provider idempotency. Redirect parameters or arbitrary status posts must never invoke settlement.

The provider connection must configure hosted card fields, authentication such as 3D Secure, payment-method replacement, receipts, applicable taxes, signed lifecycle callbacks and verified refund/dispute handling. The preparation-only implementation does not represent these features as connected.

#### New-account operating setup

After registration and an explicit administrator access grant, the Standard and Unlimited offers expose all initial management modules. A new account starts with an empty private catalog and resources; it does not inherit another merchant's stores, ATRIs, credentials or API keys.

Configure the resources the business intends to use: store/domain and catalog, a published checkout or flow, account-owned payment integrations and routing, then shipping, tracking, messaging or affiliate integrations as required. API keys are created explicitly with their allowed operations and owned ATRIs. Empty reports are valid for an account without transactions; they are not evidence of working external payment delivery.

Adding a team member is create-only: an existing authentication identity cannot have its password reset or be silently claimed by a different account. Concurrent member creation and role edits enforce account ownership under database locks. All team access still inherits the main account's current subscription and ban state.

#### Authentication deployment

Configure `SUPABASE_URL` and server-only `SUPABASE_SERVICE_ROLE_KEY` on the API. Public signup uses this credential to create a new password identity with automatic confirmation. It is never returned to a browser and sends no invitation, recovery or verification email. Automatic confirmation is not proof of email ownership. Signup has separate IP and normalized-email rate limits per API process.

Authenticated onboarding rechecks user ID and email against live Supabase Auth, using `SUPABASE_ANON_KEY` or `NEXT_PUBLIC_SUPABASE_ANON_KEY` with the user's Bearer token, falling back to the server key. `SUPABASE_JWT_SECRET` alone cannot perform that check. Missing Auth connectivity fails closed.

New password identities carry an administrator-owned `platform_signup: password-v1` Auth marker and must match their stored onboarding Auth UUID. Legacy identities retain their existing confirmation requirement. An unbound public-signup JWT cannot claim a preprovisioned account through email alone, including through browser RLS.

Account, profile, assignment and consent writes share one transaction. A confirmed rollback removes only the identity freshly created by that signup. An ambiguous commit preserves the login for recovery; it never deletes a possibly committed account. Recovery cannot attach a fresh identity to a pre-existing main or child account.

### Creative integrations

V5 supplement reviewed 2026-10-30: *Commerce workflows* in Part 2 documents current standalone offers, link attribution/privacy, page/flow publication and payment boundaries. Existing non-V5 contracts below retain their endpoint-specific behavior.


Source audit: 18 October 2026. This describes the implemented Kontrol API, not the capabilities advertised by external providers.


Current operations supplement (2026-10-22): authentication, reporting and job recovery in *Operations, reporting and current behavior* in Part 2, the complete method/path and scope index in the endpoint index (Part 3), and account agreement generation in *Account agreements* in Part 2. Use the endpoint reference (Part 4) for endpoint-specific restrictions; a visible UI action does not imply API-key authorization.

#### What an agent can actually do

| Capability | Implemented Kontrol interface |
|---|---|
| Configure/test OpenAI, Anthropic, Fal.ai, Higgsfield | Account integrations API |
| Generate homepage copy with Anthropic | Durable homepage jobs; legacy synchronous generation also exists |
| Generate arbitrary product descriptions or checkout copy | Creative jobs using saved OpenAI or Anthropic integration |
| Generate images/video using Fal.ai or Higgsfield | Creative jobs with durable provider handles and explicit polling |
| Import existing image/video bytes or URLs | Store assets and product-media APIs |
| Attach media/text to native checkout, landing, post-sell or Thank-you blocks | Read the page’s actual document, edit its draft with its current revision, preview, then publish with merchant rights |

The common generation route is `/v1/integrations/creative/jobs`. Generated results are not automatically published or attached to a store. There is no agent-specific model endpoint. Do not invent `/v1/ai/generate` or `/v1/fal/jobs` routes.

#### Authentication and account boundaries

Base URL: `https://api.kontrolcheckout.com`. Send `Authorization: Bearer <KONTROL_API_KEY>` with an API key of the account. Human dashboard sessions use their existing JWT. All operations retain account/role checks; another account's store is not accessible through an ID.

Current scoped-key categories are significant:

- Integrations and creative jobs: `integrations.read` for GET, `integrations.write` for PUT and POST, including polling.
- Store assets, product content, checkout documents: `checkouts.read` / `checkouts.write`.
- Homepage jobs: **`reports.read` / `reports.write`**, as currently classified by `apiScopeFor`; do not assume `checkouts.write` alone enables them.

Job creation/application additionally revalidate an account administrator (or super admin) principal, store ownership, account availability and integration configuration. Scope grants never override those checks; an API key always acts as the account administrator. `GET /v1/integrations/:key/secrets` is a human-session secret reveal, unavailable to API keys. An agent should use saved credentials server-side, not request their plaintext.

#### Configure and test providers

Read `GET /v1/integrations`: `catalog` describes supported fields and `items` describes the caller's saved integration state. Save with `PUT /v1/integrations/:key`:

```json
{"enabled":true,"config":{"model":"YOUR_VERIFIED_MODEL_ID"},"secrets":{"apiKey":"SUPPLIED_PROVIDER_KEY"}}
```

Omitted secrets remain stored; an explicit empty string or null clears a saved secret. Never put real keys in generated docs or builder documents. Query the catalog rather than assuming model names are current provider offerings.

| Key | Non-secret config fields | Secret fields | Connection test |
|---|---|---|---|
| `openai` | `model`, `baseUrl`, `organizationId` | `apiKey` | GET provider `/models` |
| `anthropic` | `model`, `baseUrl`, `anthropicVersion` | `apiKey` | GET provider `/v1/models` |
| `fal` | `model`, `queueUrl` | `apiKey` | Authenticated model-pricing lookup, **not generation** |
| `higgsfield` | `model`, `baseUrl` | `apiKey`, `apiSecret` | Random nonexistent request-status lookup, **not generation** |

`POST /v1/integrations/:key/test` accepts `{}` to test saved settings, or `{config,secrets}` for unsaved values. Nonempty supplied secret values override saved ones for the test; blank supplied values retain saved values here, unlike PUT. Testing can run while the integration is disabled. Returns `{ok,detail}`, including elapsed `ms`; a completed failed credential check normally still returns HTTP 200 with `ok:false`. Unknown/unsupported verifier: 404; malformed body: 400; missing account: 403. The provider call is bounded to 10 seconds.

Fal's test may include `endpoint`, `unitPrice`, `unit`, `currency`. This is model unit pricing, not a quote or a debit. Higgsfield's verifier treats provider HTTP 200 or 404 as credentials accepted; that does not establish model availability or sufficient generation credit. OpenAI/Anthropic tests return model counts, not a generated result. These tests do not submit generation requests.

Other integrations are discovered through the same catalog, but their dedicated operations differ: domain/DNS management, messaging, tracking or payment integrations must not be treated as creative generators. Use their own endpoint documentation.

#### General creative jobs: writing, images and video

Requires database migration `242_creative_jobs.sql`. Configure and enable the account integration first. Create a job:

```http
POST /v1/integrations/creative/jobs
Authorization: Bearer <KONTROL_API_KEY>
Content-Type: application/json
```

```json
{"requestId":"7d14e9da-2c4b-47a7-a10a-f7aa24c92e51","provider":"openai","model":"YOUR_VERIFIED_MODEL_ID","input":{"prompt":"Write an accurate product introduction using these supplied facts: ...","system":"Do not invent features or reviews.","maxTokens":1000}}
```

`provider` is `openai`, `anthropic`, `fal` or `higgsfield`. Omit `model` to use the saved integration model. Model identifiers accept letters, digits, underscores, hyphens and slash/dot-separated segments (200 characters maximum). For Fal/Higgsfield, `input` is the selected model's documented JSON input, such as `{ "prompt":"..." }`; required dimensions, duration, reference images and other fields depend on that model. Request body limit: 128 KiB. There is no generic model-discovery route: verify the exact model and its schema in official provider documentation.

Writing input accepts only `prompt` (required, nonempty, at most 30,000 characters), optional `system` (10,000 characters) and integer `maxTokens` (default 2,000; OpenAI 16–8,000, Anthropic 1–8,000). OpenAI uses Responses; Anthropic uses Messages. These calls execute within the initial POST, bounded to 20 seconds, and are persisted as jobs; they are not background writing workers. Fal/Higgsfield submit asynchronous provider jobs. Every provider response is bounded to 1 MiB and redirects are rejected.

Creation returns HTTP 202 `{job}`; replaying the same account/request ID and identical body returns 200 and never submits again. Reusing the ID with different input returns 409. The row is persisted before contacting the provider, including under concurrent submissions with the same ID. Different request IDs are independent jobs and can incur separate charges; there is no account spending cap or automatic concurrency cap.

Read `GET /v1/integrations/creative/jobs/:id` for local state. For `queued` or `running` media jobs call `POST /v1/integrations/creative/jobs/:id/poll` to contact the provider and persist progress/result. GET does not poll remotely. Wait 2–5 seconds between polls and back off on errors. Terminal polling returns the stored result without another provider request. Another account's job returns 404.

The public job includes `id`, `request_id`, `provider`, `model`, `status`, `provider_id`, `result`, `error`, `created_at` and `updated_at`. States are `submitting`, `queued`, `running`, `completed`, `failed`, `uncertain` and `cancelled`. `result` preserves the provider response: inspect OpenAI `output` text content, Anthropic `content` text blocks, Fal model-specific media fields or Higgsfield `images[].url`/`video.url`. An OpenAI incomplete response or truncated Anthropic response is `failed`, retaining the response for inspection. A Fal completed status containing an error is also `failed`.

There is deliberately no automatic submission retry. A lost response, provider rejection during submission or timeout is conservatively recorded as `uncertain`; inspect provider usage before choosing a fresh ID. A `submitting` job older than 60 seconds becomes `uncertain` when read. Invalid local writing input becomes `failed`. Provider polling failure returns 502 without replacing the saved state: retry **polling**, not submission. Missing active integration is 422; malformed request is 400; missing account is 403; inaccessible job is 404; unavailable persistence is 503. A 202 response can contain a failed or uncertain job, so always inspect `job.status`.

Only official provider origins are permitted for generation and saved polling/result URLs; custom proxies are rejected with 422. Higgsfield uses the account's saved `apiKey` plus `apiSecret` as its combined provider credential. Changing/disabling credentials can prevent subsequent polling. No credentials are exposed in job responses. Provider calls can incur costs even when a local request times out; no price quote, token-cost ledger, cancellation endpoint or automatic media import is implemented. Cancel at the provider if needed. Generated URLs can expire: import approved assets before publishing them.

Provider lifecycle references: [OpenAI reasoning and incomplete responses](https://developers.openai.com/api/docs/guides/reasoning), [Fal queue lifecycle](https://fal.ai/docs/documentation/model-apis/inference/queue), [Higgsfield quick start](https://open.higgsfield.ai/quick-start). These define provider behavior; Kontrol's bounds and routes above are the implemented contract.
#### Homepage writing: durable workflow

1. `GET /v1/home-ai/jobs/capabilities` returns `{enabled,localOnly:true}`. Availability requires `HOME_AI_JOBS_ENABLED=true`, background workers enabled, local checkout data and the jobs table.
2. `POST /v1/home-ai/jobs` with `{ "shopId":"STORE_UUID", "requestId":"FRESH_UUID" }` returns HTTP 202 `{job}`. The body is strict: no arbitrary prompt, provider, model or product ID is accepted. An active, configured Anthropic integration is required.
3. Poll `GET /v1/home-ai/jobs/:id`. A 2–5 second interval with backoff is an agent recommendation, not a server-enforced polling contract. `GET /v1/home-ai/jobs?shopId=STORE_UUID` lists the latest 20 jobs for this scope/store.
4. When `status` is `ready`, inspect `job.proposal`. It has optional `homeIntro`, `homeStory`, `homeTestimonials`, `homeFaq`; it is not an EditorDocument, product page or media file. Review factual claims and use genuine customer evidence; do not publish invented testimonials.
5. `POST /v1/home-ai/jobs/:id/apply` merges the proposal into store homepage settings only if the storefront and Anthropic integration revisions still match. Reapplying an already-applied job is safe. Re-read the returned status: a storefront conflict can return HTTP 200 with `status:"conflict"`, preserving current edits.
6. `POST /v1/home-ai/jobs/:id/cancel` discards queued/ready work; for generating work it sets `cancel_requested`. It does not guarantee a provider refund.

States: `queued`, `generating`, `ready`, `applied`, `failed`, `uncertain`, `cancelled`, `conflict`. `ready` is not published. Responses expose identifiers, state, timestamps, `fields`, errors and cancellation/cache-refresh state; the single-job GET also includes `proposal`. Private scope hashes, credentials, leases and revision fingerprints are omitted.

Reuse the **same requestId** after an ambiguous creation response. It is idempotent for the same principal/scope/store; a mismatched reuse is 409. An account can have only one queued/generating job, and a store cannot have another queued/generating/ready generation; conflicts return 409 with a `jobId`. Missing Anthropic configuration: 422. Unavailable feature: 503. Missing/inaccessible job/store: 404; changed permissions: 403.

The worker builds bounded store/catalog/review context, requests at most 3,000 output tokens with a 20-second provider bound and 256 KiB response cap, then validates a proposal no larger than 64 KiB. A lost worker/provider outcome becomes `uncertain`; **do not blindly create a new paid request**. Read the job and provider usage first. There is no token-cost ledger, price quote or generation-budget parameter in this API. A provider may charge even if local processing times out or cancellation arrives later.

Legacy `POST /v1/checkouts/:shopId/storefront/generate` also calls Anthropic, but writes generated homepage fields immediately and returns `{ok:true,fields:[...]}` (502 `{ok:false,error}` on generation failure). It has no proposal review, durable job ID or idempotency key. Prefer the durable flow when available; do not silently fall back to a second provider request after an uncertain job.

#### Media import and attachment

After a creative job completes, inspect its result and download the intended media using your agent HTTP client. Upload its actual bytes through the store asset route below, or attach an approved media URL through product media. Generation does not attach or publish automatically. Saved provider credentials remain server-side.

For store/builder media, use:

```http
POST /v1/checkouts/STORE_UUID/assets?content_type=image%2Fwebp&prefix=hero
Authorization: Bearer <KONTROL_API_KEY>
Content-Type: application/octet-stream

<actual file bytes>
```

The raw-byte upload avoids base64 overhead. Legacy JSON `{content_type,data_base64,prefix?}` is also supported. Response: `{url,path}`. Supported MIME types: PNG, JPEG, WebP, GIF, MP4, WebM. Maximum decoded file size: 20 MiB. Unsupported type: 415; oversized: 413; empty raw body/missing raw MIME: 400; storage failure: 502. Store-asset MP4 uploads reject a detectable trailing `moov` index with 422; prepare a fast-start MP4. Upload creates a public immutable URL; it does **not** attach it to a block automatically.

For a product gallery:

- `POST /v1/checkouts/:shopId/products/:pid/media` with `{url,kind:"image",alt:"Accurate product description",rehost:true,variant_id:null}` returns HTTP 201 media row. `kind` can be `video`. External image rehosting is best effort; verify the returned URL instead of assuming it was copied.
- `POST /v1/checkouts/:shopId/products/:pid/media/upload` accepts JSON `{content_type,data_base64,alt?,variant_id?}` and returns HTTP 201 media row. Same six MIME types and 20 MiB decoded limit; raw octet-stream is **not** supported on this product route. Route transport cap is 30 MiB.
- `PUT .../media/:id` updates `alt`, `position`, `variant_id`; `POST .../media/:id/move` accepts `{dir:"up"}` or `{dir:"down"}`. A variant association updates the selected variant's image. Both store ownership and product membership are checked.

For written product content, `PUT /v1/checkouts/:shopId/products/:pid` accepts a partial patch such as `{description:"...",seo_title:"...",seo_description:"..."}`. Preserve pricing/options; content generation must not silently modify them. Description limit is 100,000 characters, SEO title 200, SEO description 500. Product sections have their separate replace-all endpoint; GET and preserve existing entries before replacing.

For checkout blocks, obtain the actual catalog/document and use the image/video block's declared URL field or a supported store/product variable. Do not guess block types or set arbitrary HTML. Save through `PUT /v1/checkouts/profiles/:id/document/draft` with `{document,baseRevision}`, inspect validation issues, preview, then publish with `POST .../document/publish` and `{baseRevision,note}`. A 409 means re-read/merge, not overwrite a concurrent edit. A 422 means fix document issues. Uploading an asset, saving a draft and publishing are three distinct steps.

#### Verification and limits

External provider model availability and prices are not asserted here; inspect current catalog and authenticated provider responses at execution time.


#### Hand generated content to the native V5 builder

For a checkout, discover registered fields and templates through the checkout-only editor catalogue. For Landing, Post-sell or Thank-you, read that page’s actual document resource and start from its draft/published/default document. Use *Commerce workflows* in Part 2 for the save/publish endpoints and revision contract. There is no separate creative API that publishes a flow or authorizes a purchase.

Use generated copy and media as inputs to native text, image, video and layout blocks. Keep the page editable: a screenshot pasted into one image block is not a reconstruction of its content. Native Popup uses a real document trigger or delay and cannot hide protected payment controls. Preserve required controls, action bindings, shared style parameters and localized content. Do not inject generated scripts to bypass the renderer or load pixel server credentials.

A standalone saved offer can attach its own independent product name, image, variant label and price without creating a catalogue product or store. The link pins these commercial terms separately from the reusable checkout design. Post-sell offers instead select owned catalogue configurations; generated descriptions cannot change their published price, quantity, selected offer ID, initial card or MID. Never manufacture reviews, receipts, paid status, support destinations or financial totals as creative copy.

Preview the saved document at desktop/tablet/mobile widths before publication. Canvas and signed previews are inert: a rendered Pay, Accept or Thank-you block does not prove a capture, delivery, provider integration or conversion. Review real supplied assets and dynamic bindings, then have the authorized merchant publish the intended revision.

## 3. Endpoint index

One line per endpoint, by category and subcategory, in the order of Part 4. Address, required scope, title.

### Getting started

#### Authentication and identity

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/me` | `settings.read` | Identify the API key and its account (account id, key label, default ATRI) |

#### API keys and permissions

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/keys` | `api_keys.read` | List API keys |
| POST | `/v1/keys` | `api_keys.write` | Create an API key |
| PATCH | `/v1/keys/:id` | `api_keys.write` | Update a key |
| DELETE | `/v1/keys/:id` | `api_keys.write` | Delete a key |
| GET | `/v1/keys/:id/reveal` | `api_keys.write` | Reveal a raw key |
| GET | `/v1/keys/scopes` | `api_keys.read` | List the API key permission catalog |

#### Search and entity summaries

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/entities/product` | `*.read` | Summarise a sold product |
| GET | `/v1/entities/storefront` | `*.read` | Summarise a storefront |
| GET | `/v1/search` | `*.read` | Global search (command palette) |

#### Errors, limits and service status

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/health` | `operations.read` | Check that the API and its database answer |
| GET | `/v1/openapi.json` | `operations.read` | Get the OpenAPI document |
| GET | `/v1/operation-capabilities` | `operations.read` | Read background operation availability |
| GET | `/v1/perf` | `operations.read` | Read your API traffic performance (latency, errors, recent minutes) |

### Overview

#### Dashboard

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/alerts` | `reports.read` | Get dashboard alerts |
| GET | `/v1/metrics/atri-activity` | `reports.read` | ATRI Activity |
| GET | `/v1/metrics/series` | `reports.read` | Filtered Chart Series |

#### Transactions

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/filters/facets` | `routing.read` | Get every option of the unified filter |
| GET | `/v1/transactions` | `transactions.read` | List transactions (dashboard list: all columns, filters, sort) |
| POST | `/v1/transactions` | `transactions.read` | Sync transactions of a date window (partner shape, paged) |
| GET | `/v1/transactions/:id/card` | `transactions.write` | Read a transaction's card number in clear |
| GET | `/v1/transactions/:id/details` | `transactions.read` | Get a transaction's full record (attempts, basket, 3DS, fees, pipeline, attribution) |
| GET | `/v1/transactions/:id/events` | `transactions.read` | Order / charge timeline (transaction modal Logs tab) |
| GET | `/v1/transactions/:id/events/export.csv` | `transactions.read` | Order / charge timeline as CSV |
| POST | `/v1/transactions/:id/retry` | `charges.write` | Retry a declined card sale |
| GET | `/v1/transactions/:transactionId` | `transactions.read` | Get a transaction (partner summary with refund history) |
| POST | `/v1/transactions/:transactionId/note` | `transactions.write` | Add a note to a transaction |
| GET | `/v1/transactions/:transactionId/notes` | `transactions.read` | Read a transaction's note thread |
| POST | `/v1/transactions/bulk` | `transactions.write` | Bulk-edit transactions |
| GET | `/v1/transactions/bulk-jobs` | `transactions.read` | List transaction bulk jobs |
| POST | `/v1/transactions/bulk-jobs` | `transactions.write` | Start a transaction bulk job |
| GET | `/v1/transactions/bulk-jobs/:id` | `transactions.read` | Read a transaction bulk job |
| POST | `/v1/transactions/bulk-jobs/:id/cancel` | `transactions.write` | Cancel a transaction bulk job |
| GET | `/v1/transactions/bulk-jobs/:id/errors` | `transactions.read` | List a transaction bulk job failures |
| GET | `/v1/transactions/bulk-jobs/:id/result` | `transactions.read` | Read a transaction bulk job result |
| POST | `/v1/transactions/charge` | `charges.write` | Charge one manual card sale (ATRI or a pinned MID) |
| GET | `/v1/transactions/export` | `transactions.read` | Export transactions CSV |
| GET | `/v1/transactions/facets` | `transactions.read` | Get filter dropdown values |
| GET | `/v1/transactions/ids` | `transactions.read` | List transaction ids matching filters (select all) |
| DELETE | `/v1/transactions/notes/:noteId` | `transactions.write` | Delete a transaction note |

### Payments

#### Charging

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/charge` | `charges.write` | Charge orders (one order or a batch) |
| GET | `/v1/charge/orders/:orderId` | `charges.read` | Read a submitted payment or recover its saved bank challenge |
| POST | `/v1/charge/status` | `charges.read` | Recover the status of charges |
| POST | `/v1/checkout/pre-auth` | `charges.write` | Verify a card for an explicitly selected subscription |
| GET | `/v2/rebill-batches` | `charges.read` | List reference rebill batches |
| POST | `/v2/rebill-batches` | `charges.write` | Queue reference rebills |
| GET | `/v2/rebill-batches/:id` | `charges.read` | Read a reference rebill batch |
| POST | `/v2/rebill-batches/:id/cancel` | `charges.write` | Cancel undispatched rebills |
| POST | `/v2/rebill-batches/:id/resume` | `charges.write` | Re-check unresolved rebills |

#### 3-D Secure

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/3ds/sessions` | `charges.write` | Start a 3DS authentication session |
| GET | `/v1/3ds/sessions/:id` | `charges.read` | Get / advance a 3DS session |
| POST | `/v1/3ds/sessions/:id/complete` | `charges.write` | Complete a browser step of a 3DS session |

#### Gateways

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/accounts` | `routing.read` | List card gateways (MIDs) with this month's usage |
| POST | `/v1/accounts` | `routing.write` | Create gateway |
| PATCH | `/v1/accounts/:id` | `routing.write` | Update gateway |
| DELETE | `/v1/accounts/:id` | `routing.write` | Delete gateway |
| POST | `/v1/accounts/:id/archive` | `routing.write` | Archive gateway |
| GET | `/v1/accounts/:id/credentials` | `routing.write` | Read gateway credentials |
| POST | `/v1/accounts/:id/duplicate` | `routing.write` | Duplicate gateway |
| POST | `/v1/accounts/:id/restore` | `routing.write` | Restore an archived gateway |
| POST | `/v1/accounts/convesio/connect` | `routing.write` | Mint ConvesioPay secret key |
| POST | `/v1/accounts/import` | `routing.write` | Bulk-import gateways |
| GET | `/v1/acquiring-banks` | `routing.read` | List acquiring banks |
| POST | `/v1/acquiring-banks` | `routing.write` | Add an unlisted acquiring bank |
| GET | `/v1/categories` | `routing.read` | List categories |
| POST | `/v1/categories` | `routing.write` | Create a category |
| PATCH | `/v1/categories/:id` | `routing.write` | Rename a category |
| DELETE | `/v1/categories/:id` | `routing.write` | Delete a category |
| GET | `/v1/companies` | `routing.read` | List companies |
| POST | `/v1/companies` | `routing.write` | Add an unlisted company |
| POST | `/v1/convesio/s2s-test` | `charges.write` | Test a ConvesioPay S2S charge |
| GET | `/v1/processors` | `routing.read` | List processors |
| POST | `/v1/processors` | `routing.write` | Add an unlisted processor |
| GET | `/v1/stripe/options` | `charges.read` | List available Stripe checkout modes |
| GET | `/v1/v5/flow-payment-capabilities` | `routing.read` | List post-purchase payment readiness |
| PUT | `/v1/v5/flow-payment-capabilities/:midId` | `routing.write` | Revoke a historical Vault opt-in |

#### Wallet providers

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/wallet-providers` | `routing.read` | List wallet gateways (Apple Pay / Google Pay MIDs) |
| POST | `/v1/wallet-providers` | `routing.write` | Create wallet MID |
| GET | `/v1/wallet-providers/:id` | `routing.read` | Get wallet MID |
| PATCH | `/v1/wallet-providers/:id` | `routing.write` | Update wallet MID |
| DELETE | `/v1/wallet-providers/:id` | `routing.write` | Delete wallet MID |
| GET | `/v1/wallet-providers/:id/cert-probe` | `routing.read` | Probe Apple cert |
| POST | `/v1/wallet-providers/:id/create-domain` | `routing.write` | Provision Render domain |
| GET | `/v1/wallet-providers/:id/credentials` | `routing.write` | Read a wallet MID's stored secrets (in clear) |
| POST | `/v1/wallet-providers/:id/enable-methods` | `routing.write` | Enable wallet methods |
| GET | `/v1/wallet-providers/:id/status` | `routing.read` | Apple Pay readiness |
| POST | `/v1/wallet-providers/:id/test-session` | `routing.write` | Open a test Apple Pay sheet |
| POST | `/v1/wallet-providers/:id/verify-domain` | `routing.write` | Verify Render domain |
| POST | `/v1/wallet-providers/bootstrap` | `routing.write` | Bootstrap MID via Convesio |
| GET | `/v1/wallet-providers/bootstrap-capabilities` | `routing.read` | Read wallet setup availability |
| GET | `/v1/wallet-providers/bootstrap-jobs` | `routing.read` | List wallet setups |
| POST | `/v1/wallet-providers/bootstrap-jobs` | `routing.write` | Start a wallet setup |
| GET | `/v1/wallet-providers/bootstrap-jobs/:id` | `routing.read` | Read a wallet setup |
| POST | `/v1/wallet-providers/bootstrap-jobs/:id/cancel` | `routing.write` | Cancel a wallet setup |
| POST | `/v1/wallet-providers/bootstrap-jobs/:id/reconcile` | `routing.write` | Confirm an uncertain hostname registration |

#### Bank accounts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/bank-accounts` | `routing.read` | List bank accounts |
| POST | `/v1/bank-accounts` | `routing.write` | Add a bank account |
| GET | `/v1/bank-accounts/:id` | `routing.read` | Get a bank account |
| PATCH | `/v1/bank-accounts/:id` | `routing.write` | Update a bank account |
| DELETE | `/v1/bank-accounts/:id` | `routing.write` | Deactivate a bank account |

#### Card ATRIs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/atris` | `routing.read` | List routable ATRIs (id, name, default) |
| GET | `/v1/trips` | `routing.read` | List ATRIs with configuration, member MIDs and month usage |
| POST | `/v1/trips` | `routing.write` | Create an ATRI |
| PATCH | `/v1/trips/:id` | `routing.write` | Update an ATRI |
| DELETE | `/v1/trips/:id` | `routing.write` | Delete an ATRI |
| PUT | `/v1/trips/:id/accounts` | `routing.write` | Replace ATRI members |
| POST | `/v1/trips/:id/archive` | `routing.write` | Archive an ATRI |
| POST | `/v1/trips/:id/default` | `routing.write` | Toggle the default ATRI |
| GET | `/v1/trips/:id/dispatch-share` | `routing.read` | Read smart dispatch share |
| POST | `/v1/trips/:id/duplicate` | `routing.write` | Duplicate an ATRI |
| POST | `/v1/trips/:id/restore` | `routing.write` | Restore an archived ATRI |

#### Wallet and wire ATRIs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/payment-atris` | `routing.read` | List wallet and wire ATRIs |
| POST | `/v1/payment-atris` | `routing.write` | Create a wallet or wire ATRI |
| PATCH | `/v1/payment-atris/:id` | `routing.write` | Edit a wallet or wire ATRI |
| DELETE | `/v1/payment-atris/:id` | `routing.write` | Delete an unused ATRI |
| POST | `/v1/payment-atris/:id/default` | `routing.write` | Make an ATRI the default of its method |
| PUT | `/v1/payment-atris/:id/members` | `routing.write` | Replace the members of an ATRI |

#### Filters

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/filters` | `routing.read` | List the account filters and rules |
| PATCH | `/v1/filters/:key` | `routing.write` | Update an account filter |
| GET | `/v1/rejections` | `operations.read` | Read the rejections log |

#### BIN intelligence

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/bin-catalog` | `routing.read` | Read the account card catalogue |
| GET | `/v1/bin-catalog/jobs` | `routing.read` | List BIN catalogue jobs |
| GET | `/v1/bin-catalog/jobs/:id` | `routing.read` | Get a BIN catalogue job |
| POST | `/v1/bin-catalog/jobs/:id/cancel` | `routing.write` | Cancel a BIN catalogue job |
| GET | `/v1/bin-catalog/jobs/capabilities` | `routing.read` | BIN catalogue job capability |
| POST | `/v1/bin-catalog/sync` | `routing.write` | Sync the account card catalogue |
| GET | `/v1/bin-generation-jobs/:id` | `routing.write` | Read a BIN generation job |
| POST | `/v1/bin-generation-jobs/:id/apply` | `routing.write` | Apply the proposals of a BIN generation job |
| POST | `/v1/bin-generation-jobs/:id/cancel` | `routing.write` | Cancel a BIN generation job |
| GET | `/v1/bin-generation-jobs/:id/result` | `routing.write` | Read the proposals of a BIN generation job |
| GET | `/v1/bin-generation/capabilities` | `routing.read` | BIN generation availability |
| GET | `/v1/bin-info` | `reports.read` | BIN Lists |
| GET | `/v1/bin-issuers` | `routing.read` | Search issuer banks |
| GET | `/v1/bin-map` | `reports.read` | List mapping rules per target |
| GET | `/v1/bin-profiles` | `routing.read` | List BIN profiles |
| POST | `/v1/bin-profiles` | `routing.write` | Create a BIN profile |
| GET | `/v1/bin-profiles/:id` | `routing.read` | Get one BIN profile |
| PUT | `/v1/bin-profiles/:id` | `routing.write` | Update a BIN profile |
| DELETE | `/v1/bin-profiles/:id` | `routing.write` | Delete a BIN profile |
| GET | `/v1/bin-profiles/:id/analytics` | `routing.read` | BIN profile analytics |
| GET | `/v1/bin-profiles/:id/decisions` | `routing.read` | BIN profile decision log |
| PUT | `/v1/bin-profiles/:id/default` | `routing.write` | Make a BIN profile the default of its kind |
| POST | `/v1/bin-profiles/:id/generate` | `routing.write` | Generate rules (retired) |
| GET | `/v1/bin-profiles/:id/generation-jobs` | `routing.write` | List the generation jobs of a profile |
| POST | `/v1/bin-profiles/:id/generation-jobs` | `routing.write` | Start a BIN rule generation (preview job) |
| GET | `/v1/bin-profiles/:id/rules` | `routing.read` | List the rules of a BIN profile |
| POST | `/v1/bin-profiles/:id/rules` | `routing.write` | Create a rule |
| PUT | `/v1/bin-profiles/:id/rules/:rid` | `routing.write` | Update a rule |
| DELETE | `/v1/bin-profiles/:id/rules/:rid` | `routing.write` | Delete a rule |
| POST | `/v1/bin-profiles/:id/rules/:rid/duplicate` | `routing.write` | Duplicate a rule |
| POST | `/v1/bin-profiles/:id/rules/bulk` | `routing.write` | Bulk enable, disable or delete rules |
| GET | `/v1/bin-profiles/:id/rules/export.csv` | `routing.read` | Export the rules of a profile (CSV) |
| POST | `/v1/bin-profiles/:id/rules/import` | `routing.write` | Import rules from CSV: commit |
| GET | `/v1/bin-profiles/:id/rules/import/outcomes/:requestId` | `routing.read` | Read a saved BIN import result |
| POST | `/v1/bin-profiles/:id/rules/import/preview` | `routing.read` | Import rules from CSV: preview |
| GET | `/v1/bin-profiles/:id/rules/import/previews/:token` | `routing.read` | Read a BIN import preview page |
| PUT | `/v1/bin-profiles/:id/rules/order` | `routing.write` | Reorder the rules of a profile |
| GET | `/v1/bin-profiles/csv-template` | `routing.read` | CSV template for a rules import |
| GET | `/v1/bin-profiles/defaults` | `routing.read` | BIN profile criteria defaults |
| GET | `/v1/bin-profiles/export.csv` | `routing.read` | Export every profile of a kind (CSV) |
| GET | `/v1/bin-profiles/import-capabilities` | `routing.read` | BIN import capability |
| GET | `/v1/bin-scrub-enabled` | `routing.read` | Read the BIN scrubbing master switch |
| PUT | `/v1/bin-scrub-enabled` | `routing.write` | Toggle BIN scrubbing globally |
| GET | `/v1/bin-scrub-hits` | `routing.read` | List legacy BIN scrub hits |
| POST | `/v1/bin-scrub-rules/import` | `routing.write` | Import legacy scrub CSV into a scrubbing profile |
| GET | `/v1/scrub-bins` | `customers.read` | Read the BIN scrub list synced by the external rebill tool |
| PUT | `/v1/scrub-bins` | `customers.write` | Replace the BIN scrub list synced by the external rebill tool |

#### MID scrubbing

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/bin-scrub` | `routing.read` | List MIDs auto-disabled by MID scrubbing |
| POST | `/v1/bin-scrub/run` | `routing.write` | Run a MID scrubbing pass now |

### Commerce

#### Stores

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/checkouts` | `checkouts.read` | List the stores of the account |
| POST | `/v1/checkouts` | `checkouts.write` | Create a store |
| GET | `/v1/checkouts/:shopId` | `checkouts.read` | Read one store |
| PUT | `/v1/checkouts/:shopId` | `checkouts.write` | Update a store |
| DELETE | `/v1/checkouts/:shopId` | `checkouts.write` | Archive a store |
| POST | `/v1/checkouts/:shopId/assets` | `checkouts.write` | Upload a storefront asset |
| POST | `/v1/checkouts/:shopId/checkout` | `checkouts.write` | Assign a checkout or published flow to a store |
| POST | `/v1/checkouts/:shopId/duplicate` | `checkouts.write` | Duplicate a store |
| PUT | `/v1/checkouts/:shopId/medusa/connection` | `checkouts.write` | Save Medusa connection |
| POST | `/v1/checkouts/:shopId/medusa/installations` | `checkouts.write` | Create Medusa installation session |
| GET | `/v1/checkouts/:shopId/medusa/installations/latest` | `checkouts.read` | Read latest Medusa installation status |
| POST | `/v1/checkouts/:shopId/medusa/orders/retry` | `checkouts.write` | Retry a failed Medusa order export |
| POST | `/v1/checkouts/:shopId/medusa/ping` | `checkouts.write` | Test Medusa readiness |
| GET | `/v1/checkouts/:shopId/onboarding` | `checkouts.read` | Read the setup-wizard state of a store |
| PUT | `/v1/checkouts/:shopId/onboarding` | `checkouts.write` | Move the setup-wizard cursor |
| DELETE | `/v1/checkouts/:shopId/onboarding` | `checkouts.write` | Clear the setup-wizard cursor |
| GET | `/v1/checkouts/:shopId/overview` | `checkouts.read` | Read the store setup checklist |
| GET | `/v1/checkouts/:shopId/payment-methods` | `checkouts.read` | Read a store's payment methods (card, wallet, wire sources) |
| PUT | `/v1/checkouts/:shopId/payment-methods` | `checkouts.write` | Set a store's payment methods (card, wallet, wire sources) |
| GET | `/v1/checkouts/:shopId/routing` | `checkouts.read` | Read a store's effective payment routing (checkout side: ATRI, wallets, 3DS) |
| PUT | `/v1/checkouts/:shopId/routing` | `checkouts.write` | Set a store's payment routing |
| GET | `/v1/checkouts/:shopId/routing/details` | `checkouts.read` | Read a store's full payment-routing record (key, checkout, flow, default MID) |
| GET | `/v1/checkouts/:shopId/secrets` | `checkouts.write` | Read a store's Shopify secrets (in clear) |
| POST | `/v1/checkouts/:shopId/shopify-oauth/start` | `checkouts.write` | Start the Shopify connection |
| POST | `/v1/checkouts/:shopId/shopify/ping` | `checkouts.write` | Prove the stored Shopify token reaches the right store |
| GET | `/v1/checkouts/:shopId/storefront` | `checkouts.read` | Read store site content and company identity |
| PUT | `/v1/checkouts/:shopId/storefront` | `checkouts.write` | Save store site content and company identity |
| POST | `/v1/checkouts/:shopId/storefront/generate` | `checkouts.write` | Generate homepage copy with AI |
| POST | `/v1/checkouts/:shopId/theme-check` | `checkouts.write` | Check that the store theme is wired to the checkout |
| GET | `/v1/checkouts/health` | `checkouts.read` | Check the Ecommerce integration health |
| GET | `/v1/checkouts/providers` | `checkouts.read` | List the legacy payment providers usable for a new store |
| GET | `/v1/checkouts/shopify/theme-files` | `checkouts.read` | The two theme files to install in Shopify |
| GET | `/v1/home-ai/jobs` | `reports.read` | List homepage generations |
| POST | `/v1/home-ai/jobs` | `reports.write` | Start a homepage copy generation |
| GET | `/v1/home-ai/jobs/:id` | `reports.read` | Read a homepage proposal |
| POST | `/v1/home-ai/jobs/:id/apply` | `reports.write` | Apply a homepage proposal |
| POST | `/v1/home-ai/jobs/:id/cancel` | `reports.write` | Cancel a homepage generation |
| GET | `/v1/home-ai/jobs/capabilities` | `reports.read` | Read homepage generation availability |

#### Products

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/checkouts/:shopId/medusa/import` | `checkouts.write` | Queue Medusa catalog import |
| GET | `/v1/checkouts/:shopId/medusa/import/status` | `checkouts.read` | Read Medusa import status |
| GET | `/v1/checkouts/:shopId/products` | `checkouts.read` | List a store's products (unpaged) |
| POST | `/v1/checkouts/:shopId/products` | `checkouts.write` | Create a complete product atomically |
| GET | `/v1/checkouts/:shopId/products-stats` | `checkouts.read` | Read per-product sales stats of a store |
| GET | `/v1/checkouts/:shopId/products/:pid` | `checkouts.read` | Read a product in full |
| PUT | `/v1/checkouts/:shopId/products/:pid` | `checkouts.write` | Update product core fields |
| DELETE | `/v1/checkouts/:shopId/products/:pid` | `checkouts.write` | Delete a product |
| PUT | `/v1/checkouts/:shopId/products/:pid/availability` | `checkouts.write` | Set which stores list the product |
| PUT | `/v1/checkouts/:shopId/products/:pid/bundle` | `checkouts.write` | Replace bundle components |
| POST | `/v1/checkouts/:shopId/products/:pid/media` | `checkouts.write` | Add media from a URL |
| PUT | `/v1/checkouts/:shopId/products/:pid/media/:id` | `checkouts.write` | Update a media item |
| DELETE | `/v1/checkouts/:shopId/products/:pid/media/:id` | `checkouts.write` | Delete a media item |
| POST | `/v1/checkouts/:shopId/products/:pid/media/:id/move` | `checkouts.write` | Move a media item in the product gallery |
| POST | `/v1/checkouts/:shopId/products/:pid/media/upload` | `checkouts.write` | Upload media bytes |
| PUT | `/v1/checkouts/:shopId/products/:pid/options` | `checkouts.write` | Replace product options and rebuild variants |
| PUT | `/v1/checkouts/:shopId/products/:pid/page-config` | `checkouts.write` | Replace the product page configuration |
| POST | `/v1/checkouts/:shopId/products/:pid/reviews` | `checkouts.write` | Add a product review |
| PUT | `/v1/checkouts/:shopId/products/:pid/reviews/:id` | `checkouts.write` | Update a review |
| DELETE | `/v1/checkouts/:shopId/products/:pid/reviews/:id` | `checkouts.write` | Delete a review |
| PUT | `/v1/checkouts/:shopId/products/:pid/sections` | `checkouts.write` | Replace the product page sections |
| PUT | `/v1/checkouts/:shopId/products/:pid/specs` | `checkouts.write` | Replace product specifications |
| PUT | `/v1/checkouts/:shopId/products/:pid/tiers` | `checkouts.write` | Replace quantity price tiers |
| DELETE | `/v1/checkouts/:shopId/products/:pid/translations/:id` | `checkouts.write` | Delete a product translation |
| PUT | `/v1/checkouts/:shopId/products/:pid/variants` | `checkouts.write` | Update variant prices, SKUs and stock |
| POST | `/v1/checkouts/:shopId/products/:pid/variants/rebuild` | `checkouts.write` | Rebuild the variant matrix |
| POST | `/v1/checkouts/:shopId/products/attach` | `checkouts.write` | Add existing products to a store |
| POST | `/v1/checkouts/:shopId/products/export-pdf-v2` | `checkouts.write` | Stream the product catalogue for a PDF (one store) |
| POST | `/v1/checkouts/:shopId/products/page-v1/export` | `checkouts.write` | Export the product catalogue as CSV (one store) |
| POST | `/v1/checkouts/:shopId/products/page-v1/query` | `checkouts.read` | Query one store's product catalogue (paged, filtered, sorted) |
| POST | `/v1/checkouts/:shopId/shopify/import` | `checkouts.write` | Import the Shopify catalogue |
| GET | `/v1/checkouts/medusa/catalog-jobs` | `checkouts.read` | List Medusa catalogue imports |
| POST | `/v1/checkouts/medusa/catalog-jobs` | `checkouts.write` | Queue a Medusa catalogue import |
| GET | `/v1/checkouts/medusa/catalog-jobs/:id` | `checkouts.read` | Get a Medusa catalogue import |
| POST | `/v1/checkouts/medusa/catalog-jobs/:id/cancel` | `checkouts.write` | Cancel a Medusa catalogue import |
| GET | `/v1/checkouts/medusa/catalog-jobs/:id/errors` | `checkouts.read` | List the errors of a Medusa import |
| GET | `/v1/checkouts/medusa/catalog-jobs/:id/targets` | `checkouts.read` | List the stores of a Medusa import |
| GET | `/v1/checkouts/medusa/catalog-jobs/capability` | `checkouts.read` | Medusa catalogue job capability |
| POST | `/v1/checkouts/medusa/sync-all` | `checkouts.write` | Queue visible Medusa stores |
| GET | `/v1/checkouts/products` | `checkouts.read` | List every product across the account's stores (unpaged) |
| POST | `/v1/checkouts/products/export-pdf-v2` | `checkouts.write` | Stream the product catalogue for a PDF |
| POST | `/v1/checkouts/products/page-v1/export` | `checkouts.write` | Export the product catalogue as CSV |
| POST | `/v1/checkouts/products/page-v1/query` | `checkouts.read` | Query the product catalogue across stores (paged, filtered, sorted) |
| GET | `/v1/checkouts/products/paging-capabilities` | `checkouts.read` | Read catalogue paging availability |
| GET | `/v1/checkouts/shopify/job-capabilities` | `checkouts.read` | Read background Shopify import availability |
| GET | `/v1/checkouts/shopify/jobs` | `checkouts.read` | List Shopify catalogue import progress |
| POST | `/v1/checkouts/shopify/jobs` | `checkouts.write` | Queue a Shopify catalogue import |
| GET | `/v1/checkouts/shopify/jobs/:jobId` | `checkouts.read` | Read Shopify catalogue import details |
| POST | `/v1/checkouts/shopify/jobs/:jobId/cancel` | `checkouts.write` | Cancel a Shopify catalogue import |
| POST | `/v1/checkouts/shopify/sync-all` | `checkouts.write` | Resync every connected Shopify catalogue |
| POST | `/v1/v5/catalog/products` | `checkouts.write` | Create an account catalogue product |
| GET | `/v1/v5/catalog/products/:id` | `checkouts.read` | Read an account catalogue product |
| PATCH | `/v1/v5/catalog/products/:id` | `checkouts.write` | Update an account catalogue product |

#### Themes

| method | address | scope | title |
|---|---|---|---|
| PUT | `/v1/checkouts/:shopId/theme` | `checkouts.write` | Apply a theme to a store |
| GET | `/v1/checkouts/themes` | `checkouts.read` | List storefront themes, editor metadata and optional usage |
| GET | `/v1/checkouts/themes/custom` | `checkouts.read` | The account's made themes |
| POST | `/v1/checkouts/themes/custom` | `checkouts.write` | Create a theme |
| GET | `/v1/checkouts/themes/custom/:id` | `checkouts.read` | Open a theme in the builder |
| PATCH | `/v1/checkouts/themes/custom/:id` | `checkouts.write` | Save a theme, or its work in progress |
| DELETE | `/v1/checkouts/themes/custom/:id` | `checkouts.write` | Delete a theme |

#### Checkouts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/checkouts/ab-tests` | `checkouts.read` | Read legacy checkout split history |
| POST | `/v1/checkouts/ab-tests` | `checkouts.write` | Create a checkout A/B test (retired: answers 410) |
| PATCH | `/v1/checkouts/ab-tests/:id` | `checkouts.write` | Edit a checkout A/B test (retired: answers 410) |
| GET | `/v1/checkouts/profiles` | `checkouts.read` | List the checkouts (templates) |
| POST | `/v1/checkouts/profiles` | `checkouts.write` | Create a checkout |
| GET | `/v1/checkouts/profiles/3ds-options` | `checkouts.read` | List configured 3DS integrations for a checkout |
| PATCH | `/v1/checkouts/profiles/:id` | `checkouts.write` | Edit a checkout |
| DELETE | `/v1/checkouts/profiles/:id` | `checkouts.write` | Archive a checkout template |
| GET | `/v1/checkouts/profiles/:id/document` | `checkouts.read` | Open a checkout in the visual editor |
| PUT | `/v1/checkouts/profiles/:id/document/draft` | `checkouts.write` | Save the editor's draft |
| DELETE | `/v1/checkouts/profiles/:id/document/draft` | `checkouts.write` | Discard the draft |
| POST | `/v1/checkouts/profiles/:id/document/links` | `checkouts.write` | A signed storefront link for the editor canvas or the Preview |
| POST | `/v1/checkouts/profiles/:id/document/publish` | `checkouts.write` | Publish the draft |
| GET | `/v1/checkouts/profiles/:id/document/stores` | `checkouts.read` | List stores available for checkout preview |
| GET | `/v1/checkouts/profiles/:id/document/versions` | `checkouts.read` | The published versions of a checkout |
| POST | `/v1/checkouts/profiles/:id/document/versions/:version/restore` | `checkouts.write` | Restore a version into the draft |
| GET | `/v1/checkouts/profiles/:id/sites` | `checkouts.read` | List the stores using a checkout |
| GET | `/v1/checkouts/sessions` | `checkouts.read` | List recent checkout sessions |
| GET | `/v1/checkouts/sessions/:kind/:id` | `checkouts.read` | Read one checkout session timeline |
| GET | `/v1/editor/catalog` | `checkouts.read` | Read the checkout editor catalogue |
| GET | `/v1/editor/entities/discount-codes` | `checkouts.read` | Pick discount codes for the editor |
| GET | `/v1/editor/entities/products` | `checkouts.read` | Pick products for the editor |
| GET | `/v1/editor/entities/resolve` | `checkouts.read` | Resolve editor references |
| GET | `/v1/editor/entities/subscription-products` | `checkouts.read` | Pick subscription products for the editor |
| GET | `/v1/editor/fonts` | `checkouts.read` | List custom fonts |
| POST | `/v1/editor/fonts` | `checkouts.write` | Upload a custom font |
| DELETE | `/v1/editor/fonts/:id` | `checkouts.write` | Delete a custom font |
| GET | `/v1/editor/saved-blocks` | `checkouts.read` | List saved blocks |
| POST | `/v1/editor/saved-blocks` | `checkouts.write` | Save a block |
| PATCH | `/v1/editor/saved-blocks/:id` | `checkouts.write` | Update a saved block |
| DELETE | `/v1/editor/saved-blocks/:id` | `checkouts.write` | Delete a saved block |

#### Pages

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/v5/funnels` | `checkouts.read` | List funnel pages |
| POST | `/v1/v5/funnels` | `checkouts.write` | Create a funnel page |
| GET | `/v1/v5/funnels/:id` | `checkouts.read` | Read a funnel page |
| PATCH | `/v1/v5/funnels/:id` | `checkouts.write` | Rename a funnel page |
| DELETE | `/v1/v5/funnels/:id` | `checkouts.write` | Archive a funnel page |
| POST | `/v1/v5/funnels/:id/assets` | `checkouts.write` | Upload media for a funnel page |
| GET | `/v1/v5/funnels/:id/document` | `checkouts.read` | Read a funnel page document |
| PUT | `/v1/v5/funnels/:id/document/draft` | `checkouts.write` | Save a funnel page draft |
| DELETE | `/v1/v5/funnels/:id/document/draft` | `checkouts.write` | Discard a funnel page draft |
| POST | `/v1/v5/funnels/:id/document/links` | `checkouts.write` | Issue a signed page preview link |
| POST | `/v1/v5/funnels/:id/document/publish` | `checkouts.write` | Publish a funnel page |
| GET | `/v1/v5/funnels/:id/document/stores` | `checkouts.read` | List stores for a page preview |
| GET | `/v1/v5/funnels/:id/document/versions` | `checkouts.read` | List funnel page versions |
| POST | `/v1/v5/funnels/:id/document/versions/:version/restore` | `checkouts.write` | Restore a funnel page version into the draft |
| POST | `/v1/v5/funnels/:id/duplicate` | `checkouts.write` | Duplicate a funnel page |

#### Flows

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/v5/flows` | `checkouts.read` | List flows |
| POST | `/v1/v5/flows` | `checkouts.write` | Create a flow |
| GET | `/v1/v5/flows/:id` | `checkouts.read` | Read a flow |
| PATCH | `/v1/v5/flows/:id` | `checkouts.write` | Rename a flow |
| DELETE | `/v1/v5/flows/:id` | `checkouts.write` | Archive a flow |
| POST | `/v1/v5/flows/:id/assign` | `checkouts.write` | Assign a flow to checkouts |
| PUT | `/v1/v5/flows/:id/draft` | `checkouts.write` | Save a flow draft |
| POST | `/v1/v5/flows/:id/duplicate` | `checkouts.write` | Duplicate a flow |
| POST | `/v1/v5/flows/:id/link-assets` | `checkouts.write` | Upload an image for a flow link |
| GET | `/v1/v5/flows/:id/link-options` | `checkouts.read` | Read saved-link options for a flow |
| POST | `/v1/v5/flows/:id/preview` | `checkouts.read` | Issue a flow walk-through preview |
| POST | `/v1/v5/flows/:id/publish` | `checkouts.write` | Publish a flow |
| GET | `/v1/v5/flows/:id/short-links` | `checkouts.read` | List the saved links of a flow |
| POST | `/v1/v5/flows/:id/short-links` | `checkouts.write` | Create or edit a saved link of a flow |
| PATCH | `/v1/v5/flows/:id/short-links/:linkId` | `checkouts.write` | Change the lifecycle of a flow link |
| GET | `/v1/v5/flows/:id/versions` | `checkouts.read` | List flow versions |
| POST | `/v1/v5/flows/:id/versions/:version/restore` | `checkouts.write` | Restore a flow version into the draft |
| GET | `/v1/v5/flows/options` | `checkouts.read` | Flow condition choices |
| POST | `/v1/v5/flows/validate` | `checkouts.write` | Validate a flow graph |

#### Standalone and embedded checkouts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/checkouts/standalone` | `checkouts.read` | List standalone checkouts |
| POST | `/v1/checkouts/standalone` | `checkouts.write` | Create a standalone checkout |
| GET | `/v1/checkouts/standalone/:id` | `checkouts.read` | Read a standalone checkout |
| PATCH | `/v1/checkouts/standalone/:id` | `checkouts.write` | Update a standalone checkout |
| DELETE | `/v1/checkouts/standalone/:id` | `checkouts.write` | Archive a standalone checkout |
| POST | `/v1/checkouts/standalone/:id/active` | `checkouts.write` | Enable or disable a standalone checkout |
| GET | `/v1/checkouts/standalone/:id/document` | `checkouts.read` | Read the checkout document |
| PUT | `/v1/checkouts/standalone/:id/document/draft` | `checkouts.write` | Save the document draft |
| DELETE | `/v1/checkouts/standalone/:id/document/draft` | `checkouts.write` | Discard the document draft |
| POST | `/v1/checkouts/standalone/:id/document/links` | `checkouts.write` | Create an editor or preview link |
| POST | `/v1/checkouts/standalone/:id/document/publish` | `checkouts.write` | Publish the document |
| GET | `/v1/checkouts/standalone/:id/document/stores` | `checkouts.read` | List preview stores |
| GET | `/v1/checkouts/standalone/:id/document/versions` | `checkouts.read` | List published document versions |
| POST | `/v1/checkouts/standalone/:id/document/versions/:version/restore` | `checkouts.write` | Restore a document version |
| POST | `/v1/checkouts/standalone/:id/duplicate` | `checkouts.write` | Duplicate a standalone checkout |
| POST | `/v1/checkouts/standalone/:id/link-assets` | `checkouts.write` | Upload a link image |
| GET | `/v1/checkouts/standalone/:id/link-options` | `checkouts.read` | Read link options |
| POST | `/v1/checkouts/standalone/:id/publish` | `checkouts.write` | Publish settings and document |
| POST | `/v1/checkouts/standalone/:id/rotate-secret` | `checkouts.write` | Rotate the link signing secret |
| GET | `/v1/checkouts/standalone/:id/short-links` | `checkouts.read` | List short links |
| POST | `/v1/checkouts/standalone/:id/short-links` | `checkouts.write` | Create or edit a short link |
| PATCH | `/v1/checkouts/standalone/:id/short-links/:linkId` | `checkouts.write` | Change a short link state |
| POST | `/v1/checkouts/standalone/:id/url` | `checkouts.write` | Build a signed long link |
| GET | `/v1/checkouts/standalone/options` | `checkouts.read` | Read standalone checkout options |

#### Affiliates

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/affiliates` | `affiliates.read` | List affiliates |
| POST | `/v1/affiliates` | `affiliates.write` | Create an affiliate |
| GET | `/v1/affiliates/:id` | `affiliates.read` | Get one affiliate |
| PATCH | `/v1/affiliates/:id` | `affiliates.write` | Update an affiliate |
| DELETE | `/v1/affiliates/:id` | `affiliates.write` | Archive an affiliate |
| GET | `/v1/affiliates/:id/cuts` | `affiliates.read` | List affiliate cut entries |
| POST | `/v1/affiliates/:id/invite` | `affiliates.write` | Resend an affiliate invitation |
| POST | `/v1/affiliates/:id/reset-mfa` | `affiliates.write` | Reset affiliate two-step verification |
| POST | `/v1/affiliates/assets/:kind/:id/links` | `affiliates.write` | Generate published asset distribution links |
| GET | `/v1/affiliates/assets/:kind/:id/sharing` | `affiliates.read` | Read asset sharing |
| PATCH | `/v1/affiliates/assets/:kind/:id/sharing` | `affiliates.write` | Update asset sharing |
| GET | `/v1/affiliates/checkouts` | `affiliates.read` | List checkout choices for affiliate access |
| PATCH | `/v1/affiliates/settings` | `affiliates.write` | Set the affiliate account currency |
| GET | `/v1/v5/affiliates/store-checkouts/reviews` | `affiliates.read` | List store checkouts and their review status |

#### Domains

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/checkouts/:shopId/domain/check` | `checkouts.write` | Diagnose the store domain connection |
| POST | `/v1/checkouts/:shopId/domain/fix-cloudflare` | `checkouts.write` | Queue domain fix-cloudflare |
| POST | `/v1/checkouts/:shopId/domain/move-service` | `checkouts.write` | Queue a store move between services |
| POST | `/v1/checkouts/:shopId/domain/remove` | `checkouts.write` | Queue domain remove |
| POST | `/v1/checkouts/:shopId/domain/setup-cloudflare` | `checkouts.write` | Configure the store domain in Cloudflare |
| POST | `/v1/checkouts/:shopId/domain/verify` | `checkouts.write` | Queue domain verify |
| GET | `/v1/checkouts/domain/job-capabilities` | `checkouts.read` | Read domain job availability |
| GET | `/v1/checkouts/domain/jobs` | `checkouts.read` | List domain operations of a store |
| POST | `/v1/checkouts/domain/jobs` | `checkouts.write` | Start a domain operation |
| GET | `/v1/checkouts/domain/jobs/:jobId` | `checkouts.read` | Read a domain operation |
| POST | `/v1/checkouts/domain/jobs/:jobId/cancel` | `checkouts.write` | Cancel a domain operation |
| POST | `/v1/checkouts/domain/jobs/:jobId/reconcile` | `checkouts.write` | Reconcile an uncertain domain operation |
| POST | `/v1/checkouts/domain/jobs/:jobId/resume` | `checkouts.write` | Resume a paused service move |
| GET | `/v1/checkouts/domain/preview` | `checkouts.read` | Preview the DNS record a domain needs |
| POST | `/v1/checkouts/domain/reconcile-legacy` | `checkouts.write` | Reconcile a legacy domain write |

#### Pixels and tracking

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/checkouts/:shopId/google-ads` | `checkouts.read` | List a store's Google Ads tags |
| POST | `/v1/checkouts/:shopId/google-ads` | `checkouts.write` | Add a Google Ads tag to a store |
| PUT | `/v1/checkouts/:shopId/google-ads/:id` | `checkouts.write` | Edit a Google Ads tag |
| DELETE | `/v1/checkouts/:shopId/google-ads/:id` | `checkouts.write` | Delete a Google Ads tag |
| GET | `/v1/checkouts/:shopId/pixels` | `tracking.read` | List a store's pixels |
| POST | `/v1/checkouts/:shopId/pixels` | `tracking.write` | Add a pixel to a store |
| PUT | `/v1/checkouts/:shopId/pixels/:id` | `tracking.write` | Update a pixel |
| DELETE | `/v1/checkouts/:shopId/pixels/:id` | `tracking.write` | Delete a pixel |
| GET | `/v1/checkouts/:shopId/pixels/:id/secrets` | `checkouts.write` | Read a pixel's CAPI token (in clear) |
| GET | `/v1/checkouts/pixels` | `tracking.read` | List every pixel of the caller's stores |
| POST | `/v1/checkouts/pixels` | `tracking.write` | Add an account pixel |
| GET | `/v1/checkouts/pixels-audit` | `tracking.read` | Audit pixels configuration vs firing |
| PUT | `/v1/checkouts/pixels/:id` | `tracking.write` | Update an account pixel |
| DELETE | `/v1/checkouts/pixels/:id` | `tracking.write` | Delete an account pixel |
| GET | `/v1/checkouts/pixels/:id/secrets` | `tracking.write` | Read an account pixel token (in clear) |

#### Discounts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/discounts` | `checkouts.read` | List discount codes |
| POST | `/v1/discounts` | `checkouts.write` | Add a discount code |
| GET | `/v1/discounts/:id` | `checkouts.read` | One discount code |
| PATCH | `/v1/discounts/:id` | `checkouts.write` | Edit a discount code |
| DELETE | `/v1/discounts/:id` | `checkouts.write` | Delete (or archive) a discount code |
| GET | `/v1/discounts/targets` | `checkouts.read` | What a discount code can target |

#### Cart recovery

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/recovery/bindings` | `recovery.read` | List what each store picked |
| PUT | `/v1/recovery/bindings` | `recovery.write` | Set what one store picks |
| GET | `/v1/recovery/carts` | `recovery.read` | List recovery carts |
| POST | `/v1/recovery/carts` | `recovery.write` | Hand an abandoned cart to the recovery tool |
| GET | `/v1/recovery/carts/:cart_token` | `recovery.read` | Read a cart's recovery state and sends (integration view) |
| GET | `/v1/recovery/carts/:cart_token/details` | `recovery.read` | Read a recovery cart's full record (policy, links, raw send payloads) |
| POST | `/v1/recovery/carts/:cart_token/recovered` | `recovery.write` | Close a cart: the order was paid |
| GET | `/v1/recovery/health` | `recovery.read` | Get cart-recovery health |
| GET | `/v1/recovery/profiles` | `recovery.read` | List recovery sending settings |
| POST | `/v1/recovery/profiles` | `recovery.write` | Create recovery sending settings |
| PUT | `/v1/recovery/profiles/:id` | `recovery.write` | Update recovery sending settings |
| DELETE | `/v1/recovery/profiles/:id` | `recovery.write` | Delete recovery sending settings |
| POST | `/v1/recovery/profiles/:id/default` | `recovery.write` | Make sending settings the channel default |
| GET | `/v1/recovery/sends` | `recovery.read` | List recovery sends |
| GET | `/v1/recovery/sends/:id` | `recovery.read` | Get one recovery send |
| POST | `/v1/recovery/sends/:id/notify` | `recovery.write` | Re-send the checkout callback for a send |
| GET | `/v1/recovery/templates` | `recovery.read` | List recovery templates |
| POST | `/v1/recovery/templates` | `recovery.write` | Create a recovery template |
| PUT | `/v1/recovery/templates/:id` | `recovery.write` | Update a recovery template |
| DELETE | `/v1/recovery/templates/:id` | `recovery.write` | Delete a recovery template |
| POST | `/v1/recovery/templates/:id/default` | `recovery.write` | Make a recovery template the default |
| POST | `/v1/recovery/templates/preview` | `recovery.read` | Preview a recovery template |

#### Senders

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/messaging/alerts` | `integrations.read` | Get messaging provider alerts |
| GET | `/v1/messaging/analytics` | `integrations.read` | Get per-day messaging analytics for a channel |
| GET | `/v1/messaging/email-providers` | `integrations.read` | List email (SMTP) providers |
| POST | `/v1/messaging/email-providers` | `integrations.write` | Create an email (SMTP) provider |
| PUT | `/v1/messaging/email-providers/:id` | `integrations.write` | Update an email provider |
| DELETE | `/v1/messaging/email-providers/:id` | `integrations.write` | Delete an email provider |
| GET | `/v1/messaging/email-providers/:id/credentials` | `integrations.write` | Read an email provider's stored secrets (in clear) |
| POST | `/v1/messaging/email-providers/:id/test` | `integrations.write` | Test an email provider (SMTP verify or send) |
| GET | `/v1/messaging/logs` | `integrations.read` | List messaging send logs for a channel |
| GET | `/v1/messaging/sms-providers` | `integrations.read` | List SMS providers |
| POST | `/v1/messaging/sms-providers` | `integrations.write` | Create an SMS provider |
| PUT | `/v1/messaging/sms-providers/:id` | `integrations.write` | Update an SMS provider |
| DELETE | `/v1/messaging/sms-providers/:id` | `integrations.write` | Delete an SMS provider |
| GET | `/v1/messaging/sms-providers/:id/credentials` | `integrations.write` | Read an SMS provider's stored API key (in clear) |
| POST | `/v1/messaging/sms-providers/:id/test` | `integrations.write` | Send a test SMS through a provider |
| GET | `/v1/sender-costs` | `integrations.read` | Read messaging costs for a range |
| GET | `/v1/sender-rates` | `integrations.read` | List sender rates |
| PUT | `/v1/sender-rates` | `integrations.write` | Replace sender rates |

#### Sender ATRIs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/sender-atris` | `integrations.read` | List sender ATRIs |
| POST | `/v1/sender-atris` | `integrations.write` | Create a sender ATRI |
| PATCH | `/v1/sender-atris/:id` | `integrations.write` | Update a sender ATRI |
| DELETE | `/v1/sender-atris/:id` | `integrations.write` | Delete a sender ATRI |
| POST | `/v1/sender-atris/:id/default` | `integrations.write` | Set the default sender ATRI |
| PUT | `/v1/sender-atris/:id/members` | `integrations.write` | Replace sender ATRI members |

### Headless checkout

#### Embedded (iframe) checkout

| method | address | scope | title |
|---|---|---|---|
| POST | `/v5/standalone/iframe-session` | `charges.write` | Create an embedded (iframe) checkout session |

#### Store sessions and entry

| method | address | scope | title |
|---|---|---|---|
| POST | `/v5/store/entry` | `charges.write` | Create or refresh store checkout entry |
| POST | `/v5/store/session` | `charges.write` | Read safe store entry bootstrap |

#### Checkout orders

| method | address | scope | title |
|---|---|---|---|
| POST | `/v5/checkout/order` | `charges.write` | Prepare a canonical checkout order |
| POST | `/v5/checkout/order/dispatch` | `charges.write` | Claim the single initial payment dispatch |
| POST | `/v5/checkout/order/recover` | `charges.write` | Recover the owned initial order without dispatch |
| POST | `/v5/checkout/order/reserve` | `charges.write` | Reserve the server-owned initial payment identity |
| POST | `/v5/checkout/order/verify` | `charges.write` | Verify a prepared checkout order |

#### Flow runtime

| method | address | scope | title |
|---|---|---|---|
| GET | `/v5/flow/:checkoutId` | `charges.write` | Read current pinned flow node |
| POST | `/v5/flow/:checkoutId/actions` | `charges.write` | Confirm an upsell cart or advance its flow |
| POST | `/v5/flow/:checkoutId/authentication/background` | `charges.write` | Observe an existing optional post-sell authentication |
| POST | `/v5/flow/:checkoutId/cart` | `charges.write` | Update the initial flow cart |
| POST | `/v5/flow/:checkoutId/events` | `charges.write` | Record verified page and offer activity |
| POST | `/v5/flow/:checkoutId/purchase-observed` | `charges.write` | Observe browser Purchase dispatch |
| POST | `/v5/flow/:checkoutId/quote` | `charges.write` | Quote published offer choices |

#### Standalone runtime

| method | address | scope | title |
|---|---|---|---|
| POST | `/v5/standalone/activity` | `charges.write` | Record bound checkout activity |
| POST | `/v5/standalone/completion` | `charges.write` | Read captured standalone completion |
| POST | `/v5/standalone/entry` | `charges.write` | Pin standalone entry and clean its URL |
| POST | `/v5/standalone/lead` | `charges.write` | Record checkout contact submission |
| POST | `/v5/standalone/session` | `charges.write` | Read pinned standalone render input |

#### Wallet and wire sessions

| method | address | scope | title |
|---|---|---|---|
| POST | `/v5/payment-methods` | `charges.write` | Read checkout payment methods (storefront) |
| POST | `/v5/standalone/wallet-status` | `charges.write` | Read bound standalone wallet outcome |
| POST | `/v5/wire/check` | `charges.write` | Check a bank wire (storefront) |
| POST | `/v5/wire/start` | `charges.write` | Start or resume a bank wire (storefront) |

### KontrolPay

#### Onboarding

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/kontrolpay` | `kontrolpay.read` | Read the KontrolPay overview |
| POST | `/v1/kontrolpay/applications` | `kontrolpay.write` | Add an application |
| GET | `/v1/kontrolpay/applications/:id` | `kontrolpay.read` | Read one application |
| GET | `/v1/kontrolpay/applications/:id/agreement` | `kontrolpay.read` | Read the agreement |
| GET | `/v1/kontrolpay/applications/:id/agreement/pdf` | `kontrolpay.read` | Download the agreement PDF |
| POST | `/v1/kontrolpay/applications/:id/agreement/sign` | `kontrolpay.write` | Sign the agreement |
| POST | `/v1/kontrolpay/applications/:id/documents` | `kontrolpay.write` | Upload a document |
| DELETE | `/v1/kontrolpay/applications/:id/documents/:documentId` | `kontrolpay.write` | Remove a document |
| POST | `/v1/kontrolpay/applications/:id/requests/:requestId/answer` | `kontrolpay.write` | Answer a request item |
| PUT | `/v1/kontrolpay/applications/:id/sensitive` | `kontrolpay.write` | Save sealed values |
| PUT | `/v1/kontrolpay/applications/:id/steps/:step` | `kontrolpay.write` | Save a form step |
| POST | `/v1/kontrolpay/applications/:id/submit` | `kontrolpay.write` | Submit the application |
| POST | `/v1/kontrolpay/applications/:id/withdraw` | `kontrolpay.write` | Withdraw the application |

#### Balance and payouts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/kontrolpay/balances` | `kontrolpay.read` | Read balances |
| GET | `/v1/kontrolpay/payouts` | `kontrolpay.read` | List payouts |
| GET | `/v1/kontrolpay/payouts/:payoutId` | `kontrolpay.read` | Read one payout |

#### Reserve

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/kontrolpay/reserve` | `kontrolpay.read` | Read the reserve |

#### Transactions

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/kontrolpay/transactions` | `kontrolpay.read` | List ledger transactions |

### Subscriptions

#### Schedules

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/jobs/:jobId` | `subscriptions.read` | Get a schedule billing job (Force bill / Sample) |
| POST | `/v1/subscription/jobs/:jobId/cancel` | `subscriptions.write` | Cancel a schedule billing job |
| POST | `/v1/subscription/jobs/:jobId/pause` | `subscriptions.write` | Pause a schedule billing job |
| POST | `/v1/subscription/jobs/:jobId/resume` | `subscriptions.write` | Resume a schedule billing job |
| GET | `/v1/subscription/schedules` | `subscriptions.read` | List schedules |
| GET | `/v1/subscription/schedules/:id` | `subscriptions.read` | Get a schedule |
| DELETE | `/v1/subscription/schedules/:id` | `subscriptions.write` | Delete a schedule |
| GET | `/v1/subscription/schedules/:id/analysis` | `subscriptions.read` | Analysis of one schedule |
| POST | `/v1/subscription/schedules/:id/cancel` | `subscriptions.write` | Cancel a schedule |
| POST | `/v1/subscription/schedules/:id/cancel-processing` | `subscriptions.write` | Cancel the schedule and its running job |
| GET | `/v1/subscription/schedules/:id/entries` | `subscriptions.read` | List the charges of a schedule |
| GET | `/v1/subscription/schedules/:id/entries/:entryId` | `subscriptions.read` | Get one charge of a schedule |
| POST | `/v1/subscription/schedules/:id/entries/bulk` | `subscriptions.write` | Bulk action on the charges of a schedule |
| GET | `/v1/subscription/schedules/:id/entries/ids` | `subscriptions.read` | Ids of a day's charge list |
| GET | `/v1/subscription/schedules/:id/history` | `subscriptions.read` | Schedule history |
| GET | `/v1/subscription/schedules/:id/jobs` | `subscriptions.read` | List the jobs of a schedule |
| POST | `/v1/subscription/schedules/:id/jobs` | `subscriptions.write` | Start a manual job (Force bill / Sample) |
| POST | `/v1/subscription/schedules/:id/override` | `subscriptions.write` | Override the day or the amount of a schedule |
| POST | `/v1/subscription/schedules/:id/pause` | `subscriptions.write` | Pause a schedule |
| POST | `/v1/subscription/schedules/:id/rerun-post-dispatch` | `subscriptions.write` | Re-run post-dispatch (legacy retry child) |
| POST | `/v1/subscription/schedules/:id/reschedule-now` | `subscriptions.write` | Re-spread overdue charges over the rest of today |
| POST | `/v1/subscription/schedules/:id/reschedule-today` | `subscriptions.write` | Reschedule undispatched charges to today |
| POST | `/v1/subscription/schedules/:id/reset-processing` | `subscriptions.write` | Revert in-flight charges |
| POST | `/v1/subscription/schedules/:id/reset-test` | `subscriptions.write` | Reset a test schedule |
| POST | `/v1/subscription/schedules/:id/resume` | `subscriptions.write` | Resume a schedule |
| POST | `/v1/subscription/schedules/:id/retry-reason` | `subscriptions.write` | Retry the declines of one reason |
| POST | `/v1/subscription/schedules/:id/route` | `subscriptions.write` | Set a day's route override |
| GET | `/v1/subscription/schedules/:id/transactions` | `subscriptions.read` | Schedule transactions and exact analytics drill-down |
| POST | `/v1/subscription/schedules/:id/uncancel` | `subscriptions.write` | Uncancel a schedule |
| POST | `/v1/subscription/schedules/analysis` | `subscriptions.write` | Analyse several schedules (background report) |
| GET | `/v1/subscription/schedules/attention` | `subscriptions.read` | Schedules needing attention |
| POST | `/v1/subscription/schedules/bulk` | `subscriptions.write` | Bulk Pause / Resume / Cancel / Change route of schedule days |
| GET | `/v1/subscription/schedules/bulk-jobs` | `subscriptions.read` | List schedule bulk jobs |
| POST | `/v1/subscription/schedules/bulk-jobs` | `subscriptions.write` | Create a schedule bulk job |
| GET | `/v1/subscription/schedules/bulk-jobs/:id` | `subscriptions.read` | Read a schedule bulk job |
| POST | `/v1/subscription/schedules/bulk-jobs/:id/cancel` | `subscriptions.write` | Cancel a schedule bulk job |
| GET | `/v1/subscription/schedules/bulk-jobs/:id/results` | `subscriptions.read` | Read schedule bulk job results |
| POST | `/v1/subscription/schedules/bulk-jobs/:id/resume` | `subscriptions.write` | Resume a held schedule bulk job |
| GET | `/v1/subscription/schedules/bulk-jobs/capability` | `subscriptions.read` | Schedule bulk jobs: capability |
| GET | `/v1/subscription/schedules/calendar` | `subscriptions.read` | Calendar of schedules |
| GET | `/v1/subscription/schedules/ids` | `subscriptions.read` | List the ids of the matching schedules |

#### Monitoring

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/alerts` | `subscriptions.read` | Subscription engine alerts |
| GET | `/v1/subscription/dashboard` | `subscriptions.read` | Subscription dashboard KPIs |
| GET | `/v1/subscription/monitoring` | `subscriptions.read` | Subscription monitoring KPIs |

#### Products

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/attachment-jobs` | `subscriptions.read` | List historical attachment jobs |
| POST | `/v1/subscription/attachment-jobs` | `subscriptions.write` | Start a historical attachment preview or apply |
| GET | `/v1/subscription/attachment-jobs/:id` | `subscriptions.read` | Read a historical attachment job |
| POST | `/v1/subscription/attachment-jobs/:id/cancel` | `subscriptions.write` | Cancel a historical attachment job |
| GET | `/v1/subscription/attachment-jobs/:id/errors` | `subscriptions.read` | Read historical attachment failures and skips |
| GET | `/v1/subscription/attachment-jobs/capability` | `subscriptions.read` | Read historical attachment capability |
| POST | `/v1/subscription/plan/preview` | `subscriptions.read` | Simulate a subscription plan |
| GET | `/v1/subscription/storefronts` | `subscriptions.read` | List storefront hosts |
| GET | `/v1/subscription/subscriptions` | `subscriptions.read` | List subscription products |
| POST | `/v1/subscription/subscriptions` | `subscriptions.write` | Create a subscription product |
| GET | `/v1/subscription/subscriptions/:id` | `subscriptions.read` | Get a subscription product |
| PUT | `/v1/subscription/subscriptions/:id` | `subscriptions.write` | Update a subscription product |
| DELETE | `/v1/subscription/subscriptions/:id` | `subscriptions.write` | Delete a subscription product |
| POST | `/v1/subscription/subscriptions/:id/attach` | `subscriptions.write` | Attach a product to past sales |

#### Rebill flows

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/flows` | `subscriptions.read` | List Rebill Flows |
| POST | `/v1/subscription/flows` | `subscriptions.write` | Create a Rebill Flow |
| GET | `/v1/subscription/flows/:id` | `subscriptions.read` | Get a Rebill Flow |
| PATCH | `/v1/subscription/flows/:id` | `subscriptions.write` | Rename a Rebill Flow |
| DELETE | `/v1/subscription/flows/:id` | `subscriptions.write` | Archive a Rebill Flow |
| GET | `/v1/subscription/flows/:id/activity` | `subscriptions.read` | Get Rebill Flow activity |
| PUT | `/v1/subscription/flows/:id/draft` | `subscriptions.write` | Save a Rebill Flow draft |
| POST | `/v1/subscription/flows/:id/duplicate` | `subscriptions.write` | Duplicate a Rebill Flow |
| GET | `/v1/subscription/flows/:id/paused` | `subscriptions.read` | Count subscriptions paused by a Rebill Flow |
| POST | `/v1/subscription/flows/:id/preview` | `subscriptions.read` | Test a Rebill Flow |
| POST | `/v1/subscription/flows/:id/publish` | `subscriptions.write` | Publish a Rebill Flow |
| POST | `/v1/subscription/flows/:id/resume-paused` | `subscriptions.write` | Resume subscriptions paused by a Rebill Flow |
| GET | `/v1/subscription/flows/:id/versions` | `subscriptions.read` | List Rebill Flow versions |
| POST | `/v1/subscription/flows/:id/versions/:version/restore` | `subscriptions.write` | Restore a Rebill Flow version as the draft |
| GET | `/v1/subscription/flows/options` | `subscriptions.read` | Get Rebill Flow options |

#### Subscribers

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/bulk-jobs` | `subscriptions.read` | List subscription bulk-edit jobs (subs and schedule charges) |
| GET | `/v1/subscription/bulk-jobs/:jobId` | `subscriptions.read` | Read a subscription bulk-edit job |
| POST | `/v1/subscription/bulk-jobs/:jobId/cancel` | `subscriptions.write` | Cancel a subscription bulk-edit job |
| GET | `/v1/subscription/bulk-jobs/:jobId/errors` | `subscriptions.read` | Read a subscription bulk-edit job's failures |
| GET | `/v1/subscription/subs` | `subscriptions.read` | List subs (customer subscriptions) |
| POST | `/v1/subscription/subs` | `subscriptions.write` | Attach a product to one sale (manual sub) |
| GET | `/v1/subscription/subs/:id` | `subscriptions.read` | Get a sub |
| PATCH | `/v1/subscription/subs/:id` | `subscriptions.write` | Edit a sub |
| DELETE | `/v1/subscription/subs/:id` | `subscriptions.write` | Cancel a sub |
| POST | `/v1/subscription/subs/:id/charge-now` | `subscriptions.write` | Force bill one sub now |
| POST | `/v1/subscription/subs/:id/charge-now-v2` | `subscriptions.write` | Force bill one sub with a durable operator intent |
| GET | `/v1/subscription/subs/:id/customer` | `subscriptions.read` | Customer view of a sub |
| POST | `/v1/subscription/subs/:id/pause` | `subscriptions.write` | Pause a sub |
| POST | `/v1/subscription/subs/:id/resume` | `subscriptions.write` | Resume a sub |
| POST | `/v1/subscription/subs/attach-sale` | `subscriptions.write` | Re-run the attach for one sale |
| POST | `/v1/subscription/subs/bulk` | `subscriptions.write` | Bulk action on subs |
| GET | `/v1/subscription/subs/by-order/:orderId` | `subscriptions.read` | Subs of an order |
| GET | `/v1/subscription/subs/ids` | `subscriptions.read` | Ids of every sub matching filters |

#### Logs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription-charge-logs` | `operations.read` | List charge batches sent by the external rebill tool |
| GET | `/v1/subscription-export-logs` | `operations.read` | List export sessions pulled by the external rebill tool |
| GET | `/v1/subscription/transactions` | `subscriptions.read` | List subscription engine charges (charge log) |

#### Retry

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/subscription/decline-map` | `subscriptions.write` | Map a decline text to insufficient funds |
| DELETE | `/v1/subscription/decline-map` | `subscriptions.write` | Remove a decline mapping |
| GET | `/v1/subscription/profiles` | `subscriptions.read` | List retry profiles |
| POST | `/v1/subscription/profiles` | `subscriptions.write` | Create a retry profile |
| GET | `/v1/subscription/profiles/:id` | `subscriptions.read` | Get a retry profile |
| PUT | `/v1/subscription/profiles/:id` | `subscriptions.write` | Replace a retry profile |
| DELETE | `/v1/subscription/profiles/:id` | `subscriptions.write` | Delete a retry profile |

#### Settings

| method | address | scope | title |
|---|---|---|---|
| PATCH | `/v1/subscription/routing-constraints` | `subscriptions.write` | Set the rebill routing constraints |
| GET | `/v1/subscription/routing-constraints/feasibility` | `subscriptions.read` | Feasibility of a routing-constraints draft |
| GET | `/v1/subscription/scrub-bins` | `subscriptions.read` | List the subscription engine's scrub BINs |
| POST | `/v1/subscription/scrub-bins` | `subscriptions.write` | Add scrub BINs to the subscription engine |
| PATCH | `/v1/subscription/scrub-bins/:bin` | `subscriptions.write` | Enable or disable a scrub BIN |
| DELETE | `/v1/subscription/scrub-bins/:bin` | `subscriptions.write` | Remove a scrub BIN |
| GET | `/v1/subscription/scrub-bins/history` | `subscriptions.read` | Scrub BIN history |
| POST | `/v1/subscription/scrub-bins/recalculate` | `subscriptions.write` | Recalculate auto scrub BINs |
| GET | `/v1/subscription/scrub-bins/runs` | `subscriptions.read` | List scrub recalculation runs |
| GET | `/v1/subscription/scrub-bins/runs/:runId` | `subscriptions.read` | Get a scrub recalculation run |
| GET | `/v1/subscription/settings` | `subscriptions.read` | Get subscription settings |
| PUT | `/v1/subscription/settings` | `subscriptions.write` | Update subscription settings |
| PATCH | `/v1/subscription/settings/global` | `subscriptions.write` | Set the account dispatch kill switch |

#### Metrics

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/metrics/catalogue` | `subscriptions.read` | Get the subscription metric catalogue |
| GET | `/v1/subscription/metrics/jobs` | `subscriptions.read` | List subscription metrics jobs |
| POST | `/v1/subscription/metrics/jobs` | `subscriptions.write` | Queue a subscription metrics calculation |
| GET | `/v1/subscription/metrics/jobs/:id` | `subscriptions.read` | Get a subscription metrics job |
| POST | `/v1/subscription/metrics/jobs/:id/cancel` | `subscriptions.write` | Cancel a subscription metrics job |
| GET | `/v1/subscription/metrics/jobs/:id/result` | `subscriptions.read` | Get a subscription metrics job result |
| GET | `/v1/subscription/metrics/jobs/capability` | `subscriptions.read` | Subscription metrics job capability |

### Customers

#### Customers

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/customers` | `customers.read` | List customers |
| GET | `/v1/customers/:key/3ds` | `customers.read` | List customer 3DS authentications |
| GET | `/v1/customers/:key/events` | `customers.read` | Customer timeline |
| GET | `/v1/customers/:key/events/export.csv` | `customers.read` | Customer timeline as CSV |
| POST | `/v1/customers/:key/flag` | `customers.write` | Allow or forbid several subscriptions for a customer |
| GET | `/v1/customers/:key/notes` | `customers.read` | List a customer's notes |
| GET | `/v1/customers/:key/subscriptions` | `customers.read` | Every subscription of a customer |
| GET | `/v1/customers/:key/summary` | `customers.read` | Get a customer summary |
| POST | `/v1/customers/bulk` | `customers.write` | Run one action on many customers (preview, then run) |
| GET | `/v1/customers/bulk-jobs` | `customers.read` | List customer bulk jobs |
| POST | `/v1/customers/bulk-jobs` | `customers.write` | Start a customer bulk job |
| GET | `/v1/customers/bulk-jobs/:id` | `customers.read` | Read a customer bulk job |
| POST | `/v1/customers/bulk-jobs/:id/cancel` | `customers.write` | Cancel a customer bulk job |
| GET | `/v1/customers/bulk-jobs/:id/errors` | `customers.read` | List a customer bulk job failures |
| GET | `/v1/customers/bulk-jobs/:id/result` | `customers.read` | Read a customer bulk job result |
| GET | `/v1/customers/export` | `customers.read` | Export customers as CSV |
| GET | `/v1/customers/export-pdf-v2` | `customers.read` | Stream customers for a PDF export |
| GET | `/v1/customers/ids` | `customers.read` | List customer ids (select all matching) |
| GET | `/v1/subscription/customer` | `subscriptions.read` | Customer view by order id or e-mail |

#### Refunds and disputes

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/refund` | `refunds.write` | Refund a transaction |
| POST | `/v1/refund/cancel-test` | `refunds.write` | Cancel TEST refunds (one refund, or every test refund of a transaction) |
| POST | `/v1/refund/chargeback` | `refunds.write` | Mark or unmark a refund as a chargeback |
| POST | `/v1/refund/mark` | `refunds.write` | Mark as refunded (no gateway call) + blacklist |
| POST | `/v1/refund/search` | `refunds.read` | Search transactions by dispute identifiers (card, amount, auth code, descriptor, e-mail, order) |
| GET | `/v1/refund/status` | `refunds.read` | Read refund outcomes of a transaction |
| GET | `/v1/refunds` | `refunds.read` | List refunds |
| POST | `/v1/refunds/:id/dispute` | `refunds.write` | Label a refund as an RDR or Ethoca alert |
| POST | `/v1/transactions/:id/action` | `refunds.write` | Run a refund or dispute action on a transaction |
| POST | `/v1/transactions/:id/chargeback-refund` | `refunds.write` | Refund a transaction and mark it as a chargeback (money moves unless external: true) |
| POST | `/v1/transactions/:id/dispute` | `refunds.write` | Label a transaction RDR or Ethoca without a gateway refund (books an external refund) |
| POST | `/v1/transactions/:transactionId/alert` | `refunds.write` | Settle an Ethoca alert by refunding (money MOVES) |
| POST | `/v1/transactions/:transactionId/chargeback` | `refunds.write` | Mark or unmark a transaction as charged back (no money moves) |
| POST | `/v1/transactions/:transactionId/rdr` | `refunds.write` | Mark an RDR dispute (books an external refund - NO money moves) |

#### Blacklist

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/blacklist` | `customers.read` | List blacklist entries (search, counts by source) |
| POST | `/v1/blacklist` | `customers.write` | Blacklist a customer |
| DELETE | `/v1/blacklist` | `customers.write` | Remove a customer from the blacklist by e-mail or card number |
| DELETE | `/v1/blacklist/:id` | `customers.write` | Remove one blacklist entry by id |
| POST | `/v1/blacklist/check` | `customers.read` | Check whether a customer is blacklisted |
| GET | `/v1/blacklist/cleanup` | `customers.read` | List required blacklist cleanup |
| GET | `/v1/blacklist/cleanup/:id` | `customers.read` | Read a blacklist cleanup job |
| POST | `/v1/blacklist/cleanup/:id/retry` | `customers.write` | Retry a failed blacklist cleanup |
| GET | `/v1/blacklist/client/:clientId` | `customers.read` | List an account's blacklisted customers with their matched orders (partner view) |
| POST | `/v1/blacklist/import` | `customers.write` | Import blacklist e-mails now (synchronous) |
| GET | `/v1/blacklist/import-capabilities` | `customers.read` | Blacklist import capability |
| GET | `/v1/blacklist/import-jobs` | `customers.read` | List blacklist imports |
| POST | `/v1/blacklist/import-jobs` | `customers.write` | Queue a blacklist e-mail import (background job) |
| GET | `/v1/blacklist/import-jobs/:id` | `customers.read` | Get a blacklist import |
| POST | `/v1/blacklist/import-jobs/:id/cancel` | `customers.write` | Stop a blacklist import |
| POST | `/v1/blacklist/import-jobs/:id/retry-cleanup` | `customers.write` | Retry blacklist import cleanup |
| GET | `/v1/blacklist/merchant/:merchantId` | `customers.read` | List blacklisted customers of a merchant (one MID) |

### Reports

#### Dashboard metrics

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics` | `reports.read` | Dashboard metrics (with Straight / Subscription split and ad spend) |

#### Gateways

No endpoint of its own: see this subcategory in Part 4.

#### BINs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/bins` | `reports.read` | Get the Bin & Issuers report |

#### Refunds

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/segments` | `reports.read` | Segment analysis (dashboard: with totals) |

#### Checkouts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/checkouts` | `reports.read` | Checkout analytics |

#### Flows

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/flows` | `reports.read` | Flow performance |

#### Post-sells

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/postsells` | `reports.read` | Read post-sell performance and diagnostics |

#### Products

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/products` | `reports.read` | Product breakdown (dashboard: totals, winners, ad spend) |

#### Affiliates

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/affiliates/report` | `reports.read` | Read the per-affiliate report |

#### Traffic

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/traffic` | `reports.read` | Traffic report by dimension |

#### Recovery

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/recovery/report` | `recovery.read` | Get the cart-recovery funnel report |

#### Subscriptions

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/subscription/reports` | `subscriptions.read` | Per-day subscription report |

#### Financial

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/financial` | `reports.read` | Get the Financial report (the Finance breakdown day by day) |

#### Report jobs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/metrics/jobs` | `reports.read` | List dashboard report calculations |
| POST | `/v1/metrics/jobs` | `reports.write` | Start a dashboard report calculation in the background |
| GET | `/v1/metrics/jobs/:jobId` | `reports.read` | Read a dashboard report calculation's progress |
| POST | `/v1/metrics/jobs/:jobId/cancel` | `reports.write` | Cancel a dashboard report calculation |
| GET | `/v1/metrics/jobs/:jobId/result` | `reports.read` | Read a completed dashboard report |

#### Partner reports

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/report-jobs` | `reports.read` | List Reporting API report calculations |
| POST | `/v1/report-jobs` | `reports.write` | Calculate a Reporting API report in the background |
| GET | `/v1/report-jobs/:jobId` | `reports.read` | Read a Reporting API report calculation's progress |
| POST | `/v1/report-jobs/:jobId/cancel` | `reports.write` | Cancel a Reporting API report calculation |
| GET | `/v1/report-jobs/:jobId/result` | `reports.read` | Read a completed Reporting API report |
| GET | `/v1/report-jobs/capabilities` | `reports.read` | Read Reporting API background availability |
| GET | `/v1/reports/gateways` | `reports.read` | Gateway report (Reporting API: stable shape) |
| GET | `/v1/reports/products` | `reports.read` | Product report (Reporting API: stable shape) |
| GET | `/v1/reports/segments` | `reports.read` | Segment report (Reporting API: stable shape) |
| GET | `/v1/reports/transactions` | `transactions.read` | Transactions report (Reporting API: stable shape, exact total) |
| GET | `/v1/status/daily` | `reports.read` | Get daily status snapshot |

### Settings

#### Integrations

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/expify` | `integrations.read` | Get the Exify export configuration |
| GET | `/v1/expify/credentials` | `integrations.write` | Read the Exify targets' stored secrets |
| GET | `/v1/expify/jobs` | `integrations.read` | List queued Exify export jobs |
| POST | `/v1/expify/jobs` | `integrations.write` | Queue an Exify export |
| GET | `/v1/expify/jobs/:id` | `integrations.read` | Get an Exify export |
| GET | `/v1/expify/jobs/:id/batches` | `integrations.read` | List the batches of an Exify export |
| POST | `/v1/expify/jobs/:id/batches/:batchId/resolve` | `integrations.write` | Resolve an unknown Exify batch |
| POST | `/v1/expify/jobs/:id/batches/:batchId/retry` | `integrations.write` | Retry a refused Exify batch |
| POST | `/v1/expify/jobs/:id/cancel` | `integrations.write` | Cancel an Exify export |
| GET | `/v1/expify/jobs/:id/items` | `integrations.read` | List the items of an Exify export |
| GET | `/v1/expify/jobs/capability` | `integrations.read` | Exify export job capability |
| GET | `/v1/expify/preview` | `integrations.read` | Preview Exify export payloads |
| POST | `/v1/expify/run` | `integrations.write` | Run the Exify export now (retired) |
| GET | `/v1/expify/runs` | `integrations.read` | List scheduled Exify export runs (daily cron log) |
| GET | `/v1/expify/runs/:id/sends` | `integrations.read` | List the sends of an Exify run |
| PATCH | `/v1/expify/settings` | `integrations.write` | Update Exify export settings |
| PATCH | `/v1/expify/targets/:version` | `integrations.write` | Update an Exify target |
| GET | `/v1/integrations` | `integrations.read` | List integrations catalog + account state |
| GET | `/v1/integrations/3ds/metrics` | `integrations.read` | Get 3DS analytics for a date range |
| GET | `/v1/integrations/3ds/sessions` | `integrations.read` | List recent 3DS sessions |
| PUT | `/v1/integrations/:key` | `integrations.write` | Save an integration (enable, config, secrets) |
| GET | `/v1/integrations/:key/secrets` | `integrations.write` | Read an integration's stored secrets (in clear) |
| POST | `/v1/integrations/:key/test` | `integrations.write` | Test an integration's credentials |
| GET | `/v1/integrations/alerts` | `integrations.read` | List inbound dispute alerts |
| POST | `/v1/integrations/creative/jobs` | `integrations.write` | Create an idempotent creative generation job |
| GET | `/v1/integrations/creative/jobs/:id` | `integrations.read` | Read a creative job |
| POST | `/v1/integrations/creative/jobs/:id/poll` | `integrations.write` | Poll a creative media job |
| GET | `/v1/integrations/friendlies/keys` | `integrations.read` | List API key identities for Friendlies pricing |
| GET | `/v1/integrations/friendlies/metrics` | `integrations.read` | Friendlies analytics |
| POST | `/v1/integrations/google_ads/conversion-actions` | `integrations.write` | Google Ads - list the conversion actions ("Test connection") |
| GET | `/v1/integrations/pilot/sync` | `integrations.read` | Pilot spend sync: status |
| POST | `/v1/integrations/pilot/sync` | `integrations.write` | Pilot spend sync: run now |
| GET | `/v1/integrations/pilot/sync-capabilities` | `integrations.read` | Read Pilot sync availability |
| GET | `/v1/integrations/pilot/sync-jobs` | `integrations.read` | List Pilot sync jobs |
| POST | `/v1/integrations/pilot/sync-jobs` | `integrations.write` | Start a Pilot spend sync |
| GET | `/v1/integrations/pilot/sync-jobs/:jobId` | `integrations.read` | Read a Pilot sync job |
| POST | `/v1/integrations/pilot/sync-jobs/:jobId/cancel` | `integrations.write` | Cancel a Pilot sync job |
| GET | `/v1/integrations/pilot/sync-jobs/:jobId/errors` | `integrations.read` | List the failed or skipped days of a Pilot sync |
| GET | `/v1/integrations/pilot/targets` | `integrations.read` | Pilot campaign targets - list |
| PUT | `/v1/integrations/pilot/targets` | `integrations.write` | Pilot campaign targets - manual overrides |
| GET | `/v1/integrations/product-matching/metrics` | `integrations.read` | Get smart product matching analytics |
| GET | `/v1/integrations/thesupportcare/logs` | `integrations.read` | List recent TheSupportCare sends |
| POST | `/v1/integrations/thesupportcare/test` | `integrations.write` | Test TheSupportCare credentials |
| GET | `/v1/platformpay` | `integrations.read` | Read PlatformPay settings and 24h send stats |
| GET | `/v1/platformpay/credentials` | `integrations.write` | Read the stored PlatformPay secret_key |
| GET | `/v1/platformpay/sends` | `integrations.read` | List PlatformPay send attempts |
| PATCH | `/v1/platformpay/settings` | `integrations.write` | Update PlatformPay settings |
| GET | `/v1/storefronts` | `routing.read` | List storefront catalogs |
| POST | `/v1/storefronts` | `routing.write` | Create a storefront catalog for a host |
| PATCH | `/v1/storefronts/:id` | `routing.write` | Rename a storefront or change its host |
| DELETE | `/v1/storefronts/:id` | `routing.write` | Delete a storefront and its catalog |
| GET | `/v1/storefronts/:id/products` | `routing.read` | List a storefront's products |
| PUT | `/v1/storefronts/:id/products` | `routing.write` | Replace a storefront's product list |

#### Monitoring and alerts

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/reconciliation` | `operations.read` | Get reconciliation gaps |
| POST | `/v1/reconciliation/run` | `operations.write` | Run reconciliation now |
| GET | `/v1/uptime/contacts` | `monitoring.read` | List alert destinations |
| POST | `/v1/uptime/contacts` | `monitoring.write` | Add an alert destination |
| PATCH | `/v1/uptime/contacts/:id` | `monitoring.write` | Update an alert destination |
| DELETE | `/v1/uptime/contacts/:id` | `monitoring.write` | Delete an alert destination |
| POST | `/v1/uptime/contacts/:id/resend` | `monitoring.write` | Resend a destination code |
| POST | `/v1/uptime/contacts/test` | `monitoring.write` | Send a test alert to a destination |
| POST | `/v1/uptime/contacts/verify` | `monitoring.write` | Verify a destination |
| GET | `/v1/uptime/events` | `monitoring.read` | List uptime events |
| GET | `/v1/uptime/monitors` | `monitoring.read` | List uptime monitors |
| POST | `/v1/uptime/monitors/:id/test` | `monitoring.write` | Send a test alert for a monitor |

#### Members

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/users` | `users.read` | List account members |
| POST | `/v1/users/password` | `users.write` | Set a member's password |
| PUT | `/v1/users/role` | `users.write` | Add a member or change its role |
| DELETE | `/v1/users/role` | `users.write` | Remove a member |
| GET | `/v1/users/trips` | `users.read` | Read a member's ATRI view grants |
| PUT | `/v1/users/trips` | `users.write` | Replace a member's ATRI view grants |

#### Account and billing

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/platform-subscription` | `billing.read` | Read platform subscription and offers |
| POST | `/v1/platform-subscription/cancel` | `billing.write` | Cancel the platform subscription renewal |
| POST | `/v1/platform-subscription/checkout` | `billing.write` | Prepare the platform subscription invoice |
| GET | `/v1/platform-subscription/invoices` | `billing.read` | List platform subscription invoices |
| GET | `/v1/platform-subscription/invoices/:id` | `billing.read` | Read a platform subscription invoice |
| GET | `/v1/platform-subscription/invoices/:id/pdf` | `billing.read` | Download a platform subscription invoice PDF |
| POST | `/v1/platform-subscription/onboarding` | `billing.write` | Complete account setup and accept subscription terms |
| GET | `/v1/platform-subscription/plan-change` | `billing.read` | Review a proposed plan change |
| POST | `/v1/platform-subscription/plan-change/accept` | `billing.write` | Accept a proposed plan change |
| POST | `/v1/platform-subscription/plan-change/decline` | `billing.write` | Decline or withdraw a plan change |
| POST | `/v1/platform-subscription/resume` | `billing.write` | Resume the platform subscription renewal |
| GET | `/v1/settings` | `settings.read` | Read account settings |
| PATCH | `/v1/settings` | `settings.write` | Update account settings |
| GET | `/v1/settings/credentials` | `settings.write` | Reveal the stored Telegram bot token |

#### Agreements

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/me/agreements` | `billing.read` | List account CRM agreements |
| POST | `/v1/me/agreements` | `billing.write` | Generate a CRM agreement draft |
| GET | `/v1/me/agreements/:id` | `billing.read` | Read a CRM agreement |
| GET | `/v1/me/agreements/:id/pdf` | `billing.read` | Download CRM agreement PDF |
| POST | `/v1/me/agreements/:id/sign` | `billing.write` | Sign a CRM agreement |

#### Logs

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/audit-logs` | `operations.read` | List audit logs |
| GET | `/v1/charge-logs` | `operations.read` | List /v1/charge requests (every call, refused ones included) |
| GET | `/v1/checkouts/event-types` | `tracking.read` | List the checkout event types in use |
| GET | `/v1/checkouts/events` | `tracking.read` | List checkout events (flat, filterable) |
| GET | `/v1/errors` | `operations.read` | List server errors |
| GET | `/v1/filters/hits` | `routing.read` | Read the filter block log |
| GET | `/v1/wallet-logs` | `operations.read` | Wallet Logs |

#### Preferences

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/me/prefs` | `settings.read` | Get my dashboard preferences |
| PUT | `/v1/me/prefs` | `settings.write` | Merge my dashboard preferences |

### Inbound webhooks

#### Payment providers and 3-D Secure

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/3ds/callback/:id/method` | no key (provider) | 3DS Method completion callback (browser redirect, GET) |
| POST | `/v1/3ds/callback/:id/method` | no key (provider) | 3DS Method completion callback (form post, POST) |
| POST | `/v1/3ds/callback/:id/notify` | no key (provider) | ACS challenge result callback (CRes) |
| GET | `/v1/3ds/callback/:id/return` | no key (provider) | Hosted challenge return callback (browser redirect, GET) |
| POST | `/v1/3ds/callback/:id/return` | no key (provider) | Hosted challenge return callback (form post, POST) |
| GET | `/v1/payments/return` | no key (provider) | Resume a checkout after a provider return (browser redirect, GET) |
| POST | `/v1/payments/return` | no key (provider) | Resume a checkout after a provider return (form post, POST) |
| GET | `/v1/payments/return/complete` | no key (provider) | Display a neutral payment return page |
| POST | `/v1/stripe/webhooks/:accountId` | no key (provider) | Receive a Stripe webhook (provider) |

#### Dispute alerts

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/alerts/:provider/:account` | no key (provider) | Receive a chargeback / dispute alert (webhook) |

#### Messaging delivery reports

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/recovery/email-callback/:providerId` | no key (provider) | E-mail delivery receipt (Resend webhook) |
| POST | `/v1/recovery/sms-callback` | no key (provider) | MessageWhiz delivery report |

#### Store platforms

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/shopify/oauth/callback` | no key (provider) | Shopify OAuth callback (browser) |

#### Uptime monitoring

| method | address | scope | title |
|---|---|---|---|
| POST | `/v1/uptime/callback` | no key (provider) | UptimeRobot alert sink |

### Outbound webhooks and services

#### Checkout webhooks

| method | address | scope | title |
|---|---|---|---|
| GET | `/v1/checkouts/:checkoutId/webhooks` | `checkouts.read` | List checkout webhooks |
| POST | `/v1/checkouts/:checkoutId/webhooks` | `checkouts.write` | Add checkout webhook |
| PUT | `/v1/checkouts/:checkoutId/webhooks/:endpointId` | `checkouts.write` | Edit checkout webhook |
| DELETE | `/v1/checkouts/:checkoutId/webhooks/:endpointId` | `checkouts.write` | Delete checkout webhook |
| GET | `/v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries` | `checkouts.read` | List webhook deliveries |
| GET | `/v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries/:deliveryId` | `checkouts.read` | View webhook payload and attempts |
| POST | `/v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries/:deliveryId/resend` | `checkouts.write` | Resend one webhook delivery |
| POST | `/v1/checkouts/:checkoutId/webhooks/:endpointId/resend-failed` | `checkouts.write` | Resend failed webhook period |
| POST | `/v1/checkouts/:checkoutId/webhooks/:endpointId/rotate-secret` | `checkouts.write` | Rotate webhook secret |
| POST | `/v1/checkouts/:checkoutId/webhooks/:endpointId/test` | `checkouts.write` | Send a synthetic webhook event |

#### Services Kontrol calls

No endpoint of its own: see this subcategory in Part 4.

## 4. Endpoint reference

### Getting started

Who you are, which key and scopes you hold, and how the API answers: identity, API keys and their permissions, search, errors, limits and service status.

#### Authentication and identity

Identify the API key and the account it acts for. Part 1 of llm.md explains the Authorization header.

##### `GET /v1/me`

**Scope** `settings.read` - **Identify the API key and its account (account id, key label, default ATRI)**

Identifies the API key itself and its account (accountId, account e-mail, key label and prefix, default ATRI): the one public identity call. Validates a key and identifies the account it belongs to: a stable opaque accountId, the account e-mail, the key's own label and prefix, and the ATRI a charge without a route would use. Read-only, apart from a best-effort last_used_at update on the key.

*No parameters.*

**Response**

```json
{
  "accountId": "acc_3f9c1e7a2b6d4081",
  "accountEmail": "clienta@example.com",
  "name": "RB Client A",
  "keyPrefix": "ck_abc123",
  "defaultAtri": "6f2b1c94-8d3a-4a71-b0e5-1c7d9f4e2a83"
}
```

| response field | type | description |
|---|---|---|
| `accountId` | string | Opaque, STABLE account id: `acc_` + first 16 hex of sha256(lower-cased account email). Never changes for an account; identical across all of its keys; the same value the rebill export stamps on `results[].accountId`. |
| `accountEmail` | string | The account's main-user email (the tenancy key - api_keys.owner_email). Sub-account users of that account resolve to the same account. |
| `name` | string | The API KEY's label (api_keys.name) - what the account named this integration (e.g. 'RB Client A'). There is no separate account display name; use this or `accountEmail` to label a profile. |
| `keyPrefix` | string \| null | Non-secret display prefix of the key (`ck_` + 6 chars), for showing next to the masked key. |
| `defaultAtri` | string (uuid) \| null | The ATRI a charge from this key routes to when it omits `atri`: the key's own default (api_keys.default_trip_id) if set, else the ACCOUNT's default ATRI (trips.is_default, per account). null = this key must always pass `atri`. |

**Errors**

- `401` {"error":"Missing API key"}: neither Authorization: Bearer <key> nor a non-empty X-Api-Key header.
- `401` {"error":"Invalid API key"}: unknown or inactive key.
- `401` {"error":"API key is not attached to an account"}: the key has no owning account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"settings.read"} when the key's scopes lack settings.read; {"error":"Banned","message":"..."} when the account owner is banned.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Service temporarily unavailable","detail":"authentication backend error"}: the key lookup failed (retry).

**Gotchas**

- `name` is the key's label, not an account name (accounts have no display name). Two keys of one account have the same accountId and can have different names.
- `accountId` is "acc_" + 16 hex characters of a hash of the account e-mail: stable and opaque, not a database id.
- `defaultAtri` can be null: then every charge must name its route. GET /v1/atris lists the choices.
- Default per-IP rate limit (300 per minute): cache the answer, do not call it per charge.

#### API keys and permissions

Create, scope, rotate and revoke the account's API keys (Settings > API keys in the dashboard). A key can only grant the scopes it holds.

##### `GET /v1/keys`

**Scope** `api_keys.read` - **List API keys**

Lists every API key of the caller's account, newest first, with its scopes, default ATRI, active flag and the non-secret prefix plus the last 6 characters of the raw key. The full key is never in this response.

*No parameters.*

**Response**

```json
{
  "keys": [
    {
      "id": "11111111-2222-4333-8444-555555555555",
      "name": "Agent automation key",
      "key_prefix": "ck_9fK2mQ",
      "default_trip_id": "22222222-3333-4444-8555-666666666666",
      "active": true,
      "key_type": "charge",
      "scopes": [
        "transactions.read",
        "reports.read"
      ],
      "created_at": "2026-11-20T09:12:44.318Z",
      "last_used_at": "2026-11-23T06:31:02.774Z",
      "scope_catalog": 2,
      "key_last6": "eUc4Gi"
    },
    {
      "id": "33333333-4444-4555-8666-777777777777",
      "name": "Checkout backend",
      "key_prefix": "ck_Xp7Lda",
      "default_trip_id": null,
      "active": false,
      "key_type": "admin",
      "scopes": null,
      "created_at": "2025-11-02T18:45:10.002Z",
      "last_used_at": null,
      "scope_catalog": null,
      "key_last6": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `keys` | object[] | Every key of the caller's account, newest first (created_at desc). No pagination, no filter; inactive keys are included. |
| `keys[].id` | uuid | Key id, the :id of the reveal, PATCH and DELETE routes. |
| `keys[].name` | string | Label chosen at creation (1..128 chars). Not unique. |
| `keys[].key_prefix` | string | Non-secret display prefix: "ck_" plus the first 6 characters after it (9 characters). |
| `keys[].key_last6` | string \| null | Last 6 characters of the raw key (decrypted for display). null for a key stored before encrypted copies existed; such a key can never be revealed. |
| `keys[].default_trip_id` | uuid \| null | Default ATRI of the key: where a charge that names no route goes. Always an ATRI of the same account. |
| `keys[].active` | boolean | false = the key no longer authenticates anywhere (soft revoke). |
| `keys[].key_type` | "charge" \| "admin" | Legacy column, kept for compatibility. Ignored by every check: any active key drives its account. New keys get the column default ("charge"). |
| `keys[].scopes` | string[] \| null | The key's permissions ("<category>.read" / "<category>.write"); null = the complete catalogue, [] = none. |
| `keys[].scope_catalog` | integer \| null | 2 = scopes read with the current catalogue; 1 or null = saved before 2026-11-24 (see the scope catalog note of POST /v1/keys). |
| `keys[].created_at` | string (ISO-8601) | Creation time. |
| `keys[].last_used_at` | string (ISO-8601) \| null | Last time the key was seen on POST /v1/charge, GET /v1/atris, GET /v1/me, the /v1/3ds, /v1/recovery and /v1/checkouts key routes or the rebill export. Calls to the account routes (/v1/<account route>) do not update it; null = never seen there. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.read"} when the key's scopes lack api_keys.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the account's plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (the keys page is for account administrators).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: a stored encrypted copy could not be decrypted (the whole list fails, not only that row), or another unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: statement timeout.

**Gotchas**

- One key type: every active key of the account drives the whole account through the API, limited only by its scopes. The legacy key_type column ("charge" or "admin") is still returned but no check reads it; keyType sent on a write is accepted and ignored.
- Reads no query parameter: limit, offset, search or active filters are ignored and the whole list is returned.
- key_last6 only identifies a key. The raw key is in the apiKey field of POST /v1/keys; GET /v1/keys/:id/reveal returns it again (to a key, only with api_keys.write and only for keys within its own scopes).
- Keys without an owning account (owner removed) are invisible here and cannot be managed through the API.
- scopes semantics: null = every category, including future ones; [] = nothing. See POST /v1/keys for the category list and which routes each category opens.

##### `POST /v1/keys`

**Scope** `api_keys.write` - **Create an API key**

Generates a new API key for the caller's account ("ck_" + 32 base64url characters), stores its SHA-256 hash and an encrypted copy, and returns the raw key once in apiKey. The key can drive every account route its scopes allow. Optionally pins a default ATRI for charges made with it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string 1..128 | **yes** | Label of the key. Not unique: two keys may share a name. |
| `scopes` | string[] (<= 38, unique) \| null; default `null` | no | The permissions of the key, as an array of unique entries "<category>.read" or "<category>.write", at most 38 (every known entry once). Categories (19): charges (Charges & 3DS), transactions (Transactions), refunds (Refunds & disputes), kontrolpay (KontrolPay), routing (ATRIs, gateways & wallets), subscriptions (Subscriptions & schedules), customers (Customers & blacklist), checkouts (Stores & checkout builder), tracking (Pixels & tracking), recovery (Cart recovery), reports (Dashboard & reports), integrations (Integrations & messaging), api_keys (API keys), users (Users & access), settings (Account settings), billing (Kontrol subscription & agreements), operations (Logs & operations), monitoring (Uptime monitoring), affiliates (Affiliates). null = the complete catalogue, including categories added later; [] = no permission at all (every scoped route answers 403). read covers GET and HEAD plus the few searches sent as POST (POST /v1/refund/search, POST /v1/blacklist/check, POST /v1/transactions, POST /v1/charge/status, POST /v1/refund/search, the products query, and any POST ending in /preview or /capabilities); write covers every other method. write does not imply read: grant both to edit what you read. An unknown entry is a 400 ("Unknown API scope"), a repeated one a 400 ("Duplicate API scope"). Omitted = null (complete catalogue) for a caller without explicit scopes. A caller whose own key has explicit scopes must send an explicit array contained in its own scopes; omitted, null or broader is a 403. |
| `defaultTripId` | uuid; default `null` | no | Default ATRI for charges made with this key that name no route. Must be an ATRI of the caller's account (404 "Unknown ATRI" otherwise). Omitted = no default (the account default applies). |
| `keyType` | "charge" \| "admin" | no | Accepted and ignored (not even validated on create): there is one key type. The legacy column takes its default. |

**Request body**

```json
{
  "name": "Agent automation key",
  "scopes": [
    "transactions.read",
    "reports.read"
  ],
  "defaultTripId": "22222222-3333-4444-8555-666666666666"
}
```

**Response** `201`

```json
{
  "key": {
    "id": "11111111-2222-4333-8444-555555555555",
    "name": "Agent automation key",
    "key_prefix": "ck_9fK2mQ",
    "default_trip_id": "22222222-3333-4444-8555-666666666666",
    "active": true,
    "key_type": "charge",
    "scopes": [
      "transactions.read",
      "reports.read"
    ],
    "created_at": "2026-11-20T09:12:44.318Z"
  },
  "apiKey": "ck_9fK2mQxL7vTbR3nD8sJhW0yZpAeUc4Gi"
}
```

| response field | type | description |
|---|---|---|
| `apiKey` | string | The raw key, "ck_" + 32 base64url characters. Send it as Authorization: Bearer <apiKey> or X-Api-Key: <apiKey>. Store it now; it can be read again only through GET /v1/keys/:id/reveal. |
| `key.id` | uuid | Key id. |
| `key.name` | string | Label. |
| `key.key_prefix` | string | "ck_" plus the first 6 characters after it. |
| `key.default_trip_id` | uuid \| null | Default ATRI, or null. |
| `key.active` | boolean | Active flag (true on creation). |
| `key.key_type` | "charge" \| "admin" | Legacy column, ignored by every check ("charge" on a new key). |
| `key.scopes` | string[] \| null | Permissions; null = complete catalogue, [] = none. |
| `key.created_at` | string (ISO-8601) | Creation time. |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): name missing, empty or over 128 characters, defaultTripId not a uuid, scopes not an array or null, an unknown entry ("Unknown API scope"), a repeated entry ("Duplicate API scope") or more entries than the catalogue.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.write"} when the key's scopes lack api_keys.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the account's plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (the keys page is for account administrators); {"error":"Cannot grant scopes beyond your own key"} when the caller's key has explicit scopes and the new key's scopes are omitted, null or not contained in them.
- `404` {"error":"Unknown ATRI"}: defaultTripId does not exist or belongs to another account (checked before the scope rule).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: the encrypted copy could not be produced (the key is not created), or another unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- One key type: every active key of the account drives the whole account through the API, limited only by its scopes. The legacy key_type column ("charge" or "admin") is still returned but no check reads it; keyType sent on a write is accepted and ignored.
- Answers 201, not 200.
- Which category a route needs (apiScopeFor in the code; the first rule that matches wins): api_keys = /v1/keys*. kontrolpay = /v1/kontrolpay*. billing = /v1/platform-subscription*, /v1/me/agreements*. monitoring = /v1/uptime*. refunds = /v1/transactions/:id/action, /v1/transactions/:id/dispute, /v1/transactions/:id/chargeback-refund, /v1/refund*, /v1/refunds*, /v1/refund-logs*, and the partner /v1/transactions/:transactionId/chargeback | rdr | alert routes. charges = /v1/transactions/charge, /v1/transactions/:id/retry, /v1/charge*, /v1/3ds*, /v1/stripe*, /v1/checkout/pre-auth, /v2/rebill-batches*. reports = /v1/affiliates/report, /v1/v5/affiliates/report, /v1/metrics*, the report jobs (/v1/metrics/jobs* and /v1/report-jobs*), /v1/home-ai*, /v1/bin-info*, /v1/bin-map*, /v1/reports/* (but /v1/reports/transactions is transactions), /v1/status*. affiliates = /v1/affiliates*, /v1/v5/affiliates*. routing = /v1/v5/flow-payment-capabilities, /v1/trips*, /v1/accounts*, /v1/categories*, /v1/processors*, /v1/acquiring-banks*, /v1/companies*, /v1/wallet-providers*, /v1/payment-atris*, /v1/bank-accounts*, /v1/storefronts*, /v1/filters*, the other /v1/bin-* routes, GET /v1/atris. checkouts = /v1/v5/flows*, /v1/v5/funnels*, /v1/v5/checkouts*, /v1/v5/catalog*, /v1/checkouts* (except the tracking routes), /v1/editor*, /v1/discounts*. tracking = /v1/checkouts/pixels*, /v1/checkouts/:shopId/pixels*, pixels-audit, events and event-types. recovery = /v1/recovery*. transactions = the other /v1/transactions* routes, /v1/reports/transactions. customers = /v1/customers*, /v1/blacklist*, /v1/scrub-bins*. subscriptions = /v1/subscription/*, /v1/rebill*, /v1/subs*, /v1/schedules*, POST /api/exportrb-v2. integrations = /v1/integrations*, /v1/messaging*, /v1/expify*, /v1/platformpay*, /v1/sender-atris*, /v1/sender-rates*, /v1/sender-costs*. users = /v1/users*. settings = /v1/me/* (but /v1/me/agreements is billing), /v1/settings*, GET /v1/me. operations = the logs and health routes (/v1/audit-logs, /v1/charge-logs, /v1/errors, /v1/rejections, /v1/wallet-logs, /v1/subscription-charge-logs, /v1/subscription-export-logs, /v1/health, /v1/infra-health, /v1/perf, /v1/reconciliation, /v1/openapi.json, /v1/operation-capabilities) and any other account route no rule names. The cross-category readers /v1/search and /v1/entities need every read scope (GET) or every write scope (other methods). Platform operator routes (platform plans, platform KontrolPay, the accounts list, order import, unified journal, job runs, audit fixes, member bans, BIN migration check) take no scope: no key reaches them.
- Scope catalog: a key created, or whose scopes are saved, from 2026-11-24 is stamped scope_catalog 2 (the categories above). An older restricted key (scope_catalog 1 or null) keeps every route it reached: a route that moved category since (uptime, sender pools, usage, flow payment capabilities, reading the platform subscription: before in operations; the account agreements: before in settings) also accepts its old scope. It gains none of the new categories (kontrolpay, billing, monitoring) until its scopes are saved again, which moves it to catalog 2. The new key is stamped catalog 2 (scope_catalog is not in this answer; GET /v1/keys shows it).
- Grant only what the agent needs: for example ["transactions.read","reports.read"] for a reporting agent. A key never reaches platform-operator routes or another account, whatever its scopes (its role is pinned to admin of its own account).
- Unknown body fields are silently dropped. There is no limit on the number of keys and no duplicate-name check: retrying a create in a loop creates several live keys.
- Revoke with PATCH /v1/keys/:id {"active":false} rather than DELETE when the key has history (see DELETE /v1/keys/:id).

##### `PATCH /v1/keys/:id`

**Scope** `api_keys.write` - **Update a key**

Partial update of one of the account's keys: rename it, change its scopes, switch it on or off (soft revoke), or change its default ATRI, optionally guarded by the default ATRI the caller last read. Only the fields present in the body are written.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Key id from GET /v1/keys. Not validated before the query: a value that is not a uuid answers 400 "A value has an invalid format.". |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string 1..128 | no | New label. null is a 400. |
| `scopes` | string[] (<= 38, unique) \| null | no | The permissions of the key, as an array of unique entries "<category>.read" or "<category>.write", at most 38 (every known entry once). Categories (19): charges (Charges & 3DS), transactions (Transactions), refunds (Refunds & disputes), kontrolpay (KontrolPay), routing (ATRIs, gateways & wallets), subscriptions (Subscriptions & schedules), customers (Customers & blacklist), checkouts (Stores & checkout builder), tracking (Pixels & tracking), recovery (Cart recovery), reports (Dashboard & reports), integrations (Integrations & messaging), api_keys (API keys), users (Users & access), settings (Account settings), billing (Kontrol subscription & agreements), operations (Logs & operations), monitoring (Uptime monitoring), affiliates (Affiliates). null = the complete catalogue, including categories added later; [] = no permission at all (every scoped route answers 403). read covers GET and HEAD plus the few searches sent as POST (POST /v1/refund/search, POST /v1/blacklist/check, POST /v1/transactions, POST /v1/charge/status, the products query, and any POST ending in /preview or /capabilities); write covers every other method. write does not imply read: grant both to edit what you read. An unknown entry is a 400 ("Unknown API scope"), a repeated one a 400 ("Duplicate API scope"). Omitted = unchanged. null = complete catalogue (refused with 403 to a caller whose own key has explicit scopes). Saving scopes also stamps the key with the current catalogue (scope_catalog 2): an older key loses its legacy route mapping then (see POST /v1/keys). |
| `active` | boolean | no | false stops the key from authenticating anywhere on the next request (soft revoke, history kept); true re-enables it. null is a 400. |
| `defaultTripId` | uuid \| null | no | New default ATRI (must be an ATRI of the caller's account, else 404 "Unknown ATRI"), or null to clear it (the account default then applies). |
| `ifDefaultTripId` | uuid \| null | no | Optional precondition: the default ATRI the caller last read (null = "it had none"). When present, the update applies only if the stored default still equals it, whatever fields the body changes; otherwise 409 with the current value. Absent = no precondition. |
| `keyType` | "charge" \| "admin" | no | Accepted for compatibility and ignored: there is one key type. Still validated (any other value is a 400). Sent alone it counts as no field (400 "No fields to update"). |

**Request body**

```json
{
  "scopes": [
    "transactions.read",
    "reports.read",
    "refunds.read"
  ],
  "ifDefaultTripId": "22222222-3333-4444-8555-666666666666"
}
```

**Response**

```json
{
  "key": {
    "id": "11111111-2222-4333-8444-555555555555",
    "name": "Agent automation key",
    "key_prefix": "ck_9fK2mQ",
    "default_trip_id": "22222222-3333-4444-8555-666666666666",
    "active": true,
    "key_type": "charge",
    "scopes": [
      "transactions.read",
      "reports.read",
      "refunds.read"
    ],
    "created_at": "2026-11-20T09:12:44.318Z",
    "last_used_at": "2026-11-23T06:31:02.774Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `key.id` | uuid | Key id. |
| `key.name` | string | Label. |
| `key.key_prefix` | string | "ck_" plus the first 6 characters after it. |
| `key.default_trip_id` | uuid \| null | Default ATRI, or null. |
| `key.active` | boolean | Active flag (true on creation). |
| `key.key_type` | "charge" \| "admin" | Legacy column, ignored by every check ("charge" on a new key). |
| `key.scopes` | string[] \| null | Permissions; null = complete catalogue, [] = none. |
| `key.created_at` | string (ISO-8601) | Creation time. |
| `key.last_used_at` | string (ISO-8601) \| null | Last use on the charge path and the small key readers (see GET /v1/keys). |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): a field of the wrong type (null name or active, keyType outside charge|admin, a uuid field that is not a uuid), an unknown or repeated scope.
- `400` {"error":"No fields to update"}: none of name, scopes, active, defaultTripId is present (for example {} or only keyType / ifDefaultTripId).
- `400` {"error":"A value has an invalid format."}: :id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.write"} when the key's scopes lack api_keys.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the account's plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (the keys page is for account administrators); {"error":"Cannot manage a key with scopes beyond your own key"} when the caller's key has explicit scopes and the target key's scopes, or the new scopes, are null or not contained in them.
- `404` {"error":"Not found"}: no such key in the caller's account (or, for a caller with explicit scopes of the current catalogue, a target saved under an older catalogue); {"error":"Unknown ATRI"}: defaultTripId is not an ATRI of the account.
- `409` {"error":"This key's default ATRI was changed in another session. Reload the key and apply your change again.","defaultTripId":"<current uuid or null>"}: ifDefaultTripId no longer matches. Nothing is written.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- One key type: every active key of the account drives the whole account through the API, limited only by its scopes. The legacy key_type column ("charge" or "admin") is still returned but no check reads it; keyType sent on a write is accepted and ignored.
- Send only the fields you change: an omitted field is left as it is.
- Setting active:false (or removing the scope you are using) on the key you are calling with locks you out on the next request.
- Check order: body validation (400), the scope rule for a caller with explicit scopes (404 / 403), the ATRI ownership (404 Unknown ATRI), then "No fields to update" (400).
- The default ATRI decides where charges that name no route go: when an agent changes it, send ifDefaultTripId with the value it read so a concurrent change is a 409, not a silent overwrite.

##### `DELETE /v1/keys/:id`

**Scope** `api_keys.write` - **Delete a key**

Permanently deletes one of the account's keys (hard delete of the row). The key stops authenticating at once. Prefer PATCH /v1/keys/:id {"active":false} to revoke a key that has history.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Key id from GET /v1/keys. Not validated before the query: a value that is not a uuid answers 400 "A value has an invalid format.". |

**Response** `204`

```json
HTTP/1.1 204 No Content (empty body)
```

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.write"} when the key's scopes lack api_keys.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the account's plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (the keys page is for account administrators).
- `404` {"error":"Not found"}: no such key in the caller's account, or (caller with explicit scopes) the target key's scopes are null or not contained in the caller's. Nothing is deleted.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- 204 with an empty body: do not parse JSON.
- Everything that pointed at the key loses the link (the references are set to null): past transactions, charge and rebill request logs, subscription schedules that bill with the key, and checkouts bound to it for payment. Such a checkout cannot take payments until it is bound to another key, and history that the account sees only through this key may drop out of its lists. Revoke with PATCH {"active":false} instead unless you mean this.
- Member grants on the key (user_api_keys) are deleted with it.
- A repeat call answers 404. Deleting the key you are calling with succeeds and locks you out.

##### `GET /v1/keys/:id/reveal`

**Scope** `api_keys.write` - **Reveal a raw key**

Decrypts and returns the full raw key of one of the account's keys so it can be copied again after creation. Writes an audit row (action reveal_key, page API Keys, the caller or the key as actor) and answers with Cache-Control: no-store.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Key id from GET /v1/keys. Not validated before the query: a value that is not a uuid answers 400 "A value has an invalid format.". |

**Response**

```json
{
  "apiKey": "ck_9fK2mQxL7vTbR3nD8sJhW0yZpAeUc4Gi"
}
```

| response field | type | description |
|---|---|---|
| `apiKey` | string | The full raw key ("ck_" + 32 base64url characters). |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.read"} when the key's scopes lack api_keys.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the account's plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (the keys page is for account administrators); {"error":"Stored secrets are only returned to an API key that may edit this configuration","code":"insufficient_scope","requiredScope":"api_keys.write"} for a key without api_keys.write; {"error":"Stored secrets are only returned to a role that may edit this configuration"} for a member who may not edit keys.
- `404` {"error":"Not found"}: no such key in the caller's account (another account's id answers the same), or, for a key with explicit scopes, a key beyond its own scopes or of an older scope catalogue.
- `409` {"error":"This key predates secure reveal and cannot be recovered. Revoke it and create a new one to get a copyable key."}: no encrypted copy is stored. Permanent: revoke and recreate.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: the encrypted copy could not be decrypted, or another unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- An unrestricted key (scopes null) or any account administrator can reveal every key of the account, including the one in use. A restricted key reveals only keys it could have granted itself. The audit row is best-effort.
- The raw key is a live credential: never log or cache the answer.
- 409 is permanent: a key without an encrypted copy can never be revealed.

##### `GET /v1/keys/scopes`

**Scope** `api_keys.read` - **List the API key permission catalog**

Returns the permission catalog a key's scopes are chosen from: the catalog version, then each of the 19 categories in order with its label and its two scopes (<id>.read and <id>.write). Unlike GET /v1/keys (the account's keys and the scopes each one holds), it lists every scope that exists, so an agent can build or check a scopes array before POST /v1/keys or PATCH /v1/keys/:id.

*No parameters.*

**Response**

```json
{
  "catalogVersion": 2,
  "categories": [
    {
      "id": "charges",
      "label": "Charges & 3DS",
      "read": "charges.read",
      "write": "charges.write"
    },
    {
      "id": "transactions",
      "label": "Transactions",
      "read": "transactions.read",
      "write": "transactions.write"
    },
    {
      "id": "refunds",
      "label": "Refunds & disputes",
      "read": "refunds.read",
      "write": "refunds.write"
    },
    {
      "id": "kontrolpay",
      "label": "KontrolPay",
      "read": "kontrolpay.read",
      "write": "kontrolpay.write"
    },
    {
      "id": "routing",
      "label": "ATRIs, gateways & wallets",
      "read": "routing.read",
      "write": "routing.write"
    },
    {
      "id": "subscriptions",
      "label": "Subscriptions & schedules",
      "read": "subscriptions.read",
      "write": "subscriptions.write"
    },
    {
      "id": "customers",
      "label": "Customers & blacklist",
      "read": "customers.read",
      "write": "customers.write"
    },
    {
      "id": "checkouts",
      "label": "Stores & checkout builder",
      "read": "checkouts.read",
      "write": "checkouts.write"
    },
    {
      "id": "tracking",
      "label": "Pixels & tracking",
      "read": "tracking.read",
      "write": "tracking.write"
    },
    {
      "id": "recovery",
      "label": "Cart recovery",
      "read": "recovery.read",
      "write": "recovery.write"
    },
    {
      "id": "reports",
      "label": "Dashboard & reports",
      "read": "reports.read",
      "write": "reports.write"
    },
    {
      "id": "integrations",
      "label": "Integrations & messaging",
      "read": "integrations.read",
      "write": "integrations.write"
    },
    {
      "id": "api_keys",
      "label": "API keys",
      "read": "api_keys.read",
      "write": "api_keys.write"
    },
    {
      "id": "users",
      "label": "Users & access",
      "read": "users.read",
      "write": "users.write"
    },
    {
      "id": "settings",
      "label": "Account settings",
      "read": "settings.read",
      "write": "settings.write"
    },
    {
      "id": "billing",
      "label": "Kontrol subscription & agreements",
      "read": "billing.read",
      "write": "billing.write"
    },
    {
      "id": "operations",
      "label": "Logs & operations",
      "read": "operations.read",
      "write": "operations.write"
    },
    {
      "id": "monitoring",
      "label": "Uptime monitoring",
      "read": "monitoring.read",
      "write": "monitoring.write"
    },
    {
      "id": "affiliates",
      "label": "Affiliates",
      "read": "affiliates.read",
      "write": "affiliates.write"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `catalogVersion` | integer | The catalog version keys are stamped with when created or when their scopes are saved (scope_catalog in GET /v1/keys). |
| `categories` | object[] | Every permission category, in the order of the dashboard picker. |
| `categories[].id` | string | The category id (charges, transactions, refunds...). |
| `categories[].label` | string | The label shown in Settings > API keys. |
| `categories[].read` | string | The read scope of the category: GET routes and reports. |
| `categories[].write` | string | The write scope: creates, updates, deletes, actions, and the reads that hand out a stored secret or a card in clear. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"api_keys.read"} when the key's scopes lack api_keys.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"api"} when the plan lacks the api module; {"error":"Banned","message":"..."} when the account owner is banned.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- A key holding X.write does not hold X.read: list both when a key must read and write a category.
- A key created with no scopes (scopes null) has full access to its account; an empty array has none.

#### Search and entity summaries

The global search of the dashboard and the one-call summaries of a product or a storefront that the entity windows open. They read every category, so a restricted key needs every read scope.

##### `GET /v1/entities/product`

**Scope** `*.read` - **Summarise a sold product**

Summary of one sold product (matched by basket slug, else by name, optionally on one store) over a window: straight sales (sale and recovery, live and completed), approvals, approved revenue shared pro rata over each order basket, average charged price per unit, first and last sale, active subscriptions on its orders, and the top 10 stores it sold on. Every figure equals the GET /v1/transactions list opened with productSlug (or product), storefront, source=sale,recovery, population=live, status=completed and the same window.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `slug` | string (0-200, trimmed) | no | Basket product slug, exact and case-sensitive. slug or name is required; slug wins when both are sent. |
| `name` | string (0-200, trimmed) | no | Basket product name (name, else slug, else product ref), exact and case-sensitive. Used when slug is absent. |
| `host` | string (0-200, trimmed) | no | Restrict to one store host (lower-cased), as the storefront filter of GET /v1/transactions reads it. |
| `days` | integer (1-365); default `30` | no | Rolling window in days (created_at >= now - days). Ignored when both from and to are sent. |
| `from` | string (ISO 8601 datetime with Z) | no | Window start, inclusive. Used only together with to; then replaces days. |
| `to` | string (ISO 8601 datetime with Z) | no | Window end, inclusive. Used only together with from. |

**Response**

```json
{
  "product": {
    "slug": "example-hoodie",
    "name": "Example Hoodie",
    "host": null,
    "url": "https://shop.example.com/products/example-hoodie"
  },
  "days": 30,
  "sales": 412,
  "approved": 361,
  "revenue_cents": 2163390,
  "revenue_currencies": [
    "USD"
  ],
  "avg_cents": 5490,
  "first_at": "2026-10-26T00:14:02.000Z",
  "last_at": "2026-11-24T09:41:10.000Z",
  "active_subs": 57,
  "stores": [
    {
      "host": "shop.example.com",
      "url": "https://shop.example.com/products/example-hoodie",
      "sales": 300,
      "approved": 266,
      "revenue_cents": 1596000,
      "revenue_currencies": [
        "USD"
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `product` | object | {slug, name, host, url}: resolved slug/name from the rows (else the query values), host echo, url = the product page (max(transaction_products.url) over the window; null when no sale carried one) - shown in the product modal, never as a table column. |
| `days` | integer | Window used. |
| `sales` | integer | v3.9.9 - distinct STRAIGHT sales (not rebillSql) in the approval rate's base (live and completed) whose ORDER's basket (the account's lines) names the product - by slug, else by the list's product name chain (name, slug, ref) - on the store bucket when `host` is given. = the list count of the modal's "Transactions" link. |
| `approved` | integer | Of which approved. |
| `revenue_cents` | integer | v3.9.9 (D5) - the CHARGED amount of the approved sales x the product's share of its order's basket (by price; a basket without prices by its lines' count). It was sum  line x quantity - the line total already IS price x quantity (migration 075), so a multi-unit line counted several times its total (+7 % ... +84 % on the top products). |
| `avg_cents` | integer | v3.9.9 - revenue_cents / the units sold (sum  quantity of the product's lines on the approved sales): the average charged per unit; 0 without a unit. It was the average LINE total. |
| `first_at / last_at` | string\|null | Oldest / newest matching sale in the window. |
| `active_subs` | integer | Active rebill_subs whose order_id is one of these sales. |
| `stores` | array | Top 10 store buckets (the list's store expression - the `storefront` value) by sales: {host, sales, approved, revenue_cents (pro-rata, as above), url} - url = the product page on that store. |

**Errors**

- `400` `{"error":"slug or name required"}` for any query validation failure (slug and name both missing, days out of 1-365, from / to not an ISO datetime, a value over 200 characters).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key has explicit scopes and does not hold EVERY `<category>.read` scope (this cross-category summary needs them all; requiredScope then names operations.read); `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Entity summaries are busy. Please retry shortly."}` when the bounded summary queue is full or the read passes its 25-second budget.

**Gotchas**

- There is no search here: find the exact slug or name first (GET /v1/search or the transaction facets).
- Subscription charges are not sales here, and refunds are not subtracted from revenue_cents.
- revenue_currencies is the currency set of the approved rows behind revenue_cents and avg_cents: [] = nothing approved, one code = that unit, two codes = mixed currencies (the cents add unlike units; never label them one currency).
- Send from and to (the day bounds of your timezone) to match a GET /v1/transactions window exactly; days alone is a rolling window.

##### `GET /v1/entities/storefront`

**Scope** `*.read` - **Summarise a storefront**

Summary of one store host over a window: live completed sales of the store bucket (subscription charges counted on their sale's store), approvals, approved revenue, first and last sale, a representative storefront URL, active subscriptions on its orders, and its top 10 products by straight sales.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `host` | string (1-200, trimmed) | **yes** | Store host. A scheme, a leading www. or pay., and any path are stripped; the host, www.<host> and pay.<host> all match. |
| `days` | integer (1-365); default `30` | no | Rolling window in days (created_at >= now - days). Ignored when both from and to are sent. |
| `from` | string (ISO 8601 datetime with Z) | no | Window start, inclusive. Used only together with to; then replaces days. |
| `to` | string (ISO 8601 datetime with Z) | no | Window end, inclusive. Used only together with from. |

**Response**

```json
{
  "host": "shop.example.com",
  "url": "https://shop.example.com/checkout",
  "days": 30,
  "sales": 1820,
  "approved": 1311,
  "revenue_cents": 6553689,
  "revenue_currencies": [
    "USD"
  ],
  "first_at": "2026-10-26T00:14:02.000Z",
  "last_at": "2026-11-24T09:58:44.000Z",
  "active_subs": 204,
  "products": [
    {
      "slug": "example-hoodie",
      "name": "Example Hoodie",
      "sales": 300,
      "approved": 266,
      "revenue_currencies": [
        "USD"
      ],
      "revenue_cents": 1596000
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `host` | string | Normalised host. |
| `url` | string\|null | max(storefront_url) among matching sales (a representative URL). |
| `sales / approved` | integer | Sale transactions on the host in the approval rate's base (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out), and the approved ones - approved / sales is THE approval rate (v3.9 section 1). |
| `revenue_cents` | integer | sum  transactions.amount_cents of APPROVED sales (whole transaction amount), cents. |
| `first_at / last_at` | string\|null | Window bounds actually observed. |
| `active_subs` | integer | Active rebill_subs attached to these sales. |
| `products` | array | Top 10 by sales: {slug, name, sales, approved, revenue_cents} - v3.9.9 (D5): the store's STRAIGHT sales whose order's basket holds the slug (`productSlug=<slug>&storefront=<host,www.host,pay.host>&status=completed&source=sale,recovery` opens them), revenue_cents = the charged amount x the slug's share of the basket (it was sum  line x quantity). |

**Errors**

- `400` `{"error":"host required"}` for any query validation failure (host missing or empty, days out of 1-365, from / to not an ISO datetime).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key has explicit scopes and does not hold EVERY `<category>.read` scope (this cross-category summary needs them all; requiredScope then names operations.read); `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Entity summaries are busy. Please retry shortly."}` when the bounded summary queue is full or the read passes its 25-second budget.

**Gotchas**

- revenue_cents at the top counts every approved charge of the store (subscription charges included); products[] counts straight sales only (no rebill, no Friendlies), pro rata over the basket.
- Sales without basket lines count in the totals but produce no product row.
- A subdomain other than www or pay is matched literally.
- revenue_currencies: see GET /v1/entities/product.

##### `GET /v1/search`

**Scope** `*.read` - **Global search (command palette)**

One bounded lookup behind the dashboard command palette: up to 8 hits per group for a term across customers (from the last 365 days of the transaction list), gateways (MIDs), ATRIs, subscription products, customer subscriptions and storefronts, each scoped to the account like the page it links to.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string (2..80 chars, trimmed) | **yes** | Search term. Trimmed, then 2 to 80 characters. % and _ are matched literally. Customers match on e-mail, first name, last name or "first last" (contains), order id (prefix), and phone (contains) only when the term holds a digit; gateways, ATRIs, products match on name (contains); subscriptions on e-mail (contains) or order id (prefix); storefronts on host or name (contains). |

**Response**

```json
{
  "customers": [
    {
      "email": "jane.doe@example.com",
      "name": "Jane Doe",
      "orderId": "ORD-100245",
      "lastSeen": "2026-11-19T11:02:40.018Z"
    }
  ],
  "gateways": [
    {
      "id": "5d6e7f80-91a2-4b3c-8d4e-5f6a7b8c9d0e",
      "name": "NMI US 03"
    }
  ],
  "atris": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "name": "US Primary Pool"
    }
  ],
  "subscriptions": [
    {
      "id": "aa11bb22-cc33-4d44-8e55-ff6677889900",
      "name": "Monthly Club"
    }
  ],
  "subs": [
    {
      "id": "bb22cc33-dd44-4e55-9f66-001122334455",
      "email": "jane.doe@example.com",
      "status": "active",
      "subscription": "Monthly Club"
    }
  ],
  "storefronts": [
    {
      "host": "shop.example.com",
      "name": "Example Shop"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `customers` | object[] | Up to 8, one per customer (deduplicated on lower(email), else order id), newest sale first, from the last 365 days of the transaction list population: {email, name (first + last, or null), orderId (most recent), lastSeen (ISO)}. |
| `gateways` | object[] | Up to 8 of the account's gateways (MIDs) {id, name}, by name. |
| `atris` | object[] | Up to 8 of the account's ATRIs {id, name}, by name. |
| `subscriptions` | object[] | Up to 8 subscription products {id, name} that are not deleted, by name. |
| `subs` | object[] | Up to 8 customer subscriptions {id, email, status, subscription (product name)}, most recently updated first. |
| `storefronts` | object[] | Up to 8 storefronts {host, name} visible to the account (its own and those billed under its MIDs), by host. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten>}: q missing, shorter than 2 or longer than 80 characters after trimming.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). A key with explicit scopes that lacks any category .read scope is refused here (the 403 body still names requiredScope operations.read).
- `503` Authentication scope is temporarily unavailable. Search is temporarily unavailable. Please try again. (the read failed, timed out after its 5 s budget, or the small search queue was full)

**Gotchas**

- Every group is capped at 8 with no paging: refine the term.
- Customer hits come only from transactions in the account scope and the last 365 days; older customers are not found here (use /v1/transactions or /v1/customers).
- Phone matching applies only when the term contains a digit.
- A 503 is safe to retry after a short pause; a superseded request (client disconnect) is cancelled server side.

#### Errors, limits and service status

Error shapes, rate limits, idempotency and paging are explained in Part 1 of llm.md. The endpoints here say which background operations are available now, whether the API answers, how your API traffic performs, and serve the OpenAPI document.

##### `GET /v1/health`

**Scope** `operations.read` - **Check that the API and its database answer**

Checks that the API and its database answer (a liveness probe for monitoring); GET /v1/perf reports your API traffic performance. Database reachability probe through the account API: 200 {status:"ok",time} when the API process answers a `select 1` on its database, 503 {status:"degraded",db:"unavailable"} when it cannot. Read only. Internal timing and mirror diagnostics are added for platform operators only; account callers never receive them.

*No parameters.*

**Response**

```json
{
  "status": "ok",
  "time": "2026-11-24T12:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `status` | string | "ok" on 200, "degraded" on the 503 body. |
| `time` | string | Server clock at response time, ISO 8601 UTC. 200 only. |
| `db` | string | 503 body only: "unavailable". |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `503` {"status":"degraded","db":"unavailable"}: the database probe failed. The cause is not returned. A different 503 body, {"error":"Server busy, retry"} with retry-after: 1, is the server shedding load, not a database problem.

**Gotchas**

- The 503 body has neither time nor error: branch on `status`.
- This is not the liveness probe of the platform: GET /healthz (no credential, never rate limited) is. This route needs a credential and counts against the 300 per minute limit; do not poll it aggressively.
- A 200 proves only that the API process reaches its database. It says nothing about gateways, wallets or background jobs.
- No parameter is read; a query string is ignored.

##### `GET /v1/openapi.json`

**Scope** `operations.read` - **Get the OpenAPI document**

Returns the OpenAPI 3.1 document of the API as JSON: the generated inventory of every registered route (about 870 paths) with the hand-written request and response schemas merged into the payment operations (POST /v1/charge, POST /v1/convesio, the 3-D Secure session routes, POST /v1/checkout/pre-auth). Only `servers` is computed per request. Nothing is read from the database and nothing changes.

*No parameters.*

**Response**

```json
{
  "openapi": "3.1.0",
  "info": {
    "title": "Kontrol API",
    "version": "5.4.0-beta.1",
    "description": "Complete registered API route reference. ..."
  },
  "servers": [
    {
      "url": "https://api.kontrolcheckout.com",
      "description": "Live"
    }
  ],
  "tags": [
    {
      "name": "Charging"
    },
    {
      "name": "Transactions"
    }
  ],
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer"
      },
      "apiKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Api-Key"
      }
    },
    "schemas": {
      "Order": {
        "type": "object",
        "required": [
          "orderId",
          "crm",
          "amount"
        ]
      }
    }
  },
  "paths": {
    "/v1/charge": {
      "post": {
        "operationId": "post-v1-charge",
        "tags": [
          "Charging"
        ],
        "summary": "Charge orders"
      }
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `openapi` | string | Always "3.1.0". |
| `info` | object | title "Kontrol API", the version of the generated inventory and a short description. |
| `servers` | object[] | Exactly one entry, computed per request: url is the configured public API URL, else protocol plus Host header of the request; description is "Live" in production, else "Local". |
| `tags` | object[] | One tag per group of this reference (Charging, Transactions, ...). |
| `components` | object | securitySchemes (bearer, X-Api-Key and the other headers) and the hand-written payment schemas (Order, ChargeRequest, ...). |
| `paths` | object | Every registered route with its operations (operationId, tags, summary, description, parameters, responses). Path parameters use the {name} form. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The document is several megabytes. Cache it: the same base URL always returns identical bytes.
- Paths keep their registered names, so account routes appear under their internal prefix there; call them at the /v1 addresses this reference documents.
- When the public API URL is not configured, servers[0].url is built from the Host header of the request: do not treat it as a verified origin.
- No parameter is read; a query string is ignored. content-type is application/json.

##### `GET /v1/operation-capabilities`

**Scope** `operations.read` - **Read background operation availability**

Says whether the background operations of the account API can be admitted right now: subscription bulk edits, report jobs, customer bulk jobs and transaction bulk jobs, plus the report kinds a report job accepts (POST /v1/metrics/jobs). Read it before starting one of those jobs. It first checks that the storage of every background operation exists, then reads whether the deployment runs background workers. Read only, answered with Cache-Control: no-store.

*No parameters.*

**Response**

```json
{
  "transactionBulk": true,
  "customerBulk": true,
  "bulkEdits": true,
  "reports": true,
  "reportKinds": [
    "main",
    "financial",
    "checkouts",
    "schedule-selection",
    "traffic",
    "bins",
    "products",
    "segments",
    "three-ds",
    "product-matching"
  ]
}
```

| response field | type | description |
|---|---|---|
| `bulkEdits` | boolean | Subscription bulk edits can be admitted. |
| `reports` | boolean | Report jobs can be admitted. |
| `reportKinds` | string[] | The kinds a report job accepts now, in this order: main, financial, checkouts, schedule-selection, traffic, bins, products, segments, three-ds, product-matching. [] when background workers are off. |
| `customerBulk` | boolean | Customer bulk jobs can be admitted. |
| `transactionBulk` | boolean | Transaction bulk jobs can be admitted. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `503` {"error":"Required storage for <operation> is unavailable. Complete the current database migrations.","requestId":"<id>"} (Retry-After: 1): a required table of the background operations is missing (the deployment is incomplete; <operation> is one of bulk edits, reports, extended reports, integration reports, schedule reports, customer bulk, transaction bulk). Retry later; never replay a job through another endpoint.

**Gotchas**

- When the deployment runs no background workers the answer is still 200, with every flag false and reportKinds []: no job can be admitted and there is no synchronous fallback.
- A successful storage check is cached for 10 minutes per API process; a failed one is not cached, so a repaired deployment is seen on the next call.
- Read it again before retrying an uncertain job start: a false here is never permission to replay a write elsewhere.
- No parameter is read; a query string is ignored.

##### `GET /v1/perf`

**Scope** `operations.read` - **Read your API traffic performance (latency, errors, recent minutes)**

Reads your account's API traffic performance (latency, errors, recent minutes); GET /v1/health only checks that the API and its database answer. Read the API Health page for the account: totals, latency percentiles, outcomes, HTTP status counts and a time series of its POST /v1/charge requests over a trailing window, plus per-MID gateway latency over the MIDs the account owns. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `minutes` | integer, 5..1440; default `60` | no | Trailing window in minutes (created_at >= now() - minutes). Coerced from the query string; out-of-range or non-integer values are a 400, not clamped. Also sets the series bucket: 60-second buckets up to 180 minutes, 3600-second buckets above. |
| `runtimePageSize` | integer, 1..2000 | no | Page size for the raw runtime samples. Only a platform super admin receives those samples, but every caller may send it: without it, a window holding more than 50,000 runtime samples answers 422 even though an account caller never sees them. |

**Response**

```json
{
  "windowMinutes": 60,
  "bucketSec": 60,
  "totals": {
    "requests": 1843,
    "errors": 3,
    "errorRate": 0.0016278
  },
  "latency": {
    "p50": 412,
    "p95": 1180,
    "p99": 2740,
    "max": 9982
  },
  "outcomes": [
    {
      "outcome": "accepted",
      "count": 1790
    },
    {
      "outcome": "invalid_body",
      "count": 50
    },
    {
      "outcome": "error",
      "count": 3
    }
  ],
  "statusCodes": [
    {
      "status": 200,
      "count": 1790
    },
    {
      "status": 400,
      "count": 50
    },
    {
      "status": 500,
      "count": 3
    }
  ],
  "series": [
    {
      "bucket": "2026-11-24T12:00:00.000Z",
      "requests": 31,
      "errors": 0,
      "p95": 1104
    },
    {
      "bucket": "2026-11-24T12:01:00.000Z",
      "requests": 28,
      "errors": 1,
      "p95": 1362
    }
  ],
  "perMid": [
    {
      "name": "Example MID 01",
      "attempts": 1248,
      "p95": 940,
      "timeouts": 6
    },
    {
      "name": "Example MID 02",
      "attempts": 590,
      "p95": 1320,
      "timeouts": 2
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `windowMinutes` | integer | Echo of the effective window actually used (your `minutes`, or 60 when omitted). Use it to confirm the default rather than assuming. |
| `bucketSec` | integer | Width of each `series` bucket in SECONDS. 60 when minutes <= 180, 3600 otherwise. Derived server-side, not requestable. |
| `maxInflight` | integer | Human super_admin outside impersonation only; omitted for all other callers. Back-pressure ceiling of concurrent in-flight charge requests PER WORKER. This is a static server config value (env MAX_INFLIGHT_REQUESTS, default 200), NOT a measurement - it never changes between calls. Meant as the denominator for the inflight gauge. |
| `totals.requests` | integer | Count of the account's POST /v1/charge request log rows in the window (all statuses). |
| `totals.errors` | integer | Count of charge_request_logs rows with status_code >= 500 ONLY. 4xx responses and declined charges are not counted as errors. |
| `totals.errorRate` | number | errors / requests as a 0..1 RATIO (not a percentage). Exactly 0 when requests is 0 - never null and never NaN. |
| `totals.shed` | integer | Human super_admin outside impersonation only; omitted for all other callers. Sum of the `shed` counter across every perf_samples row in the window (requests rejected by the back-pressure guard). Comes from perf_samples, a different table than requests/errors. |
| `latency.p50` | integer | Median request duration in MILLISECONDS, via percentile_disc (an actually-observed value, not interpolated). 0 when there is no data. |
| `latency.p95` | integer | 95th percentile request duration in milliseconds. 0 when there is no data. |
| `latency.p99` | integer | 99th percentile request duration in milliseconds. 0 when there is no data. |
| `latency.max` | integer | Slowest request duration in milliseconds in the window. 0 when there is no data. |
| `outcomes` | object[] | `[{ outcome, count }]` from charge_request_logs, ordered by count descending. outcome is the charge log classification: accepted (processed, declines included), auth_failed, invalid_body or error. |
| `statusCodes` | object[] | `[{ status, count }]`: HTTP status returned by POST /v1/charge, ordered by status ascending. |
| `series` | object[] | Time series, one entry per non-empty bucket: `{ bucket: ISO-8601 timestamp string, requests: integer, errors: integer (status_code >= 500), p95: integer ms }`, ordered by bucket ascending. |
| `runtime` | object[] | Human super_admin outside impersonation only; omitted for all other callers. Raw infrastructure samples, chronological within each page. Fields: created_at (UTC ISO), pid, inflight, shed, requests, pool_total, pool_idle, pool_waiting, loop_lag_p50_ms, loop_lag_max_ms, rss_mb. With runtimePageSize, only the newest page is returned; follow runtimePage.next for older samples. Without pagination, more than 50,000 samples are rejected explicitly. |
| `workers` | object[] | Human super_admin outside impersonation only; omitted for all other callers. Latest sample per pid from the last 2 MINUTES only (distinct on pid) - i.e. the workers currently alive. Fields: pid, created_at, inflight, pool_total, pool_idle, pool_waiting, loop_lag_p50_ms, loop_lag_max_ms, rss_mb. Deliberately has NO `shed` and NO `requests`, unlike the near-identical `runtime` rows. Order is by pid (from the distinct-on), not by load. |
| `perMid` | object[] | Per-MID gateway latency from transaction_attempts over the MIDs the account owns, skipped attempts excluded: `[{ name, attempts, p95, timeouts }]`, ordered by attempts descending. name is the attempt's account name (null rows collapse into one entry); p95 in ms; timeouts counts outcome 'timeout'. |
| `runtimePage` | object (optional) | Human super_admin outside impersonation only; omitted for all other callers. Only in bounded mode when runtimePageSize is requested: {total,next,from,maxId}. total covers the full window; next is an opaque older-page cursor or null; from/maxId freeze traversal bounds, not a retained DB snapshot. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: minutes outside 5..1440, runtimePageSize outside 1..2000, or a non-integer value.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `No account` when the caller has no resolved account.
- `422` `Runtime history is too large for one response. Request runtimePageSize and follow runtimePage.next.` (more than 50,000 runtime samples in the window and no runtimePageSize).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). `API Health is temporarily busy. Retry shortly.` when the dedicated two-connection read pool is saturated or the 5 s read budget is exceeded.

**Gotchas**

- Only POST /v1/charge requests are logged in charge_request_logs: requests to every other route are not counted here.
- totals.errors and series[].errors count status_code >= 500 only. Declines answer 200 and are not errors; read outcomes and perMid.timeouts for gateway trouble.
- bucketSec flips at 180 minutes (60 s up to 180, 3600 s above). Chart from the returned bucketSec, never from minutes.
- Latency percentiles use percentile_disc over duration_ms (observed values, not interpolated); rows without a duration still count in totals.requests.
- Two sources: request totals, latency, outcomes, statusCodes and series come from charge_request_logs (rows of the account's keys); perMid comes from transaction_attempts on owned MIDs. One request can make several attempts, so the totals do not reconcile.
- An empty window is a 200 with zero totals and empty arrays, not a 404.
- totals.errorRate is a 0..1 ratio (0.0016 = 0.16%), 0 when there are no requests.
- Unknown query fields are ignored; only minutes and runtimePageSize are read.
- The infrastructure fields (maxInflight, totals.shed, runtime, workers, runtimePage) are returned only to a platform super admin outside impersonation; never to an account caller. GET /v1/perf/runtime pages older samples for that operator only.

### Overview

The Overview menu of the dashboard: the Dashboard page and the Transactions page.

#### Dashboard

The widgets of the Dashboard page: alerts, the filtered chart series and the ATRI activity. The KPI payload of the page is GET /v1/metrics (Reports > Dashboard metrics); its last orders are GET /v1/transactions.

The Dashboard page reads these endpoints and computes the rest in the browser. To reproduce it:

- KPI cards, money ledger and breakdown tables: `GET /v1/metrics` (Reports > Dashboard metrics) with the page's range, `tz` and `side`; for a long range use `POST /v1/metrics/jobs` with `kind: "main"`. Products and flows blocks: `GET /v1/metrics/products`, `GET /v1/metrics/flows`. Last orders: `GET /v1/transactions?limit=20&count=0`, polled every 30 seconds (there is no push feed).
- Total row of every table: sums of the counts, rates recomputed from the summed components, never averaged. Approval rate = sum(approved) / sum(completed). AR per attempt = sum(arAttempts x attempts) / sum(attempts). Cap usage = sum(usedCents) / sum(monthlyCapCents) over the MIDs only; one uncapped MID makes the total uncapped.
- "(no gateway)" row: the `noGateway` object of `GET /v1/metrics`. Idle MIDs (no charge in the range) are hidden in the browser.
- "vs Yesterday": two reads of `GET /v1/metrics/series`, today and yesterday. Change in % = (today - yesterday) / yesterday; an approval rate changes in points (today rate - yesterday rate). For the hour in progress, yesterday is cut at the same minute. Hours with no data are filled with zero.
- "Net after ad spend" = net volume - Pilot ad spend of the range (ad spend from `GET /v1/metrics`, USD); "Net after fixed costs" = that line - the senders' monthly plans prorated over the range. Both appear only while the Pilot integration is active.
- Store table, Pilot reconciling row "(ad spend on no store)" = Pilot spend of the range - the spend matched to a store.
- Export (CSV / PDF of every visible block) is built in the browser from these responses.

##### `GET /v1/metrics/alerts`

**Scope** `reports.read` - **Get dashboard alerts**

Current anomalies for the dashboard alerts panel, with the account's own thresholds (account settings) and the rules of its Telegram monitor: ambiguous timeouts to review, MID gateway-authentication failures and monthly-cap usage over the requested window, plus the approval-rate watch (sales and rebill channels against the account's own 7-day baseline, collapsed MIDs, charges that reached no MID, gateway technical errors) over the trailing hours. Returns the window length and a flat list of alerts.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `hours` | integer, 1..8760; default `24` | no | Trailing window, used when `from` and `to` are not both sent. |
| `from` | string, ISO-8601 UTC datetime ending in Z | no | Window start; honoured only together with `to` (one bound alone falls back to `hours`). A bare day is a 400. |
| `to` | string, ISO-8601 UTC datetime ending in Z | no | Window end; honoured only together with `from`. |
| `atriView` | string CSV of ATRI uuids, max 4000 | no | Restricts every number feeding the timeout, auth-failure and cap alerts to these ATRIs, intersected with the caller's ATRI grants (an empty intersection falls back to the full allowed set). Non-uuid entries are dropped. |
| `atri` | string CSV of ATRI uuids, max 4000 | no | Dimension filter (ATRI reached). Applied only when from and to are both sent, and only to the per-MID data behind the mid-cap alerts. |
| `source` | string CSV, max 100 | no | Dimension filter: sale, rebill, recovery, straight, subscription. Applied only when from and to are both sent, and only to the per-MID data. |
| `bucket` | enum: hour \| day | no | Accepted and validated; no effect on this response. |
| `tz` | string, max 64 | no | Clock of the `hour` filter; no other effect here. |
| `side` | enum: straight \| subscription \| friendlies \| both | no | Accepted, validated and ignored: the alerts stay account-wide whatever the dashboard tab. |
| `status` | string, max 200 | no | Charge status CSV (approved, declined, error, unknown, pending, duplicate, aliases failed and completed, flags chargeback, rdr, ethoca). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `accountId` | string, max 4000 | no | Final MID ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `gatewayType` | string, max 100 | no | Gateway type of the final MID (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `category` | string, max 4000 | no | MID category ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `pass` | string, max 40 | no | initial / cascade. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `country` | string, max 2000 | no | Billing country (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `storefront` | string, max 4000 | no | Store host bucket (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `traffic` | string, max 2000 | no | Traffic source bucket (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `brand` | string, max 100 | no | Card brand bucket (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `paysource` | string, max 100 | no | Wallet pay source, for example APPLEPAY (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `threeDs` | string, max 200 | no | 3DS outcome (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `productSlug` | string, max 4000 | no | Basket product slug (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `cycle` | string, max 200 | no | Charge cycle (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `subscription` | string, max 4000 | no | Subscription product ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `credentialMode` | string, max 20 | no | mit / cit. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `declineCategory` | string, max 1000 | no | Decline-engine category (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `declineSeverity` | string, max 40 | no | soft / hard. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `processor` | string, max 4000 | no | Processor ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `acquiringBank` | string, max 4000 | no | Acquiring bank ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `company` | string, max 4000 | no | Company ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `hour` | string, max 200 | no | Hours 0-23 in tz (CSV); needs a valid tz or the request is a 400 `hour needs a valid tz`. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `ipType` | string, max 40 | no | IPv4 / IPv6. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `bin` | string, max 4000 | no | 6-digit BINs or a wallet label (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `funding` | string, max 200 | no | Funding type (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `browser` | string, max 200 | no | Browser (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `gatewayMcc` | string, max 1000 | no | Final MID MCC (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `gatewayBin` | string, max 1000 | no | Final MID acquirer BIN (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `pricePoint` | string, max 400 | no | Price bucket labels (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `walletProvider` | string, max 4000 | no | Wallet provider ids (CSV). Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |
| `method` | string, max 20 | no | card / wallet. Dimension filter, applied only when from and to are both sent and only to the per-MID data behind the mid-cap alerts. |

**Response**

```json
{
  "windowHours": 24,
  "alerts": [
    {
      "key": "timeouts",
      "severity": "warning",
      "title": "3 ambiguous timeout(s) need review",
      "detail": "Timeouts are not auto-retried; confirm the customer was not charged before re-attempting."
    },
    {
      "key": "mid-auth:11111111-1111-4111-8111-111111111111",
      "severity": "critical",
      "title": "Example MID 03: gateway authentication failed",
      "detail": "7 auth failure(s) in last 24h - the login / password / security key for this MID is wrong. Fix the gateway credentials."
    },
    {
      "key": "mid-cap:22222222-2222-4222-8222-222222222222",
      "severity": "warning",
      "title": "Example MID 01: 83% of monthly cap used",
      "detail": "$41,500 / $50,000 this month."
    },
    {
      "key": "ar:mids",
      "severity": "warning",
      "title": "1 MID(s) below 50% of their own 7-day rate",
      "detail": "Example MID 02 31.0% vs 68.0% (first pass). Each figure is that MID against ITSELF over the same channel and retry cohort, so a low rebill rate is not the cause."
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `windowHours` | integer | Hours of the window the timeout / auth / cap alerts were computed over: round((to - from) / 3600000), at least 1, with a range; `hours` otherwise. |
| `alerts` | object[] | Firing alerts in generation order (timeouts, mid-auth, mid-cap, then the approval-rate watch), not sorted by severity. Empty array = nothing detected. |
| `alerts[].key` | string | Stable id (Telegram de-duplication): timeouts, mid-auth:<midId>, mid-cap:<midId>, ar:straight, ar:rebill, ar:mids, ar:no-route, ar:gateway-errors. |
| `alerts[].severity` | enum: critical \| warning | mid-auth, ar:straight and ar:rebill are critical; mid-cap is critical at 95% of the cap or more, warning from the account cap-warning percentage; timeouts, ar:mids, ar:no-route and ar:gateway-errors are warnings. |
| `alerts[].title` | string | Pre-formatted headline (rates already in percent). Display only. |
| `alerts[].detail` | string | Pre-formatted explanation with sample sizes; money rendered as whole dollars. Display only; read GET /v1/metrics for numbers. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: hours outside 1..8760, from / to not a full ISO-8601 UTC datetime (for example 2026-11-01T00:00:00Z; a bare day or an offset is refused), bucket not hour | day, side outside straight | subscription | friendlies | both, a value over its max length, or `hour` without a valid tz (details.fieldErrors.tz = hour needs a valid tz). The gate also refuses a malformed or foreign `affiliate` / `flow` filter.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). `Alerts are busy. Retry shortly.` when the read passes its 5-second deadline.

**Gotchas**

- The approval-rate rules are relative, not absolute floors: a channel (sales, first rebill pass) fires when its rate falls below the account's AR floor percentage OF ITS OWN 7-day baseline (with at least 50 charges in the window and 200 in the baseline); a MID fires below the MID floor percentage of its own baseline (30 / 100 charges). Thresholds come from the account settings, not from the request.
- The approval-rate watch always reads the trailing max(windowHours, 3) hours up to now, even when from / to name a past range; it is best effort (a failure drops those alerts, the others still answer).
- from and to only take effect together; one bound alone is ignored and the trailing `hours` window is used.
- The legacy dimension filters (status, atri, accountId, ...) apply only when from and to are both sent, and only to the per-MID data, so they can change mid-cap alerts but never timeouts or mid-auth.
- `atri` (a dimension filter) and `atriView` (the whole computation) differ; non-uuid ids in them are dropped silently.
- Totals use LIVE transactions only (no test card, no CSV import, no 3DS park); a charge refused before any MID is not a transaction.
- An account with no keys and no wallet providers gets an empty alerts array, indistinguishable from a healthy account.
- Alert title / detail are display strings; do not parse numbers out of them.
- Unknown query parameters are ignored (this frozen schema is not strict).

##### `GET /v1/metrics/atri-activity`

**Scope** `reports.read` - **ATRI Activity**

Per-ATRI (routing pool) freshness strip: for every ATRI the caller may see, when it last took any real attempt, when it last approved an actual sale, when it last saw a decline, and how many distinct orders it handled in the trailing 24 hours. Powers the 'last order N min ago' health indicators so a stalled or non-converting pool is obvious at a glance.

*No parameters.*

**Response**

```json
{
  "atris": [
    {
      "id": "3f9b1c02-77a4-4a1e-9f22-5d0c8ab41e77",
      "name": "US Classic Pool",
      "trip_type": "cascade",
      "active": true,
      "last_activity_at": "2026-08-26T14:31:07.482Z",
      "last_order_at": "2026-08-26T12:04:55.119Z",
      "last_decline_at": "2026-08-26T14:31:07.482Z",
      "orders_24h": 418
    },
    { "id": "…", "name": "EU Rebill Pool", "trip_type": "classic", "active": false, "last_activity_at": null, "last_order_at": null, "last_decline_at": null, "orders_24h": 0 }
  ]
}
```

| response field | type | description |
|---|---|---|
| `atris` | array<object> | One row per visible ATRI, ordered by trip_type then name (cascade pools before classic ones). No pagination, no cap. |
| `atris[].id` | string (uuid) | trips.id - the ATRI / routing-pool id. Use this value for atriView / atri filters on the other metrics endpoints. |
| `atris[].name` | string | trips.name. |
| `atris[].trip_type` | string | classic \| cascade (snake_case field). A cascade pool only appears on attempts, never as an order's own ATRI. |
| `atris[].active` | boolean | trips.active - whether the pool is enabled for routing. An inactive pool is still returned (with its historical timestamps). |
| `atris[].last_activity_at` | string (ISO-8601 timestamp, UTC) \| null | max(transaction_attempts.created_at) over attempts with outcome <> 'skipped' whose transaction is not a Friendlies sale - i.e. the last time the pool was really tried, approved or not. Drives the 'is it still receiving traffic' health dot. null when the pool has never been tried by the caller's traffic. |
| `atris[].last_order_at` | string (ISO-8601 timestamp, UTC) \| null | max(created_at) over attempts with outcome = 'approved' ONLY, Friendlies sales excluded - the last actual SALE. null when the pool has never approved anything in the caller's scope. |
| `atris[].last_decline_at` | string (ISO-8601 timestamp, UTC) \| null | max(created_at) over attempts with outcome in ('declined','error','timeout'), Friendlies sales excluded - v3.9 section 1 ATTEMPT_DECLINED_SQL: gateway errors AND timeouts are declines here (one bounded index probe per outcome, folded by greatest()). null when there has been no refusal. |
| `atris[].orders_24h` | integer | count(distinct transaction_id) over non-skipped attempts on this pool in the last 24 hours, Friendlies sales excluded (now() - interval '24 hours', evaluated in the database). Orders, not attempts: a cascaded order retried three times on the same pool counts once. Cast ::int so it is a JSON number, not a bigint string. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- This route takes NO parameters at all - it never touches req.query. hours, from, to, atriView, bucket, tz and everything else are silently ignored; there is no 400 path. The timestamps are all-time and orders_24h is a fixed rolling 24 hours from now(), never the dashboard's selected window.
- The three timestamps mean different things and must not be conflated: last_activity_at = any non-skipped attempt, last_order_at = APPROVED only, last_decline_at = declined, error OR timeout. 'order 2h ago, decline 30s ago' is the intended reading - busy pool that has stopped converting.
- Attempts with outcome = 'skipped' (routing candidates that were never actually tried) are excluded from all three timestamps AND from orders_24h.
- Scoping is ALWAYS applied, even for admin and super_admin: clientScope() always returns an object (never null), so both the visibility filter and the attempt-count filter are on for every caller. An account with zero api keys, zero wallet providers and no owned trips gets {"atris": []} - an empty list, not an error.
- A row is visible when the ATRI belongs to the account, is the default ATRI of one of its API keys, or was reached by one of its attempts (charging key or account) or by a key-charged transaction that made no attempt.
- The attempt join is scoped to the caller's own transactions, so on a shared ATRI the timestamps and orders_24h reflect only YOUR traffic - they can be far older/lower than the pool's real activity.
- The tenant scope is applied inside the LEFT JOIN's ON clause, so an ATRI you can see but have no traffic on still appears, with all three timestamps null and orders_24h = 0. Treat null as 'no data in your scope', not as 'never used'.
- The same order is counted under BOTH its classic ATRI and every cascade pool it reached, so summing orders_24h across rows exceeds your real 24h order count. Deliberate: cascade pools never show on transactions.trip_id and would otherwise be invisible.
- Field names are snake_case (trip_type, last_activity_at, last_order_at, last_decline_at, orders_24h) - unlike most other metrics endpoints, which return camelCase.
- A member's ATRI grants narrow the list further; an API key carries no ATRI grant, so it sees every ATRI of the account scope.
- No pagination, no limit, no filtering: on an account with many pools this returns every visible ATRI in a single array.
- Friendlies attempts are left out: the three timestamps and orders_24h only read attempts whose transaction is not a Friendlies sale, so a pool that only took Friendlies traffic shows null timestamps and 0 (it is still listed when visible). The lookup checks each attempt's transaction by primary key.

##### `GET /v1/metrics/series`

**Scope** `reports.read` - **Filtered Chart Series**

Time-bucketed charge counts and approved volume for the dashboard chart, narrowed to a single ATRI and/or one side (straight | subscription). Split out from GET /v1/metrics so the default unfiltered chart never pays the cost of the filtered query. v3.9.13 - the dashboard's Straight / Subscription / Both tab drives it (the chart's own Source select is gone). `source` is read with the /transactions list's clause, the caller's ATRI grants are the list's cascade-aware scope, `atri` must be a uuid (400), and every point carries `completed`. So Straight + Subscription = the unfiltered series, point by point.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `hours` | integer, 1..8760; default `24` | no | Trailing window, used to derive the start when `from` is absent (start = end - hours). |
| `from` | string, ISO-8601 UTC datetime ending in Z | no | Window start, inclusive. Works alone (end = now). A bare day or an offset form is a 400. |
| `to` | string, ISO-8601 UTC datetime ending in Z; default `now` | no | Window end, inclusive. Works alone (start = to - hours). |
| `bucket` | enum: hour \| day; default `hour` | no | Series granularity. Anything but day reads hourly buckets. |
| `tz` | string, max 64 (IANA timezone); default `account timezone` | no | Clock of the buckets and labels; from / to stay the instants sent. An invalid zone is a 400 `Invalid report timezone`. |
| `atri` | string: one ATRI uuid | no | Restrict to ONE ATRI: the order's final pool (the list's `atriFinal`). A CSV, a name or __no_atri__ is a 400 (details.fieldErrors.atri = atri must be one ATRI id (a uuid)). |
| `source` | string CSV, max 100 | no | The list's own source clause: straight (sale + recovery), subscription (rebill) or the raw buckets sale, rebill, recovery. Unrecognised values are dropped; when none survives the series is unfiltered. |
| `atriView` | string, max 4000 | no | Accepted and ignored here (use `atri`). |
| `side` | enum: straight \| subscription \| friendlies \| both | no | Accepted, validated and ignored here. |
| `status` | string, max 200 | no | Charge status CSV (approved, declined, error, unknown, pending, duplicate, aliases failed and completed, flags chargeback, rdr, ethoca). Accepted (validated for length) and ignored by this route. |
| `accountId` | string, max 4000 | no | Final MID ids (CSV). Accepted (validated for length) and ignored by this route. |
| `gatewayType` | string, max 100 | no | Gateway type of the final MID (CSV). Accepted (validated for length) and ignored by this route. |
| `category` | string, max 4000 | no | MID category ids (CSV). Accepted (validated for length) and ignored by this route. |
| `pass` | string, max 40 | no | initial / cascade. Accepted (validated for length) and ignored by this route. |
| `country` | string, max 2000 | no | Billing country (CSV). Accepted (validated for length) and ignored by this route. |
| `storefront` | string, max 4000 | no | Store host bucket (CSV). Accepted (validated for length) and ignored by this route. |
| `traffic` | string, max 2000 | no | Traffic source bucket (CSV). Accepted (validated for length) and ignored by this route. |
| `brand` | string, max 100 | no | Card brand bucket (CSV). Accepted (validated for length) and ignored by this route. |
| `paysource` | string, max 100 | no | Wallet pay source, for example APPLEPAY (CSV). Accepted (validated for length) and ignored by this route. |
| `threeDs` | string, max 200 | no | 3DS outcome (CSV). Accepted (validated for length) and ignored by this route. |
| `productSlug` | string, max 4000 | no | Basket product slug (CSV). Accepted (validated for length) and ignored by this route. |
| `cycle` | string, max 200 | no | Charge cycle (CSV). Accepted (validated for length) and ignored by this route. |
| `subscription` | string, max 4000 | no | Subscription product ids (CSV). Accepted (validated for length) and ignored by this route. |
| `credentialMode` | string, max 20 | no | mit / cit. Accepted (validated for length) and ignored by this route. |
| `declineCategory` | string, max 1000 | no | Decline-engine category (CSV). Accepted (validated for length) and ignored by this route. |
| `declineSeverity` | string, max 40 | no | soft / hard. Accepted (validated for length) and ignored by this route. |
| `processor` | string, max 4000 | no | Processor ids (CSV). Accepted (validated for length) and ignored by this route. |
| `acquiringBank` | string, max 4000 | no | Acquiring bank ids (CSV). Accepted (validated for length) and ignored by this route. |
| `company` | string, max 4000 | no | Company ids (CSV). Accepted (validated for length) and ignored by this route. |
| `hour` | string, max 200 | no | Hours 0-23 in tz (CSV); needs a valid tz or the request is a 400 `hour needs a valid tz`. Accepted (validated for length) and ignored by this route. |
| `ipType` | string, max 40 | no | IPv4 / IPv6. Accepted (validated for length) and ignored by this route. |
| `bin` | string, max 4000 | no | 6-digit BINs or a wallet label (CSV). Accepted (validated for length) and ignored by this route. |
| `funding` | string, max 200 | no | Funding type (CSV). Accepted (validated for length) and ignored by this route. |
| `browser` | string, max 200 | no | Browser (CSV). Accepted (validated for length) and ignored by this route. |
| `gatewayMcc` | string, max 1000 | no | Final MID MCC (CSV). Accepted (validated for length) and ignored by this route. |
| `gatewayBin` | string, max 1000 | no | Final MID acquirer BIN (CSV). Accepted (validated for length) and ignored by this route. |
| `pricePoint` | string, max 400 | no | Price bucket labels (CSV). Accepted (validated for length) and ignored by this route. |
| `walletProvider` | string, max 4000 | no | Wallet provider ids (CSV). Accepted (validated for length) and ignored by this route. |
| `method` | string, max 20 | no | card / wallet. Accepted (validated for length) and ignored by this route. |

**Response**

```json
{
  "series": [
    { "label": "13:00", "total": 412, "approved": 168, "declined": 236, "completed": 409, "approvedCents": 1849300 },
    { "label": "14:00", "total": 389, "approved": 151, "declined": 230, "completed": 385, "approvedCents": 1662500 }
  ]
}
```

| response field | type | description |
|---|---|---|
| `series` | array<object> | Ordered chronologically by the truncated bucket timestamp. Contains only buckets that had at least one transaction - never zero-filled. Empty array when the api-key scope is empty or no traffic matched. |
| `series[].label` | string | Local clock label HH24:MI for hours, MM-DD for days. Display only: repeated DST hours and different dates/years can share labels. Use bucketStart as identity. |
| `series[].total` | integer | All LIVE transactions in the bucket after scoping and filters (v3.9 section 1: no test card, no CSV import, no 3DS park). Includes pending/unknown/error statuses. |
| `series[].approved` | integer | Transactions where the is_success flag is true. |
| `series[].declined` | integer | v3.9 section 1 declines: transactions with status 'declined' OR 'error' (TXN_DECLINED_SQL - a technical error is a decline). Same definition as the /v1/metrics series and /v1/metrics/segments. |
| `series[].completed` | integer | v3.9.13 - the bucket's approval-rate base (TXN_COMPLETED_SQL: status approved, declined, error or unknown), as on GET /v1/metrics series[].completed. A rate is sum of approved / sum of completed, never approved / (approved + declined). |
| `series[].approvedCents` | integer | Integer CENTS. Sum of amount_cents over is_success rows only. Cast to bigint in SQL but converted with Number() before serialization, so it arrives as a JSON number, not a string - values above 2^53 cents would lose precision. |
| `series[].bucketStart` | string (date-time) | ISO UTC start instant of the bucket. Unique chronological identity, including repeated local hours at DST fall-back. Older cached payloads may omit it. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: hours outside 1..8760, from / to not a full ISO-8601 UTC datetime (for example 2026-11-01T00:00:00Z; a bare day or an offset is refused), bucket not hour | day, side outside straight | subscription | friendlies | both, a value over its max length, or `hour` without a valid tz (details.fieldErrors.tz = hour needs a valid tz). `{"error":"Invalid","details":{"fieldErrors":{"atri":["atri must be one ATRI id (a uuid)"]}}}`; `Invalid report timezone`; `Synchronous reports support at most 400 days. Use report jobs for larger ranges.` (no report-job kind covers the series: split the range). The gate also refuses a malformed or foreign `affiliate` / `flow` filter.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). The database is temporarily unavailable (Retry-After: 1) when the reporting pool is saturated.
- `504` The request took too long and was cancelled (25-second budget, queue time included); narrow the range or use bucket=day.

**Gotchas**

- `atri` is a SINGLE uuid despite the shared schema declaring it as a 4000-char CSV-style string. v3.9.13 - anything else is a 400 naming details.fieldErrors.atri (a CSV of two ids, a name, '__no_atri__'): the CSV that works on /v1/transactions is refused here.
- v3.9.13 - the caller's ATRI grants (user_trips) scope the series as the list and GET /v1/metrics do (tripTxnScope: the order's own ATRI OR an attempt's - cascade-aware). A user granted only a CASCADE pool now sees its orders; the grant read `t.trip_id = any(...)` before and gave an empty series. `atri` itself is the order's final pool (ATRI_FINAL_SQL).
- v3.9.13 - `source` is the list's clause: straight / subscription / sale / rebill / recovery, CSV. An unrecognised value is dropped silently, and when nothing survives you get the UNFILTERED series with HTTP 200 - no error, no echo of the applied filter anywhere in the response.
- `atriView` is accepted but ignored here, unlike GET /v1/metrics where it narrows the whole dashboard. Use `atri` to narrow this endpoint.
- The central LIVE predicate (v3.9 section 1) is always applied - test-card, CSV-imported and 3DS-park rows are excluded, and a charge cocoapi refused before any MID is not a transaction - so `total` will not match a raw transaction count for the same window.
- approved + declined != total. `approved` counts the is_success flag, `declined` counts status 'declined' or 'error' (v3.9 section 1); 'pending', 'unknown' and 'duplicate' land in `total` and nowhere else. v3.9.13 - `completed` (approved, declined, error or unknown) is the approval rate's base: compute a rate as sum of approved / sum of completed.
- Labels are ambiguous and must not be used as keys. With bucket=hour a 3-day window returns three separate rows all labelled '13:00'; with bucket=day a >1-year window collides on 'MM-DD'. Rely on array order (chronological) to place points.
- Empty buckets are omitted entirely - there is no zero-filling, so consecutive array entries are not necessarily adjacent hours or days. Reconstruct the axis yourself from from/to.
- bucket defaults to 'hour': a 90-day from/to without an explicit bucket=day returns ~2160 entries.
- Window resolution: `from` alone -> from..now (hours ignored); `to` alone -> (to - hours)..to; both -> hours ignored; neither -> last 24h up to now. `to` is inclusive.
- An empty api-key scope returns HTTP 200 with `series: []` - deny-by-default is indistinguishable from a quiet window.
- The series is scoped by the account's tenancy (db/txFilters tenantScope - its api keys and its wallet providers, the rule of GET /v1/metrics), so the wallet charges (Apple / Google Pay, api_key_id NULL) are in the buckets. Checked in v3.9.13: side=straight + side=subscription = the unfiltered series, point by point.
- `tz` shifts the bucket boundaries but the from/to comparison stays in UTC, so with a non-UTC tz the first and last buckets are partial.
- When tz is omitted, this report uses the effective account timezone, matching background report preparation. Trailing-hour windows keep that timezone for their labels and calendar-dependent calculations.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A trailing `hours` window (8760 at most) never reaches it. A client that disconnects cancels its SQL.

#### Transactions

The Transactions page: the list with every filter, the full record of one transaction, its timeline, notes and card, exports, selection, bulk edits, retries and the manual card sale (Add charge). Refunds and disputes are under Customers > Refunds and disputes.

- Live rows: the page receives new transactions through a database feed the API does not expose. A client polls `GET /v1/transactions` (newest first, `count=0`) instead.
- CSV: `GET /v1/transactions/export` returns the file. PDF: built in the browser from up to 10,000 rows of `GET /v1/transactions` with the same filters. "Select all matching": `GET /v1/transactions/ids`.
- Bulk retry: there is no bulk endpoint. The Retry console calls `POST /v1/transactions/:id/retry` once per transaction, skips the ones its copy of the eligibility rule refuses, and counts recovered (count and amount), declined, errors and skipped itself. The API enforces the same rule on every call.
- "Product data sent" (detail, Products tab): parsed in the browser from each attempt's `request_sent` in `GET /v1/transactions/:id/details` (NMI `item_*_N` parameters, or the `lineItems` array) and compared with the charged amount. The decisive attempt is the last attempt of the order.
- ATRI names next to a transaction: `GET /v1/trips`.

##### `GET /v1/filters/facets`

**Scope** `routing.read` - **Get every option of the unified filter**

The single options source of the unified advanced filter: every option-backed field of the catalog in one payload. Account values of the last 90 days (countries, storefronts, traffic sources, currencies, issuers, card types and levels, gateway MCCs and BINs, product names, slugs and keys, UTM sources and campaigns) and inventories (gateways including wallet sources as wallet:<id>, ATRIs within the ATRI view, categories, processors, acquiring banks, companies, subscription products, schedules of the last 90 days, entry reasons with counts), plus the account's flows and affiliates. Cached 5 minutes per account, tenant scope and role class; a payload with a failed read is never cached. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `v5` | string | no | Legacy hint, only the value true is accepted. It changes nothing: flows and affiliates are always returned to non-refund callers. Any other query key or value is a 400. |

**Response**

```json
{
 "currencies": [
  "USD"
 ],
 "gateways": [
  {
   "value": "8b7c0000-0000-4000-8000-000000000001",
   "label": "MID A"
  },
  {
   "value": "wallet:1f2e0000-0000-4000-8000-000000000002",
   "label": "wallet.shop.example.com"
  }
 ],
 "countries": [
  "FR",
  "US"
 ],
 "entryReasons": [
  {
   "value": "Do Not Honor",
   "label": "Do Not Honor",
   "count": 812
  }
 ],
 "flows": [
  {
   "value": "11111111-1111-4111-8111-111111111111",
   "label": "Main flow"
  }
 ],
 "affiliates": [
  {
   "value": "22222222-2222-4222-8222-222222222222",
   "label": "Partner One (AFF001)"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `currencies` | string[] | ISO-4217 currencies of the account's charges (upper-cased), max 50. |
| `products` | string[] | Basket product names (else slug / ref), max 400 - the `product` values. |
| `productSlugs` | string[] | Basket product slugs, max 400. |
| `productKeys` | string[] | `<store host>\|<product ref>` keys, max 400 - the `productKey` values. |
| `gatewayMccs` | string[] | MCCs of the MIDs the charges ended on, max 100. |
| `gatewayBins` | string[] | Acquirer BINs of those MIDs, max 100. |
| `issuers` | string[] | Issuing banks, top 200 by orders. |
| `cardTypes` | string[] | bin_info card types, max 50. |
| `cardLevels` | string[] | bin_info card levels, max 100. |
| `countries` | string[] | Billing countries (upper-cased, the `country` filter's expression), max 300. |
| `storefronts` | string[] | Store host buckets, max 300. |
| `trafficSources` | string[] | Traffic buckets, max 100. |
| `utmSources` | string[] | utm_source values, top 300 by orders. |
| `utmCampaigns` | string[] | utm_campaign values, top 300. |
| `gateways` | Opt[] ({ value, label[, count] }) | The account's MIDs (value = the MID id) and wallet gateways (value = `wallet:<walletProviderId>`), by name. |
| `atris` | Opt[] ({ value, label[, count] }) | The account's ATRIs (within the caller's ATRI view). |
| `categories` | Opt[] ({ value, label[, count] }) | The account's gateway categories. |
| `processors` | Opt[] ({ value, label[, count] }) | Processors (global reference list). |
| `acquiringBanks` | Opt[] ({ value, label[, count] }) | Acquiring banks (global). |
| `companies` | Opt[] ({ value, label[, count] }) | Companies (global). |
| `subscriptions` | Opt[] ({ value, label[, count] }) | The account's subscription products (not deleted). |
| `schedules` | Opt[] ({ value, label[, count] }) | Schedules of the last 90 days: label "<name> - <run day>", max 400. |
| `entryReasons` | Opt[] ({ value, label[, count] }) | Decline reasons of the account's schedule entries (90 days), with `count`, top 200. |
| `errors` | string[] (optional) | the facet names whose read FAILED (e.g. a statement timeout): their lists are empty because the options are unavailable, not because the account has no value. Absent when every read succeeded. A payload carrying it is not cached, so the next call retries. |
| `flows` | Opt[] ({ value, label }) | The account's flows (value = flow id), for the flow filter. Absent for the refund role. |
| `affiliates` | Opt[] ({ value, label }) | The account's affiliates (value = affiliate id, label = name and public id), for the affiliate filter. Absent for the refund role. |

**Errors**

- `400` {"error":"Invalid","details":...}: an unknown query parameter, or v5 with a value other than true.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Forbidden for your role (a member role outside admin, user and refund).
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- A value missing from an option list still applies when it arrives in a URL (the lists are a convenience, 90 days deep).
- A read that fails leaves its lists empty and is named in errors rather than failing the payload.
- GET /v1/transactions/facets keeps its ten historical fields (the same reads, uncached).
- Payment method filters accept card, wallet and wire. Bank source filters use accountId=wire:<bank-account-uuid>.
- flows ({value: flow id, label: name}) and affiliates ({value: affiliate id, label: "<name> (<public id>)"}) are read live, not cached, sorted by name.

##### `GET /v1/transactions`

**Scope** `transactions.read` - **List transactions (dashboard list: all columns, filters, sort)**

The dashboard transactions list (every column, the unified filters, sort and paging, with a total); GET /v1/reports/transactions is the Reporting API report and POST /v1/transactions the partner window sync. Paginated, filtered transaction list for the dashboard. Every filter is a comma-separated multi-value list; returns the page of rows plus a total for the same filter set (ignoring paging): exact up to 10,000 rows, a lower bound flagged `totalExact: false` beyond. Ordered by `sort` / `dir` over the WHOLE result set (default created_at desc) - the same order the CSV export and the id list use. v3.9.13 - `count=0` skips the total (`total: null`) for a caller that never reads it. Supports method=wire and accountId=wire:<bank-account-uuid>. Wire rows expose bank_account_id and keep wallet/card identifiers empty.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Start of the page range (inclusive): the grain's own date. A bare day is read in tz (its first millisecond). |
| `to` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | End of the page range (inclusive). A bare day is read in tz (its last millisecond). |
| `tz` | string (IANA timezone, max 64) | no | IANA timezone the days and hours are read in. Defaults to the account timezone. Must be a known zone. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `storefront` | CSV string (max 4000) | no | Store host bucket, (direct). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `checkout` | CSV of UUIDs or none | no | Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of UUIDs or none | no | Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. |
| `affiliate` | CSV of UUIDs or none | no | Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |
| `sort` | enum: created_at \| completed_at \| amount \| status \| order_id \| email \| customer \| mid \| atri \| crm \| country \| storefront \| traffic \| decline_reason \| card \| three_ds \| method \| source \| product \| subscription \| processor \| acquiring_bank \| company \| utm_source \| utm_campaign; default `created_at` | no | Sort column (nulls last, then created_at desc). |
| `dir` | enum: asc \| desc; default `desc` | no | Sort direction. |
| `limit` | integer (1-10000); default `50` | no | Page size. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |
| `count` | enum: 0 \| 1 | no | count=0 skips the total count (total null); absent or 1 counts, capped: a total of 10001 or more comes with totalExact false. |

**Response**

```json
{
 "transactions": [
  {
   "id": "8f3c1e2a-4b77-4c0d-9e21-1a2b3c4d5e6f",
   "order_id": "ORD-10482",
   "crm": "nmi",
   "type": "sale",
   "amount_cents": "4999",
   "currency": "USD",
   "status": "approved",
   "is_success": true,
   "masked_card": "4242424242424242",
   "email": "jane.doe@example.com",
   "first_name": "Jane",
   "last_name": "Doe",
   "final_account_id": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
   "final_account_name": "MID-EU-03",
   "processor_id": "a1b2c3d4-0000-4000-8000-000000000001",
   "processor_name": "PRIORITY",
   "acquiring_bank_id": "a1b2c3d4-0000-4000-8000-000000000002",
   "acquiring_bank_name": "SYNOVUS",
   "company_id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
   "company_name": "STELLAR TIDE LLC",
   "decline_reason": null,
   "order_id_supplier": "9876543210",
   "refunded": false,
   "refunded_at": null,
   "charged_back": false,
   "dispute_kind": null,
   "created_at": "2026-08-29T14:03:11.221Z",
   "completed_at": "2026-08-29T14:03:13.004Z",
   "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
   "atri_name": "US Straight Sale",
   "traffic_source": "meta",
   "storefront_url": "https://shop.example.com/checkout",
   "wallet_provider_id": null,
   "paysource": null,
   "provider": null,
   "channel": "checkout",
   "utm_source": "tiktok",
   "utm_medium": "paid",
   "utm_campaign": "us_summer_broad",
   "attribution_source": "checkout",
   "note_count": 0,
   "attempts": 2,
   "won_attempt": 2
  },
  {
   "id": "2b9d7c14-6e0a-4f3b-b8c5-5d4e3f2a1b09",
   "order_id": "ORD-10477",
   "crm": "convesio",
   "type": "sale",
   "amount_cents": "12900",
   "currency": "USD",
   "status": "declined",
   "is_success": false,
   "masked_card": "545454..5454",
   "email": "sam@example.com",
   "first_name": "Sam",
   "last_name": "Rivera",
   "final_account_id": null,
   "final_account_name": null,
   "processor_id": "a1b2c3d4-0000-4000-8000-000000000003",
   "processor_name": "CONVESIO PAY",
   "acquiring_bank_id": "a1b2c3d4-0000-4000-8000-000000000004",
   "acquiring_bank_name": "ADYEN",
   "company_id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
   "company_name": "STELLAR TIDE LLC",
   "decline_reason": "Insufficient funds",
   "order_id_supplier": null,
   "refunded": false,
   "refunded_at": null,
   "charged_back": false,
   "dispute_kind": null,
   "created_at": "2026-08-29T13:47:02.910Z",
   "completed_at": "2026-08-29T13:47:05.118Z",
   "trip_id": null,
   "atri_name": null,
   "traffic_source": "",
   "storefront_url": null,
   "wallet_provider_id": "e5f6a7b8-1234-4c5d-8e9f-0a1b2c3d4e5f",
   "paysource": "APPLEPAY",
   "provider": "ConvesioPay",
   "channel": "checkout",
   "utm_source": "tiktok",
   "utm_medium": "paid",
   "utm_campaign": "us_summer_broad",
   "attribution_source": "wallet",
   "note_count": 1,
   "attempts": 3,
   "won_attempt": null
  }
 ],
 "total": 1384
}
```

| response field | type | description |
|---|---|---|
| `transactions` | array<object> | The requested page, ordered created_at DESC. |
| `transactions[].amount_cents` | string | Integer CENTS, but serialized as a JSON STRING (Postgres bigint, no node-postgres type parser is configured). Parse before doing math. |
| `transactions[].status` | string | pending \| approved \| declined \| error \| unknown \| duplicate. |
| `transactions[].masked_card` | string \| null | The card as stored: first6..last4 on most rows; an API key receives it unmasked as stored. Use GET /v1/transactions/:id/card for the full card of one charge. |
| `transactions[].wallet_kind` | 'apple' \| 'google' \| null | v3.9.8 item 1 - the wallet of a wallet charge (Model A, routes/wallet.ts); null on a card charge and on a pre-Model-A passthrough row (crm 'convesio', its wallet in `paysource`). The dashboard names the method from it (lib/walletMethod walletMethodOf, the twin of db/txFilters walletMethodSql). |
| `transactions[].card_brand / card_last4` | string \| null | v3.9.8 item 1 - the card a wallet charge was paid with, as ConvesioPay reports it after the charge (GET /payments/{id}: the network normalised to Visa / Mastercard / Amex / Discover, '' = asked, none; exactly four digits). A wallet row has no masked_card: these two are what the Method chip's tooltip and the Card column show for it ('--4242'). |
| `transactions[].atri_name` | string \| null | trips.name for the transaction's own trip_id; null when the order has no trip. |
| `transactions[].processor_id` | string (uuid) \| null | - processors.id behind the charge: the final MID's processor, else (wallet row) the wallet provider's. Null when the gateway carries none or the order ended on no gateway. |
| `transactions[].processor_name` | string \| null | processors.name for processor_id, as stored (UPPERCASE, e.g. 'PRIORITY'); null with it. |
| `transactions[].acquiring_bank_id` | string (uuid) \| null | - acquiring_banks.id behind the charge, resolved like processor_id (final MID, else wallet provider). |
| `transactions[].acquiring_bank_name` | string \| null | acquiring_banks.name for acquiring_bank_id (e.g. 'SYNOVUS'); null with it. |
| `transactions[].company_id` | string (uuid) \| null | - companies.id behind the charge, resolved like processor_id (final MID, else wallet provider): the legal entity the gateway is boarded under. |
| `transactions[].company_name` | string \| null | companies.name for company_id (e.g. 'STELLAR TIDE LLC'); null with it. |
| `transactions[].paysource` | string \| null | raw_payload->>'paySource' (APPLEPAY / GOOGLEPAY) - wallet rows only. |
| `transactions[].provider` | string \| null | raw_payload->>'providerName'. |
| `transactions[].channel` | string \| null | raw_payload->>'channel' (checkout / straight / sale / rebill / rebill_legacy / legacy). |
| `transactions[].note_count` | number | Rows in transaction_notes for this transaction (::int, real number). |
| `transactions[].attempts` | number | Rows in transaction_attempts for this transaction (::int). |
| `transactions[].won_attempt` | number \| null | attempt_no of the lowest approved attempt; null when nothing approved. |
| `transactions[].dispute_kind` | string \| null | 'rdr' \| 'ethoca' \| null. |
| `transactions[].utm_source / utm_medium / utm_campaign` | string \| null | - the campaign attribution of the charge (transaction_attribution, one PK lookup per row): the raw utm values as the checkout / the wallet return_url sent them (never the network label of traffic_source). null when the charge has no attribution row - every card sale until the checkout sends `attribution`, and every row whose visit carried no utm. A subscription charge shows its SALE's values (attribution_source "rebill"). |
| `transactions[].attribution_source` | "checkout" \| "wallet" \| "rebill" \| "backfill" \| null | - where the row's attribution came from: the POST /v1/charge body, the wallet session (return_url + attribution object), a COPY of the sale's row on a subscription charge, or the wallet-history backfill of migration 158. null = no row. |
| `transactions[].subscription_assignment_source` | special_pre_auth \| cart \| subscription_block \| percentage \| null | Enrollment origin of this sale; rebills resolve it from their originating subscription transaction. Null means no recorded origin. This is separate from the transaction channel/source (checkout, rebill, pre-auth). |
| `transactions[].checkout_id` | uuid \| null | Checkout captured at sale, falling back to the persisted checkout identity for older rows; changing a current store route does not rewrite this sale. |
| `transactions[].checkout_name` | string | Persisted sale checkout name or resolved legacy checkout name; unattributed history remains explicitly labeled. |
| `total` | integer \| null | Exact total unless totalExact is false. count=0 returns null. A full result set is counted only up to 10001; deep-page lower bounds can be larger. |
| `totalExact` | false \| omitted | Present and false when total is only a lower bound, not an exact count. Never stop pagination solely because offset reaches a previously reported lower bound. |
| `v5_flow` | object \| null | Recorded flow {id,name,version,versionId,sessionId,kind}; null for transactions without a flow snapshot. Exposed with flow access. Historical direct transactions are not assigned a current flow retroactively. |
| `transactions[].checkout_origin` | rebill \| api \| checkout \| manual \| imported \| unknown | Current charge origin: rebill, api, checkout, manual, imported or unknown. Exposed with flow access. Rebills have no new checkout visit even when historical checkout/flow attribution is retained. API includes Friendlies; absence of a checkout ID never proves a legacy checkout visit. |
| `transactions[].bank_account_id` | uuid \| null | Receiving bank account for a Wire transaction; null on Card and Wallet rows. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is unknown (strict), a value is outside its vocabulary, a range pair is reversed, hour has no valid tz, or sort / dir is not allowed; `{"error":"Unknown flow filter"}` / `{"error":"Unknown affiliate filter"}` for a flow or affiliate id that is not the account's.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `500` Unhandled database error (Fastify default error body).
- `503` `Authentication scope is temporarily unavailable` (the gate could not load the caller's scope); a database-unavailable message with a `retry-after: 1` header when the connection pool is exhausted (a 503 since 2026-10-18, it used to surface as a 500); or `Transaction sorting is temporarily unavailable. Please refresh shortly.` from the bounded reader of sort=product / sort=subscription. All three are safe to retry unchanged.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- - every dimension filter is built on the very expression the Traffic report groups on (db/txFilters), so a count on Reports > Traffic / Bin & Issuers opens exactly the rows it counts: device / os / browser / ipType / country / storefront / traffic / ip read the INHERITED context (a subscription charge reads its originating sale's - the earliest row of the same order_id), country is upper-cased, brand comes from the stored card network first, funding / issuer / cardLevel / bin from the card's first six digits. There is no '(unknown)' / 'Other' bucket to filter on any more: a row without a value simply matches nothing (only `brand=Other` survives, as 'no recognised network').
- `hour` is the one filter with a precondition: it needs `tz` (a known IANA zone) or the request is a 400 - the hour buckets of the Traffic report are read in the dashboard's timezone and a drill-down carries it; `tz` alone filters nothing.
- v3.9.15 - uuid-typed filters (atri, accountId, category, walletProvider, subscription, schedule...) are validated: a value that is not a uuid (or one of the key's words: `none`, `wallet:<id>`) is a 400 naming it - never unfiltered results.
- `pass` is a no-op unless exactly one value is supplied; passing both values disables that filter. `source` (since ORs its values on SOURCE_BUCKET - the Traffic report's `source` dimension expression - and 'sale' excludes the recovery rows.
- All bigint columns (amount_cents here) come back as JSON strings, while the ::int-cast columns (note_count, attempts, won_attempt, total) come back as numbers.
- Ordering is `sort`/`dir` (default `created_at desc`); every other key tie-breaks on created_at desc and there is no id tiebreaker, so paging across rows with identical values is not stable.
- - utm_source / utm_campaign on a row are the ATTRIBUTION table's values, distinct from `traffic_source` (a network label on card sales - meta | tiktok | snapchat - and a raw utm_source on wallet sales): filter campaigns with utmSource / utmCampaign, networks with traffic. Card sales carry no utm until the checkout sends `attribution` on POST /v1/charge; wallet sales carry theirs since migration 150 (back-filled from the session's return_url).
- v3.9.9 - every statistic's drill-down: a dashboard link sends population=live (the rows a statistic counts), its display timezone (`tz`, the days of from/to) and, for a refund / chargeback figure, the `refund` event - so the list total equals the figure clicked.
- Checkout subscription priority is explicit Special Pre-Auth > subscription product in the signed cart > selected Subscription product block > account product percentage attachment. Only one winning subscription is attached to a sale. Multiple signed-cart products choose the lowest sorted product UUID; conflicting selected blocks use the first matching document offer. Overlapping percentage matches choose the oldest configured matching product, then UUID.
- Last orders in dashboard All requests source=sale,recovery,rebill,friendlies&limit=20&offset=0&count=0, with the selected UTC from/to. Friendlies remains hidden by the server when its integration is inactive. Pre-auth verification attempts remain outside this sales list.
- Use source=friendlies for only Friendlies, straight for sale+recovery, or subscription for rebills. Keep all filters and dates unchanged while paginating.
- count=0 returns total:null. With counting enabled the count is capped at 10,001; totalExact:false marks a lower bound, not an exact result. An exact answer omits totalExact. Short pages return their exact end; keep filters/sort fixed and do not stop exporting at a previously observed lower bound.
- V5 filter admission is scoped to the effective account and current feature flags. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing legacy storefront data alone is not No store.
- The v5_affiliate projection enriches merchant records with immutable attribution and cut ledger entries; list and CSV include Affiliate/public ID/status/cuts. This merchant projection is never used by the masked native affiliate workspace.
- Filters use the one unified catalog shared by the transactions list, the reports and the bulk tools: the query is strict (an unknown parameter is a 400 that names it), a closed vocabulary rejects unknown values, CSV values are OR-ed inside a key and keys are AND-ed, range pairs (from/to, amountMin/amountMax, cycleMin/cycleMax, clientOrdersMin/Max, clientLtvMin/Max, the sub and client date pairs, dayFrom/dayTo) must be ordered, and hour needs a valid tz.
- There is no push feed of new transactions for an API key: to follow them live, poll this list sorted by created_at desc (for example every 30 s with limit=20&count=0) and keep the newest id you have seen.

##### `POST /v1/transactions`

**Scope** `transactions.read` - **Sync transactions of a date window (partner shape, paged)**

Syncs every transaction of a date window in the partner shape, page by page in a stable order, for mirroring; GET /v1/transactions is the dashboard list and GET /v1/reports/transactions the Reporting API report. Paginated, stable-ordered listing of every card and wallet transaction in a date window, for a partner mirroring/syncing this database. Returns the same PCI-safe per-transaction shape as /v1/refund/search plus refund/chargeback/dispute state and paging metadata.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 datetime) | **yes** | REQUIRED window start, inclusive (`created_at >= from`). Must be UTC with a trailing `Z` (`2026-08-01T00:00:00Z`); date-only strings and `+hh:mm` offsets are rejected with 400. |
| `to` | string (ISO 8601 datetime) | **yes** | REQUIRED window end, inclusive (`created_at <= to`). Same UTC-with-`Z` strictness. A cross-field refine enforces `new Date(from) <= new Date(to)`; an inverted window is a 400, not an empty result. |
| `status` | string (enum) | no | Optional exact filter on the transaction status. Allowed values ONLY: `approved`, `declined`, `error`, `unknown`, `pending`, `duplicate`. Anything else is a 400. Omit to get every status in the window. |
| `page` | integer; default `1` | no | 1-based page number, minimum 1 (a 0 or negative page is a 400). Translates to `offset = (page - 1) * pageSize`. |
| `pageSize` | integer; default `200` | no | Rows per page, 1-500. Defaults to 200 via the zod schema (unlike search's `limit`, this default is real schema-level). |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "from": "2026-08-01T00:00:00Z",
 "to": "2026-08-02T00:00:00Z",
 "status": "approved",
 "page": 1,
 "pageSize": 200
}
```

**Response**

```json
{
 "page": 1,
 "pageSize": 200,
 "totalItems": 417,
 "totalPages": 3,
 "count": 200,
 "transactions": [
  {
   "transactionId": "1c77b0a4-55de-4a91-9a2f-6d0b8f2c4471",
   "orderId": "ORD-100311",
   "amount": 89.0,
   "currency": "USD",
   "status": "approved",
   "approved": true,
   "refundStatus": "partial",
   "createdAt": "2026-08-01T00:04:19.006Z",
   "mid": "Northlight Ltd - NMI 1",
   "midNumber": "8830145",
   "gatewayTxnId": "10339112004",
   "actionType": "rebill",
   "operation": "REFUND",
   "customerId": "cus_7a1d0c55e2b94f10",
   "card": "553912......4402",
   "cardExpiration": "1127",
   "refunded": 25.0,
   "refundable": 64.0,
   "refundedAt": null,
   "chargedBack": false,
   "disputeKind": "ethoca",
   "descriptor": "NORTHLIGHT*CARE 8005550199",
   "email": "m.okafor@example.com",
   "customerName": "Miriam Okafor",
   "gatewayType": "nmi",
   "walletKind": null,
   "storefrontUrl": "https://care.example.com",
   "trafficSource": "email",
   "productId": "SKU-CARE-90",
   "orderDescription": "Care Plan 90ct",
   "paymentGatewayId": "a1d6b70e-4c22-4f0e-b1a8-93f6d2c50177",
   "authCode": "771204",
   "avsResponse": "Y",
   "cscResponse": "M",
   "responseText": "SUCCESS",
   "ipAddress": "203.0.113.77",
   "billing": {
    "address1": "88 Harbour Rd",
    "city": "Portland",
    "state": "OR",
    "postalCode": "97205",
    "country": "US",
    "phone": "+15035550188"
   },
   "shipping": {
    "firstName": "Miriam",
    "lastName": "Okafor",
    "address1": "88 Harbour Rd",
    "city": "Portland",
    "state": "OR",
    "postalCode": "97205",
    "country": "US"
   }
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `page` | integer | Echo of the requested page. |
| `pageSize` | integer | Echo of the effective page size (200 when omitted). |
| `totalItems` | integer | Total rows matching the window+status, from `count(*) over()` read off the FIRST returned row. Reads 0 whenever the page is empty - see gotchas. |
| `totalPages` | integer | `Math.ceil(totalItems / pageSize)`. Also 0 on an empty page. |
| `count` | integer | Rows on THIS page (<= pageSize). |
| `transactions` | array | Exactly the same object shape as POST /v1/refund/search returns - identical field names and semantics (both use `toPartnerTxn`). See that route for the per-field breakdown. Includes `actionType` (`straight_sale` \| `rebill` \| `rebill_legacy` \| `imported`) - see POST /v1/refund/search for the meaning of every field and why some are null. The former `preGateway` field is gone (: a refusal before any MID is not a transaction). Also `operation` (SALE\|REFUND\|VOID\|CHARGEBACK - the record's current type) and `customerId` (stable email-derived id). |

**Errors**

- `400` `{ "error": "Invalid request", "details": <zod flatten()> }` - missing/malformed `from` or `to`, an out-of-enum `status`, `page` < 1, `pageSize` outside 1-500, or the refine failure '`from` must be <= `to`'.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `transactions.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `500` `{ "error": "Internal Server Error", "requestId": "..." }`.
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- PAGING PAST THE END LIES: `totalItems`/`totalPages` are read from the first row of the page (`rows[0]?.total ?? 0`). Request a page beyond the last one and you get `count: 0, totalItems: 0, totalPages: 0` even though the window has hundreds of rows. Trust the totals from page 1, or stop when `count < pageSize`.
- Ordering differs from search: this route is `created_at ASC, id ASC` (stable, so walking pages 1..totalPages mirrors the window exactly), while /v1/refund/search is `created_at DESC`.
- New charges landing inside the window while you page will shift rows; the ASC order means they append at the end, so a sync that walks upward converges - but `totalItems` from page 1 can be stale by the last page.
- The parameter is `pageSize`, NOT `limit` (that's the search route). Sending `limit` here is silently ignored - it isn't in the schema, and unknown keys are stripped by zod rather than rejected.
- `from`/`to` are both REQUIRED here (they're optional on search) and both inclusive.
- The enum accepts `pending`, `unknown` and `duplicate`, which exist in the schema but may be rare in the data; an out-of-enum value is a 400, not an empty result.
- Only rows whose CRM is `nmi` or `convesio` are listed. Anything else is excluded from both the rows and the totals.
- Money fields are MAJOR UNITS (dollars): `amount`, `refunded`, `refundable`. Storage is integer cents.
- `shipping` addresses mirror `billing` by design (see /v1/refund/search gotchas) - do not treat them as independently captured shipping data.
- `actionType` is the sale's ORIGIN, not an operation type: there are no AUTHORIZE/CAPTURE/REFUND/VOID rows. Derive REFUND/VOID from `refundStatus`/`refunded`/`refundedAt` and chargebacks from `chargedBack`. `imported` rows (CSV card-on-file backfills) carry no gateway data at all and cannot go through POST /v1/refund - use POST /v1/refund/mark.
- Nulls are honest, not bugs: imported rows never touched a gateway; wallet rows are tokenised (no card/expiry/authCode/AVS/CSC); declines never have an authCode. : a charge cocoapi refused before any MID is not a transaction at all - the former `preGateway` field is gone and every listed decline is a MID verdict or a technical error. ARN, CAVV/3DS, customer/affiliate ids and card fingerprint do not exist in this system.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.

##### `GET /v1/transactions/:id/card`

**Scope** `transactions.write` - **Read a transaction's card number in clear**

Returns the card of one charge of the account in clear (number, expiry, holder) for the order and customer views. A rebill returns the card on file of its original sale.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Transaction id (account-scoped). A value that is not a uuid is a 404 (never the detail route's cast error). |

**Response**

```json
{
 "card": {
  "number": "4111111111111111",
  "expiry": "12/28",
  "holder": "JANE DOE",
  "brand": "visa",
  "last4": "1111",
  "source": "charge",
  "transactionId": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001"
 }
}
```

| response field | type | description |
|---|---|---|
| `card` | object\|null | The card in clear; null when no card number exists for the charge - a wallet charge (Apple Pay / Google Pay carry no PAN) or an order with no NMI card row in the caller's tenancy. A null answer writes no audit row. |
| `card.number` | string | The card number, digits only (spaces / dashes stripped), as the checkout sent it. |
| `card.expiry` | string\|null | 'MM/YY' from the stored expiry ('MMYY', 'MM/YY', 'MM/YYYY' or 'MMYYYY'); any other shape as stored; null when none is stored. |
| `card.holder` | string\|null | The cardholder name the checkout sent (cardHolderName), else the row's first + last name; null when neither exists. |
| `card.brand` | enum: visa\|mastercard\|amex\|discover\|unknown | From the number's prefix (lib/money cardBrand). |
| `card.last4` | string | The last four digits. |
| `card.source` | enum: charge\|card_on_file | 'charge' = this charge's own card; 'card_on_file' = the order's card on file (a subscription charge, or a row stored without its number). |
| `card.transactionId` | uuid | The row the card was read from: :id itself when source = 'charge', else the order's card-on-file row. |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` {"error":"Not found"} - not a uuid, unknown, or another account's charge (indistinguishable on purpose).
- `500` {"error":"Internal Server Error","requestId":"<id>"} - unexpected failure (logged with the requestId).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Never the security code: whatever is stored, a CVV is not part of this answer.
- Cache-Control: no-store (+ Pragma: no-cache on a reveal) - no browser, proxy or CDN may keep it.
- The card-on-file lookup is tenancy-scoped too: a card row of the same order under another account's keys is never read.
- An API key always receives the card in clear (number, expiry, holder); each answer that carries a card writes one view_secret audit row. A wallet charge answers {"card": null}. Sent with cache-control: no-store.

##### `GET /v1/transactions/:id/details`

**Scope** `transactions.read` - **Get a transaction's full record (attempts, basket, 3DS, fees, pipeline, attribution)**

The full dashboard record of one transaction (the redacted row with live fees, every attempt, the basket and its product-matching diagnosis, the 3DS session, the pipeline run, the attribution, the subscription entry); GET /v1/transactions/:transactionId is the shorter partner summary with refund history. Full detail for one transaction: every column of the transactions row plus a computed per-authorization fee total, the ordered cascade attempt trail (including raw gateway request/response), and the checkout basket resolved by order_id. : `pipelineRun` - the LATEST sale pipeline run behind the charge (its ordered stages with decision and duration, outcome, fell_through, timing offsets; null for a charge from before the pipeline) - and `pipelineNames`, the ATRI / MID names the run's stages cite. : `attribution` - the charge's campaign attribution row (transaction_attribution), null when none. v3.9.3: `subEntry` - the rebill_entries row that produced a SUBSCRIPTION charge (the modal's Subscription tab, "This charge" card): entry id, schedule_id, sub_id, run_day, scheduled_at, processed_at, rebill_number, rebill_type (first | recurring | retry | insufficient_funds), status, amount_cents, decline_reason, decline_normalized, mid_id, mid_name, attempt_count, blocked, retry_step (the SUB's current dunning step, rebill_subs.retry_step - an entry carries none of its own), run_id (the sale_pipeline_runs row). One read on rebill_entries (transaction_id); null on a sale, a wallet charge, a legacy / batch-API rebill (no entry) and on a failed read (decoration, like pipelineRun). The transaction also carries shopify_exports: owned checkout export states (exported, retry_pending, reconciliation_required, manual_review), recorded errors and retry timing; null means the export status could not be read. Historical orders are never automatically replayed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | transactions.id. Read raw from req.params with NO zod validation - a non-UUID value reaches Postgres and answers 400 `A value has an invalid format.` (Postgres invalid input), not a 404. |

**Response**

```json
{
 "transaction": {
  "id": "8f3c1e2a-4b77-4c0d-9e21-1a2b3c4d5e6f",
  "order_id": "ORD-10482",
  "api_key_id": "1122aabb-3344-4c55-8d66-77ee88ff99aa",
  "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
  "crm": "nmi",
  "type": "sale",
  "amount_cents": "4999",
  "currency": "USD",
  "status": "approved",
  "is_success": true,
  "masked_card": "4242424242424242",
  "email": "jane.doe@example.com",
  "first_name": "Jane",
  "last_name": "Doe",
  "final_account_id": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
  "final_account_name": "MID-EU-03",
  "decline_reason": null,
  "order_id_supplier": "9876543210",
  "idempotency_key": "checkout:ORD-10482",
  "response_envelope": {
   "response": "1",
   "responsetext": "SUCCESS"
  },
  "raw_payload": {
   "channel": "checkout",
   "country": "US",
   "phone": "+15551234567",
   "ipaddress": "203.0.113.44",
   "useragent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)"
  },
  "created_at": "2026-08-29T14:03:11.221Z",
  "completed_at": "2026-08-29T14:03:13.004Z",
  "expify_state": null,
  "expify_at": null,
  "refunded": false,
  "refunded_at": null,
  "refund_supplier_id": null,
  "refunded_cents": "0",
  "refund_status": "none",
  "transaction_fee_cents": "30",
  "discount_fee_cents": "145",
  "reserve_cents": "500",
  "total_fee_cents": "675",
  "net_cents": "4324",
  "customer_vault_id": null,
  "traffic_source": "meta",
  "storefront_url": "https://shop.example.com/checkout",
  "fbclid": "IwAR3xyz",
  "ttclid": null,
  "pre_gateway": false,
  "wallet_provider_id": null,
  "wallet_kind": null,
  "recheck_at": null,
  "recheck_attempts": 0,
  "charged_back": false,
  "dispute_kind": null,
  "import_batch_id": null,
  "attempt_txn_fees_cents": "60",
  "shopify_exports": []
 },
 "attempts": [
  {
   "id": "aa11bb22-cc33-4d44-8e55-ff6677889900",
   "nmi_account_id": "d4e5f6a7-b8c9-4012-8345-6789abcdef01",
   "account_name": "MID-US-01",
   "attempt_no": 1,
   "outcome": "declined",
   "response_code": "2",
   "response_text": "DECLINE",
   "transactionid_supplier": "9876543209",
   "decline_reason": "Do not honor",
   "latency_ms": 812,
   "created_at": "2026-08-29T14:03:11.900Z",
   "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
   "pass": "initial",
   "skip_reason": null,
   "request_sent": {
    "amount": "49.99",
    "statementDescriptor": "EXMPL SHOP"
   },
   "response_raw": {
    "response": "2",
    "responsetext": "DECLINE",
    "authcode": ""
   },
   "atri_name": "US Straight Sale"
  },
  {
   "id": "bb22cc33-dd44-4e55-8f66-001122334455",
   "nmi_account_id": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
   "account_name": "MID-EU-03",
   "attempt_no": 2,
   "outcome": "approved",
   "response_code": "1",
   "response_text": "SUCCESS",
   "transactionid_supplier": "9876543210",
   "decline_reason": null,
   "latency_ms": 934,
   "created_at": "2026-08-29T14:03:12.850Z",
   "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
   "pass": "cascade",
   "skip_reason": null,
   "request_sent": {
    "amount": "49.99",
    "statementDescriptor": "EXMPL SHOP"
   },
   "response_raw": {
    "response": "1",
    "responsetext": "SUCCESS",
    "authcode": "123456",
    "avsresponse": "Y",
    "cvvresponse": "M"
   },
   "atri_name": "US Straight Sale"
  }
 ],
 "products": [
  {
   "product_ref": "SKU-778",
   "name": "Daily Greens 30ct",
   "slug": "daily-greens-30",
   "url": "https://shop.example.com/p/daily-greens-30",
   "storefront_url": "https://shop.example.com",
   "quantity": 2,
   "line_no": 1,
   "amount_cents": "2499"
  }
 ],
 "pipelineRun": {
  "id": "6f1a2b3c-4d5e-4f60-8a7b-8c9d0e1f2a3b",
  "created_at": "2026-08-29T14:03:11.221Z",
  "order_id": "ORD-10482",
  "transaction_id": "8f3c1e2a-4b77-4c0d-9e21-1a2b3c4d5e6f",
  "rejection_id": null,
  "run_no": 1,
  "resumed_from": null,
  "flow": "initial",
  "channel": "checkout",
  "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
  "final_trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
  "bin": "411111",
  "issuer_key": "JPMORGAN CHASE",
  "card_brand": "Visa",
  "card_funding": "Debit",
  "country": "US",
  "amount_cents": 4999,
  "outcome": "approved",
  "refused_by": null,
  "fell_through": false,
  "stages": [
   {
    "name": "context",
    "input": {
     "orderId": "ORD-10482",
     "flow": "initial",
     "channel": "checkout",
     "tripId": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
     "bin": "411111",
     "issuerKey": "JPMORGAN CHASE",
     "brand": "visa",
     "country": "US",
     "binSource": "warm",
     "reads": 0
    },
    "decision": {
     "action": "resolve",
     "applied": true
    },
    "durationUs": 1830
   },
   {
    "name": "refusals",
    "input": {
     "flow": "initial",
     "bin": "411111",
     "issuerKey": "JPMORGAN CHASE",
     "rules": "blacklist,filters,precheck,cooldown",
     "scrubbing": null
    },
    "decision": {
     "action": "none",
     "applied": false,
     "reason": "checked blacklist,filters,precheck,cooldown"
    },
    "durationUs": 42110
   },
   {
    "name": "rebill_rules",
    "skipped": "not_applicable",
    "input": {
     "atri": null,
     "preferredMid": null,
     "mitArm": null,
     "sameMid": null,
     "previous": 0,
     "pinOnly": false
    },
    "decision": null,
    "durationUs": 0
   },
   {
    "name": "mapping",
    "input": {
     "profileId": "6b1f0c2e-9d3a-4f7b-8c5e-1a2b3c4d5e6f",
     "tripId": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
     "bin": "411111",
     "issuerKey": "JPMORGAN CHASE"
    },
    "decision": {
     "action": "map",
     "applied": true,
     "profileId": "6b1f0c2e-9d3a-4f7b-8c5e-1a2b3c4d5e6f",
     "ruleId": "44444444-4444-4444-8444-444444444444",
     "matchType": "issuer",
     "pool": [
      "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
      "d4e5f6a7-b8c9-4012-8345-6789abcdef01"
     ],
     "pool_n": 2,
     "reason": "pool of 2"
    },
    "durationUs": 66
   },
   {
    "name": "route",
    "input": {
     "tripId": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
     "defaultTripId": null,
     "brand": "visa",
     "pinOnly": false,
     "pin": null,
     "mappingPool": 2,
     "mappingSingle": null,
     "strategy": "smart",
     "candidates": 6,
     "eligible": 2,
     "level": "mapping"
    },
    "decision": {
     "action": "route",
     "applied": true,
     "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
     "pool": [
      "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
      "d4e5f6a7-b8c9-4012-8345-6789abcdef01"
     ],
     "pool_n": 2,
     "reason": "level: mapping"
    },
    "durationUs": 61220
   },
   {
    "name": "threeds",
    "input": {
     "mode": "inline",
     "inline": true,
     "onRebills": false,
     "onChallenge": "skip",
     "profileId": null,
     "route": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
     "ruleMode": null
    },
    "decision": {
     "action": "authenticate",
     "applied": true,
     "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
     "reason": "Y"
    },
    "durationUs": 12045000
   },
   {
    "name": "send",
    "input": {
     "tripId": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
     "strategy": "smart",
     "ordered": 2,
     "pinned": null,
     "cascadeTripId": null,
     "retryWithoutThreeDs": false,
     "threeDs": "Y"
    },
    "decision": {
     "action": "charge",
     "applied": true,
     "chosen": "d4e5f6a7-b8c9-4012-8345-6789abcdef01",
     "pool_n": 2,
     "reason": "declined on MID-US-01 (1 attempt)"
    },
    "durationUs": 3728000
   },
   {
    "name": "route",
    "input": {
     "tripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
     "pass": "cascade",
     "eligible": 1,
     "categoryMode": "none"
    },
    "decision": {
     "action": "route",
     "applied": true,
     "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
     "pool": [
      "c1d2e3f4-a5b6-4788-9900-aabbccddeeff"
     ],
     "pool_n": 1,
     "reason": "cascade: eligible"
    },
    "durationUs": 8100
   },
   {
    "name": "send",
    "input": {
     "tripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
     "pass": "cascade",
     "attempts": 1
    },
    "decision": {
     "action": "charge",
     "applied": true,
     "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
     "reason": "cascade: approved"
    },
    "durationUs": 4229000
   }
  ],
  "total_us": 20380000,
  "t_claim_us": 44200,
  "t_first_send_us": 12151000,
  "t_completed_us": 20380000
 },
 "attribution": {
  "transaction_id": "8f3c1e2a-4b77-4c0d-9e21-1a2b3c4d5e6f",
  "utm_source": "tiktok",
  "utm_medium": "paid",
  "utm_campaign": "us_summer_broad",
  "utm_id": "1758791553",
  "utm_term": null,
  "utm_content": null,
  "click_ids": {
   "ttclid": "E.C.P.CvQ1wR8kZm",
   "fbp": "fb.1.1758791553.1029384756",
   "ttclid_ts": "1758791553",
   "utm_adset": "AS-17"
  },
  "landing_url": "https://shop.example.com/products/recovery-serum?utm_source=tiktok&utm_medium=paid&utm_campaign=us_summer_broad&utm_id=1758791553&ttclid=E.C.P.CvQ1wR8kZm",
  "referrer": "shop.example.com",
  "captured_at": "2026-08-29T14:02:58.000Z",
  "source": "checkout",
  "created_at": "2026-08-29T14:03:11.309Z"
 },
 "pipelineNames": {
  "trips": {
   "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5": "US Straight Sale",
   "481c0a6e-4107-4128-99bd-6d52ac4362e5": "US Cascade"
  },
  "mids": {
   "c1d2e3f4-a5b6-4788-9900-aabbccddeeff": "MID-EU-03",
   "d4e5f6a7-b8c9-4012-8345-6789abcdef01": "MID-US-01"
  }
 }
}
```

| response field | type | description |
|---|---|---|
| `transaction` | object | `select t.*` - EVERY column of the transactions table, so new migrations add fields here automatically. |
| `transaction.attempt_txn_fees_cents` | string | Integer CENTS as a JSON string: sum of nmi_accounts.transaction_fee_cents over every non-'skipped' attempt (each MID bills the flat auth fee whether it approved or failed), at the MIDs' CURRENT rates. |
| `transaction.fees` | object | v3.9.6 live fees - { discount_cents, reserve_cents, transaction_cents, three_ds_cents, total_cents, net_cents, basis: 'live' } (integer cents, REAL JSON NUMBERS): the row's fee breakdown computed at read time from the gateway's CURRENT settings (api/src/db/fees.ts) - discount / reserve = the MID's (else the wallet provider's) bps x the approved amount, transaction = attempt_txn_fees_cents + the wallet provider's flat fee on a completed wallet charge, three_ds = the 3DS integration's current attemptFeeUsd when the charge ran 3DS with a provider, total = the four, net = the approved amount (0 when not approved) - total. The six legacy keys below carry the same live figures. |
| `transaction.transaction_fee_cents / discount_fee_cents / reserve_cents / total_fee_cents / three_ds_fee_cents` | string | v3.9.6 live fees - the LIVE figures of `fees` (transaction / discount / reserve / total / three_ds), as bigint-style JSON STRINGS for the modal: `select t.*` still returns the deprecated snapshot columns of the same names, but the route OVERWRITES them with today's computation, so a fee edit changes what an old transaction shows. The columns themselves are deprecated (migration 168) and dropped later. |
| `transaction.refunded_cents / refund_status` | string / string | Cents already refunded (bigint -> string) and 'none' \| 'partial' \| 'refunded'. Remaining refundable = amount_cents - refunded_cents. |
| `transaction.net_cents` | string | v3.9.6 live fees - fees.net_cents as a string: the approved amount (0 when not approved) - every fee at today's gateway rates; never the deprecated transactions.net_cents snapshot. |
| `attempts` | array<object> | Ordered by (outcome='skipped') then attempt_no then created_at - so skipped attempts sort LAST, and attempt_no is not monotonic across the array. |
| `attempts[].outcome` | string | approved \| declined \| error \| timeout \| skipped. |
| `attempts[].pass` | string | 'initial' or 'cascade' - which routing pass the attempt belonged to. |
| `attempts[].request_sent / response_raw` | object \| null | Raw gateway request/response JSON. Contains descriptors, AVS/CVV codes and auth codes - never a PAN or CVV value. |
| `products` | array<object> | Basket lines, deduped on (line_no, product_ref), ordered by line_no then product_ref then id. |
| `products[].amount_cents` | string \| null | Per-line cents. When the stored value is 0 (wallet multi-product lines carry no per-line price), it falls back to the MODE of non-zero amounts for the same product_ref across all transactions - so it can be an ESTIMATE, not this order's actual price. |
| `products[].name / slug / url` | string \| null | Fall back to any other row with the same product_ref that has them, so wallet lines inherit the label learned from a card sale. |
| `pipelineRun` | object \| null | - the latest sale pipeline run behind this charge (sale_pipeline_runs by transaction_id; a 3DS re-submit resumes as run 2). null before the pipeline / when the table is absent. Shape: the PIPELINE_RUN fields below. |
| `PIPELINE_RUN.id / created_at / order_id / transaction_id / rejection_id` | uuid / string / string / uuid \| null / uuid \| null | One sale pipeline run (sale_pipeline_runs, migration 148). transaction_id is null for a refusal (no transactions row, and for a discarded 3DS-policy row; rejection_id is the charge_rejections row when refused. |
| `PIPELINE_RUN.run_no / resumed_from` | integer / uuid \| null | A 3DS challenge re-submit RESUMES the run that parked: run_no 2, resumed_from = run 1 (its stages 2-4 copied as skipped: "resumed", never re-evaluated). |
| `PIPELINE_RUN.flow / channel / trip_id / final_trip_id` | string \| null ... | flow initial \| rebill; trip_id = the ATRI resolved at the start, final_trip_id = after a mapping redirect / the fall-through to the account's default ATRI (an ATRI with no eligible MID for the card never ends the charge any more). |
| `PIPELINE_RUN.bin / issuer_key / card_brand / card_funding / country / amount_cents` | scalars | The context the rules matched on: first 6 digits only, the canonical issuer key, the brand, funding and country from the bin_info preload / the payload. Never a PAN. |
| `PIPELINE_RUN.outcome / refused_by / fell_through` | enum / string \| null / boolean | outcome in approved \| declined \| error \| rejected \| parked \| replayed \| unknown; refused_by = the rejection family when rejected; fell_through = at least one stage ended in a fall-through (a technical problem routed around - the "never refused for a technical reason" counter). |
| `PIPELINE_RUN.stages[]` | array | The ordered stages - context, refusals, rebill_rules, mapping, route, threeds, send (9 entries when a cascade route/send pair was appended): { name, skipped? (not_applicable \| short_circuit \| resumed), input (ids and scalars, <= 256 B), decision: { action, applied, reason (<= 80 chars), profileId?, ruleId?, matchType?, pool (<= 5 ids), pool_n, chosen?, redirectTripId? } \| null, durationUs, error? ("timeout" \| "error" = the stage failed open) }. The whole array is <= 4 096 bytes. Every stage's vocabulary: docs/SALE_FLOW.md section 5. |
| `PIPELINE_RUN.total_us / t_claim_us / t_first_send_us / t_completed_us` | integer \| null | Microseconds from the request's receipt (the scheduler's claim instant for a Subscription charge): the result, the claim (start of stage 5), the first gateway send, the finalize. total_us is always set (a refusal has a real total: the cost of the gates); t_claim_us / t_first_send_us / t_completed_us are null for a refusal (no claim); all four are null for a swept "abandoned claim" run. |
| `pipelineNames` | object | { trips: { <atri id>: name }, mids: { <mid id>: name } } - every ATRI / MID the run's stages cite (chosen, pool, pin, 3DS route, redirect target), resolved for display; {} when no run. |
| `attribution` | object \| null | - the campaign attribution row of this charge (transaction_attribution, migration 150; the modal's UTM tab): { transaction_id, utm_source, utm_medium, utm_campaign, utm_id, utm_term, utm_content (string \| null each, raw as sent - utm_source is never the traffic_source label), click_ids (object: ttclid / fbclid / gclid / msclkid + free keys such as fbp, fbc, ttp, sccid, ttclid_ts, utm_adset, wacid; keys lower-cased), landing_url, referrer (string \| null, query keys email / phone / name / token / password / auth / session stripped), captured_at (ISO: the checkout's pay-click clock, else the request time / the wallet session's start), source ("checkout" = POST /v1/charge body - "wallet" = the wallet session - "rebill" = a COPY of the sale's row onto this subscription charge - "backfill" = the wallet history), created_at }. null = no row (the tab's "No attribution": a card sale before the checkout sends `attribution`, a visit with no utm / click id, a rejection). Decoration: a read failure is null, never a 500. |
| `subEntry` | object \| null | {id, schedule_id, order_id, sub_id, run_day (YYYY-MM-DD), scheduled_at, processed_at, rebill_number, rebill_type, status, amount_cents, decline_reason, decline_normalized, mid_id, mid_name, attempt_count, blocked, retry_step, run_id} - the rebill entry behind a subscription charge; null when the transaction is not a subscription charge of the in-house engine. |
| `transaction.subscription_assignment_source` | special_pre_auth \| cart \| subscription_block \| percentage \| null | Enrollment origin of this sale; rebills resolve it from their originating subscription transaction. Null means no recorded origin. This is separate from the transaction channel/source (checkout, rebill, pre-auth). |
| `transaction.checkout_id` | uuid \| null | Checkout captured at sale, falling back to the persisted checkout identity for older rows; changing a current store route does not rewrite this sale. |
| `transaction.checkout_name` | string | Persisted sale checkout name or resolved legacy checkout name; unattributed history remains explicitly labeled. |
| `v5_flow` | object \| null | Recorded flow {id,name,version,versionId,sessionId,kind}; null for transactions without a flow snapshot. Exposed with flow access. Historical direct transactions are not assigned a current flow retroactively. |
| `transaction.checkout_origin` | rebill \| api \| checkout \| manual \| imported \| unknown | Current charge origin: rebill, api, checkout, manual, imported or unknown. Exposed with flow access. Rebills have no new checkout visit even when historical checkout/flow attribution is retained. API includes Friendlies; absence of a checkout ID never proves a legacy checkout visit. |

**Errors**

- `400` `{"error":"A value has an invalid format."}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` {"error":"Not found"} - either the id does not exist OR it belongs to another account. The two are deliberately indistinguishable.
- `500` An unhandled database error (a non-UUID :id is the 400 above, not a 500).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- There is no zod schema on :id: a malformed id reaches Postgres and answers 400 `{"error":"A value has an invalid format."}`, not a 404 - validate the UUID yourself before calling.
- `products` is resolved by ORDER_ID, not transaction_id, so a rebill (which carries no basket of its own) shows the ORIGINAL sale's basket. Consequently the basket may not correspond 1:1 to this row's amount_cents.
- products[].amount_cents can be a cross-order MODE estimate when the stored line amount is 0 - do not reconcile it against the charge total.
- The attempts array is NOT ordered by attempt_no alone: skipped attempts are pushed to the end of the list.
- attempts are fetched WITHOUT any tenant scope (only the parent transaction lookup is scoped), so once the transaction passes the scope check the whole trail is returned.
- All bigint columns (amount_cents, refunded_cents, *_fee_cents, net_cents, attempt_txn_fees_cents) serialize as JSON STRINGS; recheck_attempts (smallint) and quantity/line_no (int) are real numbers. v3.9.6: the six fee keys are the LIVE figures re-serialized as strings (see transaction.fees, whose values are numbers).
- The static paths /v1/transactions/export and /v1/transactions/facets are matched before this parameterized route - you cannot fetch a transaction whose id is literally 'export' or 'facets'.
- - pipelineRun is decoration: a failure to read it never fails the detail (null). Its stages[].decision.reason is the operator text bounded to 80 chars; the full vocabulary (fall-through reasons, route levels, the send verdict line) is in docs/SALE_FLOW.md section 5.
- - `attribution` is NOT the transaction row's traffic_source / fbclid / ttclid / storefront_url (those four columns are unchanged and stay the "acquisition" signals of the Details tab): it is the side table's row, and on a subscription charge it is the SALE's row copied (source "rebill"), so a rebill shows the campaign that acquired the customer while its own traffic_source stays empty.
- v3.9.3: `pipelineRun` / `pipelineNames` stay one more release for API-explorer compatibility - the transaction modal now reads every run of the order from GET /v1/transactions/:id/events (scope=order) instead of the latest run of this transaction.
- Checkout subscription priority is explicit Special Pre-Auth > subscription product in the signed cart > selected Subscription product block > account product percentage attachment. Only one winning subscription is attached to a sale. Multiple signed-cart products choose the lowest sorted product UUID; conflicting selected blocks use the first matching document offer. Overlapping percentage matches choose the oldest configured matching product, then UUID.
- The v5_affiliate projection enriches merchant records with immutable attribution and cut ledger entries; list and CSV include Affiliate/public ID/status/cuts. This merchant projection is never used by the masked native affiliate workspace.
- An API key receives the transaction as stored: masked_card unmasked as stored, the raw payload and gateway bodies as received (they can hold card data: never log them). attempts[] is the cascade trail read from transaction_attempts (attempt_no, outcome, response, latency, ATRI name, pass, skip_reason, raw request / response).
- A Friendlies sale of an account without the Friendlies integration answers 404.

##### `GET /v1/transactions/:id/events`

**Scope** `transactions.read` - **Order / charge timeline (transaction modal Logs tab)**

v3.9.3 - the transaction modal's Logs tab: the SAME timeline as GET /v1/customers/:key/events (customer_events ∪ the sale pipeline runs projected as the virtual type `pipeline.run`, the same row shape, filters, server sort, server paging, facets and runNames) keyed on ONE ORDER (scope=order, default: every event of the transaction's order or of this transaction, every run of the order - refusals, retries, rebills and run 1 of a 3DS park included) or on ONE CHARGE (scope=charge: this transaction's events and runs). `scopes` carries both unfiltered sizes for the Order - This charge toggle. A run row's payload also carries `resumed_from`, `t_claim_us`, `t_first_send_us`, `t_completed_us` (v3.9.3) so the Stages modal can be fed from the row. Sort key `charge` (the row's transaction id) is accepted here and on the customer route. No PII: messages never carry an e-mail, a name or a PAN.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | transactions.id. A non-uuid value is 404 (never a Postgres cast error); a transaction of another account is 404 too. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `scope` | enum: order\|charge; default `order` | no | `order` (default) = every customer_events row whose order_id is the transaction's order OR whose transaction_id is this transaction, merged with EVERY sale pipeline run of the order (a retry, a rebill, a refusal and run 1 of a 3DS park are other transactions / no transaction of the same order; the subscription decisions hang off the order). `charge` = the rows and runs of THIS transaction only. Anything else is 400. |
| `type` | string | no | CSV of event types to keep (the closed list of api/src/db/customerEvents.ts CUSTOMER_EVENT_TYPES plus the virtual `pipeline.run`); an unknown type is 400 {"error":"Unknown event type","unknown":[...]}. |
| `q` | string | no | Case-insensitive substring of `message` (<= 200 chars). |
| `from` | string | no | ISO instant (with offset or Z): events at or after it. |
| `to` | string | no | ISO instant: events strictly before it. |
| `actor` | enum: user\|system\|api\|partner\|customer | no | Actor kind. |
| `severity` | enum: info\|warn\|error | no | Severity. |
| `subId` | uuid | no | Only the rows that reference this sub (the Subscription tab's "Logs" item). |
| `sort` | enum: at\|type\|actor\|severity\|message\|order\|charge; default `at` | no | Sort key; anything else is 400 {"error":"Invalid sort","allowed":[...]} (never silently replaced). |
| `dir` | enum: asc\|desc; default `desc` | no | Direction (ties broken by `at desc, id desc`). |
| `limit` | integer; default `50` | no | 1..10000. |
| `offset` | integer; default `0` | no | >= 0. |

**Response**

```json
{
 "rows": [
  {
   "id": "6f1a2b3c-4d5e-4f60-8a7b-8c9d0e1f2a3b",
   "at": "2026-09-26T15:07:05.400Z",
   "source": "run",
   "actor_kind": "system",
   "actor": "rebill",
   "acting_as": null,
   "event_type": "pipeline.run",
   "severity": "warn",
   "message": "Sale pipeline run (rebill): declined",
   "payload": {
    "outcome": "declined",
    "refused_by": null,
    "fell_through": false,
    "flow": "rebill",
    "channel": "rebill",
    "run_no": 1,
    "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
    "final_trip_id": null,
    "amount_cents": 1999,
    "card_brand": "Visa",
    "total_us": 2910000,
    "resumed_from": null,
    "t_claim_us": 260000,
    "t_first_send_us": 410000,
    "t_completed_us": 2900000,
    "stages": []
   },
   "order_id": "ORD-118842",
   "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
   "sub_id": null,
   "subscription_id": null,
   "entry_id": null,
   "schedule_id": null,
   "refund_id": null,
   "mid_id": null,
   "trip_id": "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5",
   "rejection_id": null,
   "decision_id": null,
   "session_id": null,
   "note_id": null,
   "blacklist_id": null,
   "total": 4
  },
  {
   "id": "184",
   "at": "2026-09-26T15:07:05.210Z",
   "source": "event",
   "actor_kind": "system",
   "actor": "dispatch",
   "acting_as": null,
   "event_type": "sub.charge.declined",
   "severity": "warn",
   "message": "Charge #2 declined on MID US 02: Insufficient funds [nsf/soft] -> retry 1 in 24 h",
   "payload": {
    "rebill_number": 2,
    "amount_cents": 1999,
    "decline_category": "nsf"
   },
   "order_id": "ORD-118842",
   "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
   "sub_id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
   "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
   "entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
   "schedule_id": null,
   "refund_id": null,
   "mid_id": "d4e5f6a7-b8c9-4012-8345-6789abcdef01",
   "trip_id": null,
   "rejection_id": null,
   "decision_id": null,
   "session_id": null,
   "note_id": null,
   "blacklist_id": null,
   "total": 4
  }
 ],
 "total": 4,
 "facets": [
  {
   "type": "sub.charge.planned",
   "n": 2
  },
  {
   "type": "pipeline.run",
   "n": 1
  },
  {
   "type": "sub.charge.declined",
   "n": 1
  }
 ],
 "runNames": {
  "trips": {
   "7a1b2c3d-4e5f-4061-8273-90a1b2c3d4e5": "Main Rebill"
  },
  "mids": {}
 },
 "scopes": {
  "order": 4,
  "charge": 2
 },
 "scope": "order",
 "order": {
  "id": "ORD-118842"
 },
 "transaction": {
  "id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111"
 },
 "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The customer route's row shape: {id, at, source ('event' \| 'run'), actor_kind, actor, acting_as, event_type, severity, message, payload, order_id, transaction_id, sub_id, subscription_id, entry_id, schedule_id, refund_id, mid_id, trip_id, rejection_id, decision_id, session_id, note_id, blacklist_id, total}. A run row's payload = {outcome, refused_by, fell_through, flow, channel, run_no, trip_id, final_trip_id, amount_cents, card_brand, total_us, resumed_from, t_claim_us, t_first_send_us, t_completed_us, stages}. |
| `total` | integer | Rows matching the filters in the requested scope (every page). |
| `facets` | array | [{type, n}] over the WHOLE requested scope (unfiltered), most frequent first - the type filter's options. |
| `runNames` | object | {trips: {id: name}, mids: {id: name}} for the run rows of the page. |
| `scopes` | object | {order, charge} - the UNFILTERED size of each scope, whatever `scope` was asked (the Order - This charge toggle's pills). |
| `scope` | string | The scope answered: 'order' \| 'charge'. |
| `order` | object | {id} - the transaction's order id. |
| `transaction` | object | {id} - the transaction the timeline was keyed on (a row whose transaction_id differs is another charge of the order: a retry, a rebill). |
| `timezone` | string | The engine timezone (America/New_York), for the day labels. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a bad instant / limit / actor / severity / scope; {"error":"Unknown event type","unknown":[...]}; {"error":"Invalid sort","allowed":[...]}.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` {"error":"Not found"} - no transaction of the caller's account has this id (or the id is not a uuid).
- `500` {"error":"Internal Server Error","requestId":"<id>"} - unexpected failure (logged with the requestId).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- The order scope is the default on purpose: the subscription decisions (sub.charge.planned / replanned, sub.paused / cancelled...) carry no transaction id, and a retry / a rebill is another transaction of the same order - a charge-only view would miss them.
- Runs are kept 30 days (jobs/binDecisionsRetention): a charge older than that has its customer_events rows but no `pipeline.run` row any more.
- Same 400 contract as the customer route: an unknown type, a sort outside at|type|actor|severity|message|order|charge, a bad scope - refused before any database read.

##### `GET /v1/transactions/:id/events/export.csv`

**Scope** `transactions.read` - **Order / charge timeline as CSV**

v3.9.3 - the same scoped timeline as GET /v1/transactions/:id/events as one CSV file: every row matching the filters (<= 10 000, OLDEST first so the file reads as a story), UTF-8 with BOM, CRLF, the customer CSV's columns (at, actor_kind, actor, acting_as, event_type, severity, message, order_id, transaction_id, sub_id, subscription_id, entry_id, schedule_id, refund_id, mid_id, trip_id, rejection_id, decision_id, session_id, note_id, blacklist_id, payload - a run row's stages left out). Cells starting with = + - @ are prefixed with an apostrophe.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | transactions.id. A non-uuid value is 404 (never a Postgres cast error); a transaction of another account is 404 too. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `scope` | enum: order\|charge; default `order` | no | `order` (default) = every customer_events row whose order_id is the transaction's order OR whose transaction_id is this transaction, merged with EVERY sale pipeline run of the order (a retry, a rebill, a refusal and run 1 of a 3DS park are other transactions / no transaction of the same order; the subscription decisions hang off the order). `charge` = the rows and runs of THIS transaction only. Anything else is 400. |
| `type` | string | no | CSV of event types to keep (the closed list of api/src/db/customerEvents.ts CUSTOMER_EVENT_TYPES plus the virtual `pipeline.run`); an unknown type is 400 {"error":"Unknown event type","unknown":[...]}. |
| `q` | string | no | Case-insensitive substring of `message` (<= 200 chars). |
| `from` | string | no | ISO instant (with offset or Z): events at or after it. |
| `to` | string | no | ISO instant: events strictly before it. |
| `actor` | enum: user\|system\|api\|partner\|customer | no | Actor kind. |
| `severity` | enum: info\|warn\|error | no | Severity. |
| `subId` | uuid | no | Only the rows that reference this sub (the Subscription tab's "Logs" item). |

**Response**

```json
at,actor_kind,actor,acting_as,event_type,severity,message,order_id,transaction_id,sub_id,subscription_id,entry_id,schedule_id,refund_id,mid_id,trip_id,rejection_id,decision_id,session_id,note_id,blacklist_id,payload
2026-09-26T15:07:05.210Z,system,dispatch,,sub.charge.declined,warn,"Charge #2 declined on MID US 02: Insufficient funds [nsf/soft] -> retry 1 in 24 h",ORD-118842,c0ffee00-aaaa-4bbb-8ccc-dddd00001111,2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f,a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33,0f1e2d3c-4b5a-4968-8776-655443322110,,,d4e5f6a7-b8c9-4012-8345-6789abcdef01,,,,,,,"{""rebill_number"":2,""amount_cents"":1999,""decline_category"":""nsf""}"
```

| response field | type | description |
|---|---|---|
| `(body)` | text/csv | Content-Disposition: attachment; filename="order-events-<order id>.csv" (scope=order) or "charge-events-<transaction id>.csv" (scope=charge). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a bad instant / limit / actor / severity / scope; {"error":"Unknown event type","unknown":[...]}; {"error":"Invalid sort","allowed":[...]}.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` {"error":"Not found"} - no transaction of the caller's account has this id (or the id is not a uuid).
- `500` {"error":"Internal Server Error","requestId":"<id>"} - unexpected failure (logged with the requestId).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Ignores sort / dir / limit / offset: the whole filtered set, oldest first, capped at 10 000 rows.

##### `POST /v1/transactions/:id/retry`

**Scope** `charges.write` - **Retry a declined card sale**

Charges again the card on file of ONE declined or errored card sale of the account, for its original amount and currency, on the route you choose: an active ATRI of the account (its normal routing and cascade) or one activated gateway (MID) of the account (pinned: that gateway is the only attempt). It runs as the account through the standard charge engine (channel retry, source dashboard) and creates a new transaction row. Returns whether it approved, the gateway that answered and the new transaction id.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The declined or errored card transaction to retry. Its order id selects the card on file (any card sale of that order that stored a card number). Another account's id answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `atriId` | uuid | no | An active ATRI of the account: the retry follows its routing and cascade. Send exactly one of atriId or midId. |
| `midId` | uuid | no | An activated gateway (MID) of the account: the retry is pinned to it (one attempt, no cascade). The ATRI used as routing context is the transaction's own ATRI when it contains this gateway, else the account default ATRI containing it, else the oldest active ATRI containing it. Send exactly one of atriId or midId. |

**Request body**

```json
{
  "midId": "00000000-0000-4000-8000-000000000002"
}
```

**Response**

```json
{
  "ok": true,
  "approved": false,
  "midName": "Demo Gateway 3",
  "amountCents": 4999,
  "declineReason": "DECLINE (200)",
  "transactionId": "00000000-0000-4000-8000-000000000003"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true whenever the retry was evaluated (approved, declined or refused before any gateway). |
| `approved` | boolean | The retry was approved. |
| `midName` | string \| null | Display name of the gateway (MID) that answered; null for a refusal before any gateway. |
| `amountCents` | integer | Amount charged in cents: always the original transaction amount. |
| `declineReason` | string \| null | Decline or refusal text when approved is false. |
| `rejected` | object (only on a refusal before any gateway) | {family, reason}, exactly as on POST /v1/charge: the account rules refused the retry before any gateway (blacklist, filter, velocity guard, BIN scrub, card pre-check, card cooldown, 3-D Secure policy, checkout limit, test card). No transaction row is created; transactionId is null. |
| `transactionId` | uuid \| null | The NEW transaction row the retry created (channel retry). null with `rejected`. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten>}: atriId or midId is not a UUID; {"error":"Choose exactly one route: atriId or midId"}: neither or both were sent; {"error":"A value has an invalid format."}: the path id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"}: the caller resolves to no account.
- `404` {"error":"Not found"}: unknown transaction, or one of another account (deliberately the same answer).
- `422` The transaction cannot be retried: {"error":"Verification charges cannot be retried outside the pre-auth workflow"}, "Only card transactions can be retried" (a wallet or non-card sale), "Transaction is already approved", "Transaction was charged back", "Transaction was refunded", "Transaction is still in progress" (pending), "Only declined or errored transactions can be retried" (for example status unknown), "No card on file for this order".
- `422` The route is unusable: {"error":"Unknown ATRI"} (not an active ATRI of the account), "Unknown MID", "MID is disabled", "MID is not in any active ATRI".
- `422` {"error":"<reason>"} or {"error":"Retry refused"}: the engine refused before evaluating anything (no card on file, order not of this account). Nothing was attempted and no row was created.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- A decline is a 200 with approved:false, and a refusal by the account rules is a 200 with approved:false plus `rejected`. Only the refusals listed under 422 mean nothing was evaluated. Always read `approved`.
- NOT idempotent: every call is a new charge attempt (the internal idempotency key includes the time). Calling twice retries twice.
- midId pins the attempt: no other gateway, no cascade. atriId runs the ATRI normal strategy, cascade included.
- Status unknown (an ambiguous gateway timeout) is refused on purpose: the original may have been approved by the issuer.
- Amount and currency are the original transaction's. To charge another amount use POST /v1/transactions/charge.
- The new row appears in GET /v1/transactions with channel retry and source dashboard. Blacklist, BIN scrub and the other account rules apply to it.
- A retry.requested event is written on the customer timeline of the source transaction before the charge.
- There is no bulk retry endpoint: retry several transactions by calling this route once per transaction (the dashboard Retry console does the same, and filters out the ineligible ones first).

##### `GET /v1/transactions/:transactionId`

**Scope** `transactions.read` - **Get a transaction (partner summary with refund history)**

The partner summary of one transaction (camelCase, masked card, billing and shipping, refund history, optional identifier checks); the full dashboard record (attempts, basket, 3DS, fees, pipeline, attribution) is GET /v1/transactions/:id/details. Direct lookup of one transaction by its id - the same PCI-safe per-transaction shape as POST /v1/refund/search and POST /v1/transactions, PLUS `refunds[]`: every refund attempt on it (newest first) with its refundId, chargeback / dispute / TEST flags. Built so the partner never has to go through the search endpoint (and its optional parameters) to read one known transaction.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | string (uuid) | **yes** | REQUIRED. Our transaction id. Not a uuid -> 400. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `cardLast4` | string (4 digits) | no | Optional validation: must equal the card's last 4 -> else 422 with `mismatched: ["cardLast4"]`. |
| `cardBin` | string (6 digits) | no | Optional validation against the card's first 6. |
| `amount` | number (major units) | no | Optional validation: exact amount match (cents compared). |
| `email` | string | no | Optional validation: case-insensitive equality with the transaction email. |
| `orderId` | string | no | Optional validation: exact orderId match. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Response**

```json
{
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "orderId": "ORD-100482",
 "amount": 49.99,
 "currency": "USD",
 "status": "approved",
 "approved": true,
 "actionType": "straight_sale",
 "operation": "CHARGEBACK",
 "customerId": "cus_3f9c1e7a2b6d4081",
 "refundStatus": "refunded",
 "chargedBack": true,
 "disputeKind": null,
 "card": "411111......1111",
 "email": "dana.reyes@example.com",
 "refunded": 49.99,
 "refundable": 0,
 "refunds": [
  {
   "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884",
   "status": "approved",
   "success": true,
   "method": "external",
   "operationType": "CHARGEBACK",
   "amount": 49.99,
   "fee": 13.0,
   "isChargeback": true,
   "disputeKind": null,
   "isTest": false,
   "requestedBy": "agent@partner.com",
   "reason": "chargeback received",
   "createdAt": "2026-09-02T10:11:12.000Z",
   "completedAt": "2026-09-02T10:11:12.300Z"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `(all search fields)` | - | Identical to one element of POST /v1/refund/search `transactions[]` - see that endpoint for every field, `actionType` and the null matrix. |
| `refunds` | object[] | Every refund attempt on this transaction, newest first (empty array when none). |
| `refunds[].refundId` | string (uuid) | The id POST /v1/refund/chargeback and POST /v1/refund/cancel-test take. |
| `refunds[].status` | string | `approved` \| `declined` \| `error` \| `pending` \| `cancelled` (a cancelled TEST refund). |
| `refunds[].success` | boolean | true = the refund counts (money booked). false for declined/errored/cancelled rows. |
| `refunds[].operationType` | string | `REFUND` \| `VOID` \| `CHARGEBACK` - the partner-model operation of this refund row (void method -> VOID, chargeback-marked -> CHARGEBACK). |
| `refunds[].method` | string \| null | `refund` (gateway) \| `void` \| `external` (no provider call: partner-side refund, chargeback mark, or dead-MID booking) \| `test`. |
| `refunds[].amount / fee` | number (major units) | Refund amount and the per-brand Ethoca/RDR fee, in dollars. |
| `refunds[].isChargeback` | boolean | true = this refund is classified as a chargeback (the transaction's `chargedBack` is true iff any successful refund has this). |
| `refunds[].disputeKind` | string \| null | `rdr` \| `ethoca` \| null. |
| `refunds[].isTest` | boolean | true = created with the TEST key (cancellable; never blacklisted anyone). |
| `refunds[].requestedBy / reason` | string \| null | The free-text attribution stored at refund time. |
| `refunds[].createdAt / completedAt` | string (ISO 8601) \| null | When the refund was claimed / finished. |

**Errors**

- `400` `transactionId` is not a uuid, or an identifier has a bad format (cardLast4 not 4 digits, ...).
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `transactions.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{ "error": "Transaction not found" }` (also for non card/wallet rows).
- `422` `{ "error": "Transaction identifiers do not match", "mismatched": ["cardLast4", ...] }` - the transaction exists but a validation identifier differs; nothing else is returned.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- Validation identifiers are optional and independent - send only what you hold. A 422 lists EVERY mismatching field, not just the first.
- `refunds[]` includes cancelled TEST rows (status `cancelled`, success false) - filter on `success` for what actually counts.
- A transaction is `chargedBack` iff at least one SUCCESSFUL refund has `isChargeback: true`; a cancelled test chargeback no longer counts.
- Rate-limited like the other partner endpoints (20/min per IP by default) - it is not a sync mechanism; use POST /v1/transactions for bulk.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.

##### `POST /v1/transactions/:transactionId/note`

**Scope** `transactions.write` - **Add a note to a transaction**

Writes a free-form note on a charge - the alert id the partner was given, what the issuer said, what the customer was told. It is the same thread the dashboard shows on the transaction (transaction_notes), appears on the customer's timeline as `note.added`, and is the context a dispute is actually won with. Notes were readable in the dashboard and writable only there; this is the refund team's way in. Nothing about the money changes.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | The transaction to act on. Must belong to the key's account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |
| `cardLast4` | string (4 digits) | no | Optional identifier check. Any mismatch answers 422 and nothing is written. |
| `cardBin` | string (6 digits) | no | Optional identifier check. |
| `amount` | number (major units) | no | Optional identifier check against the charge's amount. |
| `email` | string | no | Optional identifier check. |
| `orderId` | string | no | Optional identifier check. |
| `note` | string (1-4000) | **yes** | The note. Kept verbatim; the customer-timeline excerpt redacts an e-mail or a PAN-like run. |
| `author` | string; default `partner-api` | no | Who wrote it. Defaults to `clientId`, else 'partner-api'. |

**Response** `201`

```json
{
 "noteId": "00000000-0000-4000-8000-000000000001",
 "transactionId": "00000000-0000-4000-8000-000000000001",
 "note": "Customer contacted support.",
 "author": "support@example.com",
 "createdAt": "2026-10-18T12:00:00.000Z"
}
```

**Errors**

- `400` `note` is missing, empty or longer than 4000 characters.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `transactions.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` No such transaction in this key's scope.
- `422` `{ error: 'Transaction identifiers do not match', mismatched: [...] }` - one of the optional identifiers disagreed with the row. Nothing was written.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- This is the one public note thread of a transaction (the refund-desk note routes of the dashboard are not public). Delete a note with DELETE /v1/transactions/notes/:noteId.

##### `GET /v1/transactions/:transactionId/notes`

**Scope** `transactions.read` - **Read a transaction's note thread**

The thread the dashboard shows on a transaction, oldest first - what was written by whoever handled the charge, here or there. It is the pair of POST /v1/transactions/:transactionId/note: being able to add a note and not to read the thread back is half an endpoint. Notes are plain text and are not redacted on this surface (the customer TIMELINE excerpt is).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | The transaction to act on. Must belong to the key's account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |
| `cardLast4` | string (4 digits) | no | Optional identifier check. Any mismatch answers 422 and nothing is written. |
| `cardBin` | string (6 digits) | no | Optional identifier check. |
| `email` | string | no | Optional identifier check. |
| `orderId` | string | no | Optional identifier check. |
| `amount` | number (major units) | no | Optional identifier check against the charge's amount. Identifiers are passed in the QUERY on this endpoint, as on GET /v1/transactions/:transactionId. |

**Response** `200`

```json
{
 "transactionId": "00000000-0000-4000-8000-000000000001",
 "notes": []
}
```

**Errors**

- `400` `{"error":"Invalid request","details":{"transactionId":"must be a uuid"}}` when :transactionId is not a UUID; `{"error":"Invalid request","details":{...}}` when a field fails its schema.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `transactions.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` No such transaction in this key's scope.
- `422` `{ error: 'Transaction identifiers do not match', mismatched: [...] }` - one of the optional identifiers disagreed with the row. Nothing was written.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- This is the one public note thread of a transaction (the refund-desk note routes of the dashboard are not public). Delete a note with DELETE /v1/transactions/notes/:noteId.

##### `POST /v1/transactions/bulk`

**Scope** `transactions.write` - **Bulk-edit transactions**

Applies ONE action to a list of transactions the caller may see: blacklist the customers (email + card), attach the sales to a subscription product, cancel the subs of the orders, or add a note. Rows are processed sequentially, each checked against the caller's tenant scope before anything is written; out-of-scope or inapplicable rows are counted as skipped. Returns done / skipped / errors counts.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | uuid[] (1-10000) | **yes** | Transaction ids; ids that are not the account's are counted in skipped. |
| `action` | enum: blacklist \| attach_subscription \| cancel_subs \| note | **yes** | blacklist: blacklist the customer e-mail and card and end their live subscriptions; attach_subscription: attach each sale to subscriptionId; cancel_subs: cancel the active, paused or failed subscriptions of each order; note: add the same note to each transaction. |
| `reason` | string (0-200, trimmed); default `Bulk blacklist` | no | Reason for blacklist / cancel_subs. |
| `subscriptionId` | uuid | no | Subscription product id, required for attach_subscription (not an opt-in only product). |
| `note` | string (1-2000, trimmed) | no | Note text, required for action note. |
| `requestId` | uuid | no | Makes the blacklist writes idempotent per transaction (transactions:<requestId>:<id>). |

**Request body**

```json
{
 "ids": [
  "7a8b9c0d-1e2f-4a3b-9c4d-5e6f7a8b9c0d",
  "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
 ],
 "action": "blacklist",
 "reason": "Friendly-fraud ring 2026-09"
}
```

**Response**

```json
{
 "done": 2,
 "skipped": 0,
 "errors": []
}
```

| response field | type | description |
|---|---|---|
| `done` | integer | Rows where the action was applied. |
| `skipped` | integer | Rows left alone: out of tenant scope / unknown id, blacklist with neither email nor card, attach on a non-attachable or foreign sale (or attach returned nothing), cancel_subs with no active/paused/failed sub for the order. |
| `errors` | array of string | Up to 20 '<first 8 chars of id>: <message>' for rows that threw (e.g. a DB constraint). Rows beyond 20 errors are still processed but not listed. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body fails the schema.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `422` `{"error":"A note is required"}`; `{"error":"Unknown subscription"}`; `{"error":"This subscription product is opt-in only: it is attached only to sales whose customer opted into it at checkout"}`.
- `500` Internal Server Error with a requestId.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Synchronous and capped by the request time: for large selections use the background POST /v1/transactions/bulk-jobs (resumable, idempotent by requestId).
- Not atomic and not transactional: rows are processed one by one; a failure on row 50 leaves rows 1-49 done. Re-running is safe (each action is idempotent per row: blacklist upserts, attach skips already-attached sales, cancel skips cancelled subs, note adds ANOTHER note).
- Foreign / unknown ids are silently counted in `skipped` - never a 404. done + skipped + errors.length (<=20) = ids.length only when fewer than 20 rows threw.
- blacklist adds BOTH the email and the full card PAN (from raw_payload) to the account blacklist as source 'manual' - future charges by that customer/card on this account are refused before any MID (a rejection, never a decline -
- attach_subscription creates a rebill sub (source 'manual', by the operator) for each sale; the sale must be an approved card sale of the account with a card-on-file.
- cancel_subs cancels every rebill_sub of the transaction's ORDER (status active / paused / failed) with actor 'user'; a row whose order has no such sub is skipped.
- The 'note' action appends a note per transaction every time - calling twice duplicates notes.
- 10 000 sequential rows can take minutes; the request stays open (no background job).
- One audit row for the whole call (action 'create', page 'transactions', objectId null) - per-row changes are visible only in the respective tables.
- The note action uses one atomic batch for notes and their redacted timeline events; a database failure rolls the batch back. Duplicate input IDs still create duplicate notes. Other bulk actions retain their own execution contracts. Never automatically repeat an ambiguous mutation response.
- errors[] holds at most 20 messages; a blacklist whose subscription cleanup is still pending is reported there.

##### `GET /v1/transactions/bulk-jobs`

**Scope** `transactions.read` - **List transaction bulk jobs**

Lists the caller's last 20 transaction bulk jobs of the account, queued and running first, then newest.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000401",
      "request_id": "00000000-0000-4000-8000-000000000402",
      "action": "blacklist",
      "reason": "Fraud ring",
      "subscription_id": null,
      "status": "queued",
      "total": 2,
      "processed": 0,
      "succeeded": 0,
      "failed": 0,
      "skipped": 0,
      "units_processed": 0,
      "cancel_requested": false,
      "cleanup_pending": false,
      "error": null,
      "created_at": "2026-11-24T10:00:00.000Z",
      "updated_at": "2026-11-24T10:00:00.000Z",
      "finished_at": null,
      "errors": [],
      "result": {
        "done": 0,
        "skipped": 0
      }
    }
  ]
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.

##### `POST /v1/transactions/bulk-jobs`

**Scope** `transactions.write` - **Start a transaction bulk job**

Admits a background job that applies one action to up to 10,000 transactions of the account and answers 202 with the job. Poll GET /v1/transactions/bulk-jobs/:id, then read GET /v1/transactions/bulk-jobs/:id/result. One customer, subscription or transaction bulk job at a time per account. Get the ids of a filtered list with GET /v1/transactions/ids.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | uuid[] (1-10000) | **yes** | Transaction ids of the account. Duplicates are merged; an id that is not one of the account's transactions is skipped as Transaction not found. |
| `action` | enum: blacklist \| attach_subscription \| cancel_subs | **yes** | blacklist: blacklist the customer e-mail and card of each transaction and end their live subscriptions. attach_subscription: attach the sale to the subscription product subscriptionId (creates the subscription). cancel_subs: cancel the active, paused or failed subscriptions of each transaction's order. |
| `reason` | string (0-200, trimmed) | no | Reason stored on the blacklist rows and subscription events (default `Bulk blacklist` for blacklist). |
| `subscriptionId` | uuid | no | Subscription product id. Required when action is attach_subscription; the product must be active, not deleted and not opt-in only. |
| `requestId` | uuid | **yes** | Idempotency key. Resending the same requestId with the same body returns the same job; with a different body, 409. |

**Request body**

```json
{
  "ids": [
    "00000000-0000-4000-8000-000000000501",
    "00000000-0000-4000-8000-000000000502"
  ],
  "action": "blacklist",
  "reason": "Fraud ring",
  "requestId": "00000000-0000-4000-8000-000000000402"
}
```

**Response** `202`

```json
{
  "jobId": "00000000-0000-4000-8000-000000000401",
  "job": {
    "id": "00000000-0000-4000-8000-000000000401",
    "request_id": "00000000-0000-4000-8000-000000000402",
    "action": "blacklist",
    "reason": "Fraud ring",
    "subscription_id": null,
    "status": "queued",
    "total": 2,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body fails the schema (strict: unknown fields refused; ids empty, over 10,000 or not UUIDs; action unknown; requestId missing; attach_subscription without subscriptionId: `Subscription is required`).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `409` `{"error":"Request ID already used with different input or permissions"}`; `{"error":"Another transaction, customer or subscription bulk operation is active on this account","jobId":"..."}`.
- `422` `{"error":"Subscription is unavailable for manual attachment"}` when subscriptionId is unknown, inactive, deleted or opt-in only.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Transaction background jobs are disabled"}` when background jobs are switched off on the server.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.
- If the answer is lost, resend the same body and requestId: you get the same job, never a second one.
- There is no preview for transaction bulk jobs.

##### `GET /v1/transactions/bulk-jobs/:id`

**Scope** `transactions.read` - **Read a transaction bulk job**

Reads the status and counters of one transaction bulk job (queued, running, success, partial, failed or cancelled).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000401",
    "request_id": "00000000-0000-4000-8000-000000000402",
    "action": "blacklist",
    "reason": "Fraud ring",
    "subscription_id": null,
    "status": "success",
    "total": 2,
    "processed": 2,
    "succeeded": 2,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": "2026-11-24T10:00:07.000Z",
    "errors": [],
    "result": {
      "done": 2,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- job.errors is always [] here: read the failures with GET /v1/transactions/bulk-jobs/:id/errors.
- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.

##### `POST /v1/transactions/bulk-jobs/:id/cancel`

**Scope** `transactions.write` - **Cancel a transaction bulk job**

Requests cancellation of a queued or running transaction bulk job and returns the job. Transactions already processed stay changed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000401",
    "request_id": "00000000-0000-4000-8000-000000000402",
    "action": "blacklist",
    "reason": "Fraud ring",
    "subscription_id": null,
    "status": "running",
    "total": 2,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": true,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- Idempotent; on a finished job it changes nothing and returns the job as it is.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `GET /v1/transactions/bulk-jobs/:id/errors`

**Scope** `transactions.read` - **List a transaction bulk job failures**

Pages the finished transactions of a job that were skipped or failed, in the order sent.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |
| `limit` | integer (1-100); default `100` | no | Page size. |

**Response**

```json
{
  "errors": [
    {
      "itemId": "00000000-0000-4000-8000-000000000502",
      "reason": "Transaction not found"
    }
  ]
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `400` `{"error":"Invalid pagination"}` when offset or limit is out of bounds.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- itemId is the transaction id. Only finished rows appear.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `GET /v1/transactions/bulk-jobs/:id/result`

**Scope** `transactions.read` - **Read a transaction bulk job result**

Returns the per-transaction results in the order sent and the done, skipped and failed counters.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "results": [
    {
      "id": "00000000-0000-4000-8000-000000000501",
      "ok": true,
      "changed": 1,
      "subs": 0,
      "subsRefused": 0,
      "subsOtherProducts": 0,
      "pans": 1,
      "subsEnded": 1
    },
    {
      "id": "00000000-0000-4000-8000-000000000502",
      "ok": false,
      "skipped": "Transaction not found",
      "changed": 0,
      "subs": 0,
      "subsRefused": 0,
      "subsOtherProducts": 0,
      "pans": 0,
      "subsEnded": 0
    }
  ],
  "done": 1,
  "skipped": 1,
  "failed": 0
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- results[].id is the transaction id. Rows not processed yet keep ok false with no reason.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `POST /v1/transactions/charge`

**Scope** `charges.write` - **Charge one manual card sale (ATRI or a pinned MID)**

Charges one manual card sale with a full card number from the account side (an ATRI or one pinned MID, like Add charge in the dashboard); integrations charging orders use POST /v1/charge. Creates and charges a new card sale for the account with a full card number: the customer and order fields of a POST /v1/charge single order plus the card, routed by an active ATRI of the account, pinned on one activated gateway (MID) of the account, or sent to the account default ATRI. It runs as the account through the standard charge engine (channel and source dashboard, no API key on the row). The stored order becomes the card on file for later retries and subscription charges. Idempotent per account and orderId. Returns the standard order result plus the transaction id.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | string | **yes** | 1 to 128 characters. Idempotency key with the account: sending the same orderId again replays the stored result instead of charging again. |
| `amount` | number | **yes** | MAJOR units (49.99 means $49.99), not cents. Positive, finite, at least 0.01 and no finer than one cent (at most 2 decimals), else 400. |
| `currency` | string; default `USD` | no | Exactly 3 characters (the value itself is not checked against a list). |
| `description` | string | no | At most 256 characters. Sent to the gateway as the order description. |
| `firstName` | string | no | At most 128 characters. |
| `lastName` | string | no | At most 128 characters. |
| `email` | string | no | Valid e-mail, at most 256 characters. Also what the blacklist and the account filters match. |
| `address1` | string | no | Billing street, at most 256 characters (address verification). |
| `city` | string | no | At most 128 characters. |
| `state` | string | no | At most 64 characters. |
| `zip` | string | no | At most 32 characters. |
| `country` | string | no | At most 64 characters. |
| `ipaddress` | string | no | Customer IP for the gateway fraud scoring, at most 64 characters. |
| `phone` | string | no | At most 32 characters. |
| `useragent` | string | no | Customer browser user agent, at most 1024 characters. |
| `trafficSource` | string | no | Attribution label (meta, tiktok, ...), at most 32 characters; an invalid value is dropped, never a 400. |
| `storefrontUrl` | string | no | Storefront attribution, at most 256 characters; an invalid value is dropped, never a 400. |
| `ccnumber` | string | **yes** | Card number. Spaces and dashes are removed, then 12 to 19 digits are required. Never echoed. |
| `ccexp` | string | **yes** | Expiry as MMYY, exactly 4 digits. |
| `cvv` | string | **yes** | Security code: spaces and dashes removed, then 3 or 4 digits. |
| `atriId` | uuid | no | Route through this active ATRI of the account. Not with midId. When neither is sent the account default ATRI is used. |
| `midId` | uuid | no | Pin the sale on this activated gateway (MID) of the account: one attempt, no cascade. The routing context is the account default ATRI containing it, else the oldest active ATRI containing it. Not with atriId. |
| `products` | array | no | Optional basket for REPORTING only, never sent to the gateway: up to 200 lines of {id, name, slug, url, quantity, amount} where amount is the LINE total in major units (unitCost x quantity is used when amount is absent). A line without id, name, slug or url is skipped. Read from the raw body, never a 400. |
| `products[].id` | string | no | Product id of the line (any of id, name, slug or url is enough; a line with none of them is skipped). Reporting only, never sent to the gateway. |
| `products[].name` | string | no | Product name. Reporting only, never sent to the gateway. |
| `products[].slug` | string | no | Product slug (handle). Reporting only, never sent to the gateway. |
| `products[].url` | string | no | Product page URL. Reporting only, never sent to the gateway. |
| `products[].quantity` | number | no | Quantity of the line. Reporting only, never sent to the gateway. |
| `products[].amount` | number | no | LINE total in major units (49.99 = $49.99). Reporting only, never sent to the gateway. |
| `products[].unitCost` | number | no | Unit price in major units; used as unitCost x quantity when amount is absent. Reporting only, never sent to the gateway. |
| `attribution / utm_* / click ids` | object \| string | no | Optional campaign attribution, same contract as on POST /v1/charge (an `attribution` object or the flat utm_source, utm_medium, utm_campaign, gclid, ... keys). Read from the raw body after the transaction exists; never a 400. |

**Request body**

```json
{
  "orderId": "demo-order-0042",
  "amount": 49.99,
  "currency": "USD",
  "description": "Demo Hoodie",
  "firstName": "Jane",
  "lastName": "Example",
  "email": "jane@example.com",
  "address1": "1 Main St",
  "city": "Austin",
  "state": "TX",
  "zip": "78701",
  "country": "US",
  "phone": "+15555550100",
  "ccnumber": "4111 1111 1111 1111",
  "ccexp": "1230",
  "cvv": "123",
  "atriId": "00000000-0000-4000-8000-000000000004",
  "products": [
    {
      "id": "demo-hoodie",
      "name": "Demo Hoodie",
      "quantity": 1,
      "amount": 49.99
    }
  ]
}
```

**Response**

```json
{
  "isSuccess": true,
  "orderId": "demo-order-0042",
  "orderIdSupplier": "1000000001",
  "declineReason": null,
  "midIdUsed": "00000000-0000-4000-8000-000000000002",
  "midNameUsed": "Demo Gateway 3",
  "transactionId": "00000000-0000-4000-8000-000000000003"
}
```

| response field | type | description |
|---|---|---|
| `isSuccess` | boolean | Approved. |
| `orderId` | string | Echo of the orderId. |
| `orderIdSupplier` | string \| null | Gateway transaction id. |
| `declineReason` | string \| null | Decline or refusal text when isSuccess is false. |
| `midIdUsed` | uuid \| null | Gateway (MID) that answered. |
| `midNameUsed` | string \| null | Display name of that gateway. |
| `rejected` | object (optional) | {family, reason}: refused by the account rules before any gateway (blacklist, filter, velocity_guard, bin_scrub, card_precheck, card_cooldown, three_ds_policy, three_ds_abandoned, checkout_limit, test_card). No transaction row exists; transactionId is null. |
| `scrubbed` | boolean (optional) | true when the BIN scrub refused the order (same fact as rejected.family bin_scrub). |
| `preferredMidApplied` | boolean (optional) | Present when a gateway was pinned with midId: whether the attempt went to it. |
| `threeDs` | object (optional) | Present when the account 3-D Secure integration took part: sessionId, provider, status, liabilityShift, and pending/next/expiresAt when a browser step is required (the order is then NOT charged). |
| `isTest` | boolean (optional) | true when a simulated test card was used: no gateway was called, no money moved. |
| `processing` | boolean (optional) | A gateway request exists but its outcome is not confirmed. Do not retry; read the transaction later. |
| `reconciliationRequired` | boolean (optional) | Comes with processing: the outcome is being reconciled. |
| `transactionId` | uuid \| null | The transaction row of this order (also on a replay of the same orderId); null for a refusal before any gateway. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten>}: a missing or invalid orderId, amount (positive, at least 0.01, at most 2 decimals), ccnumber (12 to 19 digits), ccexp (MMYY), cvv (3 or 4 digits), atriId or midId not a UUID, an invalid e-mail or a field too long. Messages only: card values are never echoed.
- `400` {"error":"Choose an ATRI or a MID, not both"}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"}: the caller resolves to no account.
- `422` The route is unusable: {"error":"Unknown ATRI"}, "Unknown MID", "MID is disabled", "MID is not in any active ATRI", "No default ATRI configured" (neither atriId nor midId and the account has no active default ATRI).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- `amount` is in major units while amounts the API returns are integer cents: 4999 here charges $4,999.00.
- A decline is a 200 with isSuccess:false; a refusal by the account rules is a 200 with `rejected`. Only validation and route problems are 4xx.
- Idempotent per account and orderId: the same orderId again does not charge twice, it replays the first result (a decline included). Use a new orderId to charge again.
- The stored order keeps the validated card digits: this row is the card on file used by POST /v1/transactions/:id/retry and by subscription charges.
- The account rules of POST /v1/charge apply: blacklist, filters, BIN scrub, card cooldown, 3-D Secure policy. If the 3-D Secure integration needs a browser step, the order is parked (threeDs.pending) and is not charged; keep that integration from requiring a browser step for sales created here.
- The row is attributed to the account with no API key; channel and source are dashboard, and the caller identity is stored as chargedBy.
- The `products` basket is reporting data only; the gateway receives the usual line items.

##### `GET /v1/transactions/export`

**Scope** `transactions.read` - **Export transactions CSV**

Download the CURRENT filter set as a CSV attachment. Identical filtering, date range, account scope AND order (`sort`/`dir`) as GET /v1/transactions, but no paging - capped at the first 100,000 rows of the requested order (the 100,000 most recent, by default). v3.9.15 - spreadsheet formula injection: a TEXT cell starting with = + - @, a tab or a CR that is not a plain number is prefixed with an apostrophe (the Clients export's rule, routes/v1/customers.ts csvCell): a customer-typed `=HYPERLINK(...)` name exports as `'=HYPERLINK(...)`, a phone `+33...` as `'+33...`; money and negative numbers are unchanged.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Start of the page range (inclusive): the grain's own date. A bare day is read in tz (its first millisecond). |
| `to` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | End of the page range (inclusive). A bare day is read in tz (its last millisecond). |
| `tz` | string (IANA timezone, max 64) | no | IANA timezone the days and hours are read in. Defaults to the account timezone. Must be a known zone. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `storefront` | CSV string (max 4000) | no | Store host bucket, (direct). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `checkout` | CSV of UUIDs or none | no | Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of UUIDs or none | no | Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. |
| `affiliate` | CSV of UUIDs or none | no | Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |
| `sort` | enum: created_at \| completed_at \| amount \| status \| order_id \| email \| customer \| mid \| atri \| crm \| country \| storefront \| traffic \| decline_reason \| card \| three_ds \| method \| source \| product \| subscription \| processor \| acquiring_bank \| company \| utm_source \| utm_campaign; default `created_at` | no | Sort column (nulls last, then created_at desc). |
| `dir` | enum: asc \| desc; default `desc` | no | Sort direction. |

**Response**

```json
HTTP/1.1 200 OK
content-type: text/csv; charset=utf-8
content-disposition: attachment; filename="transactions-2026-08-30.csv"

Date (UTC),Order ID,Source,Product,Product from original sale,Subscription,Cycle,Type,Status,Success,Amount,Currency,Card,Brand,Email,First name,Last name,ATRI,MID,Processor,Acquiring bank,Company,CRM,Decline reason,Supplier txn id,Refunded,Charged back,Dispute alert,Country,Traffic,Storefront,UTM source,UTM campaign,Recovery,3DS provider,3DS status,3DS flow,3DS ECI,3DS applied,3DS liability shift,3DS fee,Completed (UTC)\r\n2026-08-29T14:03:11.221Z,ORD-10482,sale,acme-hoodie,,VIP Monthly,0,sale,approved,yes,49.99,USD,4111111111111111,Visa,jane.doe@example.com,Jane,Doe,US Straight Sale,MID-EU-03,PRIORITY,SYNOVUS,STELLAR TIDE LLC,nmi,,9876543210,no,no,,US,meta,https://shop.example.com/checkout,tiktok,us_summer_broad,,evervault,Y,frictionless,05,yes,yes,0.05,2026-08-29T14:03:13.004Z\r\n2026-08-29T13:47:02.910Z,ORD-10477,sale,acme-cap,,,,sale,declined,no,129.00,USD,545454..5454,Mastercard,sam@example.com,Sam,Rivera,,,CONVESIO PAY,ADYEN,STELLAR TIDE LLC,convesio,"Insufficient funds, retry",,no,no,,US,,,,,email,,,,,,,,2026-08-29T13:47:05.118Z\r\n
```

| response field | type | description |
|---|---|---|
| `(body)` | text/csv | Not JSON. UTF-8 with a leading BOM, CRLF line endings, RFC 4180 quoting (values containing comma/quote/newline are double-quoted with "" escaping). |
| `Amount` | string | MAJOR UNITS with 2 decimals (amount_cents / 100), e.g. '49.99' - unlike every JSON route on this file, which returns cents. |
| `Success / Refunded / Charged back` | string | Booleans render as 'yes' / 'no'; nulls render as an empty cell. |
| `Source` | string | 'rebill' or 'sale', computed from the channel + rebill-named ATRI rule - this column does NOT exist in the list route's JSON. |
| `Product` | string | The first basket line's slug of the sale - on a subscription charge, the ORIGINAL sale's product (rules.md section 20: the list reads 'from <product>'). Resolved by the charge's order_id (a subscription charge reuses the sale's order_id, so the first basket line of that order IS the original sale's product) - the same subquery as GET /v1/transactions. It is Subscription / Cycle that are resolved through rebill_entries.transaction_id first, else rebill_subs.transaction_id. |
| `Product from original sale` | string | 'yes' on a subscription charge (its Product is the sale's), empty otherwise - a flag column rather than a 'from ' prefix so Product still sorts in Excel. |
| `Method` | CSV column | v3.9.8 item 1 - the payment method as the list names it, right after Currency: Apple Pay \| Google Pay for a wallet charge (METHOD_CASE - the wallet wins over the network behind it), else the card network (Visa \| Mastercard \| Amex \| Discover), else 'Card' for a card with no recognised network. Never blank on a charge. |
| `Card` | CSV column | The masked card as stored; v3.9.8 item 1 - a wallet charge (no masked card) exports the last four digits its wallet reported ('--4242', transactions.card_last4), empty when none is known. v3.9.12 - in clear (as stored) for an admin / super_admin (an API key included); first6..last4 for every other role (user): a CSV body is a string, so the export masks its own column (the admin gate's masking pass never sees it). |
| `Subscription` | string | The subscription product name on a subscription charge (and on the sale that created the sub), empty otherwise. Resolved through rebill_entries.transaction_id (the entry that charged it) first, else rebill_subs.transaction_id (the sale that created the sub) - the same lateral subquery as GET /v1/transactions; Cycle comes from that lookup too. |
| `Cycle` | string | 0 = the sale that created the sub, 1.. = the subscription charge number; empty on a plain sale. |
| `Brand` | string | The card NETWORK (db/txFilters BRAND_CASE: the stored card_brand, else the mask's BIN ranges): Visa \| Mastercard \| Amex \| Discover, empty when none is recognised. v3.9.8 item 1 - on a wallet charge it is the network behind the wallet (the Visa of an Apple Pay charge), the wallet itself being in Method. |
| `Processor / Acquiring bank` | string | - the two columns right after MID: the reference names behind the charge (the final MID's processor / acquiring bank, else the wallet provider's), as stored ('PRIORITY', 'SYNOVUS'); empty when the gateway carries none. |
| `UTM source / UTM campaign` | string | - two columns right after Storefront: the attribution row's utm_source / utm_campaign (a subscription charge exports its sale's copy), empty cells when the charge has no row. RFC-4180 quoted when a value holds a comma. |
| `Company` | string | - the third reference column, right after Acquiring bank: the company (legal entity) behind the charge's gateway (the final MID's, else the wallet provider's), as stored ('STELLAR TIDE LLC'); empty when the gateway carries none. |
| `Recovery` | string | 'sms' \| 'email' \| 'both' when the sale was won back by an abandoned-cart relance (transactions.recovery_source); empty on any other charge. |
| `3DS provider` | string | The 3-D Secure provider that authenticated the charge (three_ds_provider); empty when 3DS was not attempted - the seven 3DS columns are then all empty. |
| `3DS status` | string | EMV transStatus (Y / A / N / U / R / I) or 'skipped', 'pending', 'fallback', 'holdout', 'excluded' - the same values as the list's three_ds_status. |
| `3DS flow` | string | 'frictionless' \| 'challenge' \| 'attempt' \| 'data-only' - the authentication flow the provider reported (three_ds_flow); empty when no authentication ran. |
| `3DS ECI` | string | The ECI (Electronic Commerce Indicator) the authentication returned; empty when none. |
| `3DS applied` | string | 'yes' when the cryptogram was sent to the gateway, 'no' when 3DS ran but nothing usable came back; empty when no provider ran. |
| `3DS liability shift` | string | 'yes' when the issuer took liability for the charge, 'no' otherwise; empty when no provider ran. |
| `3DS fee` | string | The provider's authentication fee in MAJOR units with 2 decimals; empty when zero. v3.9.6 live fees: the 3DS integration's CURRENT attemptFeeUsd on every row that ran 3DS with a provider (not passthrough / holdout / excluded / rule), computed at export time - never the deprecated three_ds_fee_cents snapshot. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is unknown (strict), a value is outside its vocabulary, a range pair is reversed, hour has no valid tz, or sort / dir is not allowed; `{"error":"Unknown flow filter"}` / `{"error":"Unknown affiliate filter"}` for a flow or affiliate id that is not the account's.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `500` Unhandled database error.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Two exports are already running. Retry when one finishes.","requestId":"..."}` (with Retry-After: 1) when this server process already streams two exports.

**Gotchas**

- The response is CSV text, not JSON - do not JSON.parse it. Success responses carry content-type text/csv, but ERROR responses (400/401/403) are JSON.
- Amount is in DOLLARS here ('49.99'), while every JSON endpoint in this file returns integer cents. Do not mix them.
- Hard cap of 100000 rows, applied AFTER the ORDER BY (`sort`/`dir`, default `created_at desc`) - an over-cap export silently drops the LAST rows of that order (the OLDEST, by default) with no flag or count in the response.
- An unknown `sort` key (or a direction passed as the key) is a 400 - the CSV is never produced in a different order than the one asked for.
- Passing limit/offset does nothing (they are stripped from the schema), so you cannot page the export.
- The CSV column set differs from the list JSON: it adds Source, Product, 'Product from original sale', Subscription, Cycle and Brand and drops id, trip_id, note_count, attempts, won_attempt, paysource, wallet_provider_id, refunded_at.
- The whole CSV is built in memory and sent as one string; a 100k-row export is a large single response body.
- The leading U+FEFF BOM is intentional (Excel UTF-8 detection) - strip it before parsing the header row programmatically.
- - the export joins transaction_attribution (one PK lookup per row) for the two UTM columns and accepts the utmSource / utmCampaign filters and the utm_source / utm_campaign sort keys exactly like the list.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- The v5_affiliate projection enriches merchant records with immutable attribution and cut ledger entries; list and CSV include Affiliate/public ID/status/cuts. This merchant projection is never used by the masked native affiliate workspace.
- Filters use the one unified catalog shared by the transactions list, the reports and the bulk tools: the query is strict (an unknown parameter is a 400 that names it), a closed vocabulary rejects unknown values, CSV values are OR-ed inside a key and keys are AND-ed, range pairs (from/to, amountMin/amountMax, cycleMin/cycleMax, clientOrdersMin/Max, clientLtvMin/Max, the sub and client date pairs, dayFrom/dayTo) must be ordered, and hour needs a valid tz.
- The CSV holds at most the first 100,000 rows of the requested order; the card column is the stored card value (as an admin sees it).

##### `GET /v1/transactions/facets`

**Scope** `transactions.read` - **Get filter dropdown values**

Distinct free-form filter values observed in the caller's own transactions over the last 90 days - the exact strings to feed back into the country / storefront / traffic / productSlug filters and, since (the Traffic report's filter bar), the issuer / cardLevel / gatewayMcc / gatewayBin filters: issuing banks (top 200 by orders), card levels, and the MCCs and acquirer BINs of the MIDs the account's charges ended on. Since : utmSources / utmCampaigns - the utm_source / utm_campaign values of the account's attribution rows (top 300 by orders each). Read-only.

*No parameters.*

**Response**

```json
{
 "countries": [
  "AU",
  "CA",
  "GB",
  "US"
 ],
 "storefronts": [
  "(direct)",
  "checkout.example.io",
  "shop.example.com"
 ],
 "trafficSources": [
  "(direct/organic)",
  "meta",
  "tiktok"
 ],
 "productSlugs": [
  "bundle-3",
  "starter-kit"
 ],
 "issuers": [
  "JPMORGAN CHASE BANK, N.A.",
  "CAPITAL ONE BANK (USA), NATIONAL ASSOCIATION",
  "BANK OF AMERICA, NATIONAL ASSOCIATION"
 ],
 "cardLevels": [
  "BUSINESS",
  "CLASSIC",
  "PLATINUM",
  "SIGNATURE",
  "STANDARD"
 ],
 "gatewayMccs": [
  "5499",
  "5964",
  "5968"
 ],
 "gatewayBins": [
  "400123",
  "480234"
 ],
 "utmSources": [
  "tiktok",
  "fb",
  "ig",
  "sms",
  "email"
 ],
 "utmCampaigns": [
  "us_summer_broad",
  "eu_retarget_7d",
  "Whop Launch"
 ]
}
```

| response field | type | description |
|---|---|---|
| `countries` | string[] | Distinct billing countries, UPPER-CASED, as the `country` filter and the Traffic report's Country breakdown read them (countryOf: the payload's root `country`, else `billingAddress.country` - so wallet charges contribute their billing country too). Sorted ascending, max 300. |
| `storefronts` | string[] | Distinct store host buckets of the rows' OWN storefront URL (lowercased host, or '(direct)'), sorted ascending, max 300. Feed straight back into the `storefront` filter. |
| `trafficSources` | string[] | Distinct traffic buckets of the rows' OWN traffic_source (or '(direct/organic)'), sorted ascending, max 100. Feed straight back into the `traffic` filter. |
| `productSlugs` | string[] | Distinct product slugs of the account's baskets (transaction_products joined by order_id), sorted ascending, max 400 - the `productSlug` filter's values. Empty (never an error) when the basket query fails. |
| `issuers` | string[] | - issuing bank names (bin_info.issuer of the card's first six digits) ordered by ORDERS DESC then name, top 200. The `issuer` filter's values (and the issuer axis of GET /v1/metrics/bins). A name containing a comma cannot travel in the CSV filter. |
| `cardLevels` | string[] | - distinct bin_info.level values of the rows' BINs (CLASSIC, SIGNATURE, BUSINESS...), sorted ascending, max 100. The `cardLevel` filter's values. |
| `gatewayMccs` | string[] | - distinct MCCs (nmi_accounts.mcc) of the MIDs the account's charges ended on, sorted ascending, max 100. The `gatewayMcc` filter's values. |
| `gatewayBins` | string[] | - distinct acquirer BINs (nmi_accounts.acquirer_bin) of those MIDs, sorted ascending, max 100. The `gatewayBin` filter's values. |
| `utmSources` | string[] | - the utm_source values of the account's attribution rows (transaction_attribution joined to the transaction for the 90-day window and the tenant scope), ordered by ORDERS DESC then value, top 300. ONE entry per case-insensitive value (the utmSource filter matches on lower()), shown with one of its real spellings. Raw utm values - not the network labels of trafficSources. Empty (never an error) when the table is absent. |
| `utmCampaigns` | string[] | - the utm_campaign values, same ranking / grouping / scope, top 300 - the utmCampaign filter's options. A campaign name containing a comma must travel double-quoted in the filter (csv()). |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `500` Unhandled database error.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- This route reads NO query parameters at all - the window is hardcoded to the last 90 days and there is no date/filter passthrough. Anything you put in the query string is ignored (and there is no 400).
- Each list is separately capped (countries 300 / storefronts 300 / trafficSources 100 / productSlugs 400 / issuers 200 / cardLevels 100 / gatewayMccs 100 / gatewayBins 100 / utmSources 300 / utmCampaigns 300) with no indication of truncation, so a rare value may be missing from the dropdown even though transactions with it exist. `issuers`, `utmSources` and `utmCampaigns` are the lists ranked by orders, so what it drops is the tail.
- The lists are the ONLY reliable source for the exact `storefront` / `traffic` bucket strings - including the sentinel values '(direct)' and '(direct/organic)', which are literals you must send verbatim.
- `countries` is upper-cased since and so is the `country` filter's matching - 'us' in an old link still works. `storefronts` / `trafficSources` list the rows' OWN values, while the filters (and the Traffic report) also let a subscription charge inherit its originating sale's; a rebill-only value cannot appear here but its sale's value does.
- MID / category / ATRI / processor / acquiring bank / company options are NOT here; they come from their own admin endpoints (GET /v1/accounts, /v1/categories, /v1/trips, /v1/processors, /v1/acquiring-banks, /v1/companies). The fixed label sets (device, os, browser, ipType, funding, brand, threeDs, hour, pricePoint) are enumerated on the filters themselves.
- A value can appear here and still match zero rows in the list, because the list also applies the ATRI view-scope and never lists the 3DS park (
- - utmSources / utmCampaigns come from the attribution side table, so a wallet sale contributes since migration 158 (the wallet-history backfill, its own transaction after 150's DDL) and a card sale only once the checkout sends `attribution`; a subscription charge's copied row counts under its sale's campaign.

##### `GET /v1/transactions/ids`

**Scope** `transactions.read` - **List transaction ids matching filters (select all)**

Returns the ids of every transaction matching the SAME filter set as GET /v1/transactions (dimension filters, date range, quick search, card/customer search), in the list's order (`sort`/`dir`, newest first by default), capped at 10 000 - the 'select all matching' of the bulk-edit UI. No paging.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Start of the page range (inclusive): the grain's own date. A bare day is read in tz (its first millisecond). |
| `to` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | End of the page range (inclusive). A bare day is read in tz (its last millisecond). |
| `tz` | string (IANA timezone, max 64) | no | IANA timezone the days and hours are read in. Defaults to the account timezone. Must be a known zone. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `storefront` | CSV string (max 4000) | no | Store host bucket, (direct). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `checkout` | CSV of UUIDs or none | no | Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of UUIDs or none | no | Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. |
| `affiliate` | CSV of UUIDs or none | no | Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |
| `sort` | enum: created_at \| completed_at \| amount \| status \| order_id \| email \| customer \| mid \| atri \| crm \| country \| storefront \| traffic \| decline_reason \| card \| three_ds \| method \| source \| product \| subscription \| processor \| acquiring_bank \| company \| utm_source \| utm_campaign; default `created_at` | no | Sort column (nulls last, then created_at desc). |
| `dir` | enum: asc \| desc; default `desc` | no | Sort direction. |

**Response**

```json
{
 "ids": [
  "7a8b9c0d-1e2f-4a3b-9c4d-5e6f7a8b9c0d",
  "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
 ],
 "capped": false
}
```

| response field | type | description |
|---|---|---|
| `ids` | array of uuid | Matching transaction ids in the requested order (default created_at desc), max 10000. |
| `capped` | boolean | true when 10000 ids were returned - more may match; narrow the filters. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is unknown (strict), a value is outside its vocabulary, a range pair is reversed, hour has no valid tz, or sort / dir is not allowed; `{"error":"Unknown flow filter"}` / `{"error":"Unknown affiliate filter"}` for a flow or affiliate id that is not the account's.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `500` Internal Server Error with a requestId.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- v3.9.9 - `refunded` no longer switches the date column (the state flag, on the charge date); `refund=...` reads from/to on the refunds row's date unless refundBasis=charge. At most 10 000 ids - the dashboard's bulk bar then offers 'Select the first 10,000 of N matching'.
- capped is true when exactly 10000 match as well - treat it as "possibly more".
- Tenant scope + ATRI view-scope apply; ids you cannot see are never returned, so feeding them to /bulk yields no skips from this source.
- `sort`/`dir` are honoured with the list's whitelist (an unknown key is a 400); the cap is applied after the ORDER BY. `sort=subscription` is the one key that adds the per-row subscription join to this otherwise join-free query.
- - sort=utm_source / utm_campaign are accepted here too; the attribution join is only paid when one of them is asked for (the filters themselves are an EXISTS and need no join).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- Filters use the one unified catalog shared by the transactions list, the reports and the bulk tools: the query is strict (an unknown parameter is a 400 that names it), a closed vocabulary rejects unknown values, CSV values are OR-ed inside a key and keys are AND-ed, range pairs (from/to, amountMin/amountMax, cycleMin/cycleMax, clientOrdersMin/Max, clientLtvMin/Max, the sub and client date pairs, dayFrom/dayTo) must be ordered, and hour needs a valid tz.
- At most 10,000 ids (capped true when the cap was reached). Feed them to POST /v1/transactions/bulk-jobs.

##### `DELETE /v1/transactions/notes/:noteId`

**Scope** `transactions.write` - **Delete a transaction note**

Deletes one transaction note; it sits with the other note endpoints, POST /v1/transactions/:transactionId/note and GET /v1/transactions/:transactionId/notes. Deletes one note of a transaction of the account (note the singular /note/ in the address).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `noteId` | uuid | **yes** | Note id. |

**Response**

```json
{
  "deleted": true
}
```

| response field | type | description |
|---|---|---|
| `deleted` | boolean | Always literally true on a 200. It is a constant, not a report of how many rows were removed - do not treat false as a possible value. |

**Errors**

- `400` `{"error":"Invalid note id"}` when :noteId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the note is unknown or its transaction is not the account's.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Scope transactions.write, like the other note routes (POST /v1/transactions/:transactionId/note needs transactions.write, GET /v1/transactions/:transactionId/notes transactions.read). A key saved before 2026-11-24 with refunds.write keeps it.

### Payments

Charging, 3-D Secure and the Payments menu: gateways (MIDs), wallet providers, bank accounts, ATRIs (routing pools), filters, BIN intelligence and MID scrubbing.

#### Charging

Charge orders with POST /v1/charge, recover their status, verify a card before a subscription, and queue reference rebills.

##### `POST /v1/charge`

**Scope** `charges.write` - **Charge orders (one order or a batch)**

Charges orders: one order or a batch (card sales and card-on-file subscription batches), the main integration endpoint; POST /v1/transactions/charge charges one manual card sale from the account side (an ATRI or a pinned MID). The main money endpoint. Accepts a single card sale, a batch of sales, or a subscription batch that charges the card on file (orders without crm/ccnumber). routeID is OPTIONAL: omit it to preserve existing store/key/account defaults, or send either an ATRI UUID or card gateway UUID in the same field. The server detects the target type. ATRIs retain normal ATRI/BIN routing; a gateway UUID pins only that gateway with no other-gateway fallback. The reply is {results:[...]}, one result per order in input order.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `routeID` | uuid | no | Optional shared ATRI or gateway UUID for this single order or every order in a batch. Same account and active-state validation as the body field. Must agree with all supplied body/envelope/item values; repeated query values are invalid. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `orders` | object[] | no | Presence of the KEY `orders` at the top level (any value, even null) switches the request to batch mode. Must then be an array of 1..100 order objects. Absent = single-order (checkout) shape, where the order fields below sit at the top level of the body. |
| `orderId` | string | **yes** | 1..128 chars. Your order identifier. Top level in the single shape, `orders[].orderId` in both batch shapes. Drives the idempotency key and, on the subscription-charge path, the card-on-file lookup. |
| `crm` | enum: nmi | **yes** | Required literal nmi for the shared card-sale pipeline, including card gateways implemented by other processor adapters. Omit on every order of a card-on-file batch. The selected gateway determines the adapter; wallet routes remain separate. |
| `amount` | number | **yes** | MAJOR units, e.g. 9.99, not cents. Must be finite, at least 0.01, and no finer than one cent (at most two decimal places). A value such as 1.005 is rejected before payment rather than silently rounded. Valid amounts are converted to integer minor units internally. |
| `routeID` | uuid; default `Existing store/key/account routing` | no | OPTIONAL active ATRI UUID or card gateway UUID owned by the authenticated account. The server detects the target type; no type parameter is needed. Supported on the single order, each orders[] item, or the batch envelope. A gateway UUID is exclusive with no fallback/cascade to another gateway; an ATRI UUID retains normal rules, including BIN mapping redirects. All supplied locations for an order must agree. Omission preserves existing routing. Protected checkout and verified credential routes cannot be overridden. |
| `atri / atriId / gatewayId / midId` | uuid | no | Older spellings of routeID, still accepted in the same places (single order, orders[] item, batch envelope) and in the query: atri and atriId name an ATRI, gatewayId and midId a card gateway. Each must be one UUID, else 400 invalid_charge_target. Every declaration for an order must name the same target, and a matching older spelling also fixes the kind of a routeID. |
| `currency` | string; default `USD` | no | Exactly 3 characters (length is validated, the value is not  -  'ZZZ' passes). On the subscription-charge path the fallback chain is order.currency -> legacy source's currency -> 'USD'. |
| `channel` | string; default `none on the sale path (absent = initial); 'rebill' on the subscription-charge path` | no | Max 32 chars, any string (a typo never 400s). Classification is done by prefix: a value starting with 'rebill' or equal to 'legacy' (case-insensitive, trimmed) makes the order a REBILL for the pre-charge filters, BIN-scrub scope and preferredMid logic; anything else / absent is an initial sale. |
| `preferredMid` | string | no | Optional trimmed MID display-name hint for rebills only (max 256). Best-effort first attempt, with normal fallback when unavailable; ignored on ordinary straight sales. Use a gateway UUID in routeID for an exclusive immutable-ID target. Explicit gateway targeting cannot be overridden by this legacy hint. |
| `source` | string | no | SUBSCRIPTION-CHARGE BATCH ONLY (rejected as unknown/stripped on the sale path). Max 32 chars. A caller tag, logged as-is. The former 'legacy' value (card fetched from an external lookup API) was RETIRED on 2026-09-13 with the old RB tool: every subscription charge now uses our own card on file, whatever `source` says. Friendlies transactions use source=friendlies and are excluded from Straight/Subscription. |
| `ccnumber` | string | no | PAN, 12..19 chars. Schema-optional but effectively required on the sale path: without it the local Luhn/expiry pre-check fails and you get a 200 with a declineReason. Must be ABSENT on every order of a subscription-charge batch. |
| `ccexp` | string | no | Expiry as MMYY, exactly 4 digits (regex `^\d{4}$`). Wrong format = 400 for the whole request. Missing = local validity pre-check decline (200, isSuccess:false). |
| `cvv` | string | no | Optional string of 3 or 4 characters in the shared charge schema; an empty string is invalid. This route does not apply a digits-only regex. Omission at schema level does not override the chosen gateway or authentication requirements. Flow post-sell payment.securityCode has its own strict 3-or-4-digit contract. |
| `firstName` | string | no | Max 128. Forwarded to NMI as `firstname` and mirrored to `shipping_firstname`. |
| `lastName` | string | no | Max 128. Forwarded to NMI as `lastname` and mirrored to `shipping_lastname`. |
| `email` | string | no | Must be a valid email (max 256) or the request 400s. Also the key the blacklist and the pre-charge filters match on. |
| `address1` | string | no | Max 256. AVS input; also mirrored to shipping_address1. |
| `city` | string | no | Max 128. Mirrored to shipping_city. |
| `state` | string | no | Max 64. Mirrored to shipping_state. v3.9.7  -  for the inline 3DS authentication it reaches the provider only as an ISO 3166-2 subdivision code (a US / CA code as is, a French region or departement name mapped to its region code, anything else omitted  -  never truncated); send what your storefront holds. |
| `zip` | string | no | Max 32. AVS input; mirrored to shipping_zip. |
| `country` | string | no | Max 64. Mirrored to shipping_country. |
| `description` | string; default `a fixed filler product name` | no | Max 256. Sent to NMI as `order_description` and as the fallback item description. If omitted a generic synthetic filler name is sent  -  the field is never blank on the wire. |
| `products` | unknown | no | DUAL-PURPOSE and never validated strictly: it NEVER rejects, not even for a string, null or an object. Elements matching the Level III shape ({productCode?, description?, quantity int>0<=9999, unitCost>=0, taxAmount?}) survive zod (first 100 only) and are forwarded to the gateway as item_*_N. Elements with checkout identity ({id,name,slug,url,quantity,amount}) are DROPPED by zod and re-read from the raw body (first 200) as `cart`  -  reporting only, never sent to any gateway. A malformed entry is silently skipped. |
| `ipaddress` | string | no | Max 64. Fraud/velocity scoring, forwarded to NMI as `ipaddress`  -  EXCEPT that IPv6 addresses fall into an A/B arm where ~10% of orders have the field deliberately omitted from the gateway call. |
| `phone` | string | no | Max 32. Forwarded to NMI as `phone` (and `shipping_phone` in the enriched A/B arm); split into number/countryCode for Convesio. v3.9.7  -  for the inline 3DS authentication the calling code follows `country` (+33 ... keeps its own); an un-normalisable number is omitted from the 3DS request only. |
| `useragent` | string | no | Max 1024. Only used by the Convesio S2S adapter (`browserInfo.userAgent`). NMI ignores it entirely  -  accepted and stored but a no-op for NMI MIDs. |
| `cavv` | string | no | Max 512. 3DS cardholder authentication verification value, passed through to the gateway as-is. For Convesio it is the trigger field: the whole threeDSData block is only built when `cavv` is present. |
| `eci` | string | no | Max 8. 3DS ECI indicator, passed through as-is. |
| `xid` | string | no | Max 512. 3DS transaction id, passed through as-is. |
| `cardholder_auth` | string | no | Max 32. 3DS cardholder auth status, passed through as-is (Convesio: threeDSData.authenticationStatus). |
| `three_ds_version` | string | no | Max 16. 3DS protocol version, passed through as-is. |
| `directory_server_id` | string | no | Max 128. 3DS directory server transaction id. Forwarded to NMI only  -  the Convesio S2S adapter does not read it. |
| `threeDsSessionId` | string (uuid) | no | Session ID from a completed explicit authentication or a pending charge response. Resume a parked order using the SAME orderId and payment data plus this ID. For a PAAY pair the engine checks both slots: the next response can park again for the other slot. Never create a new orderId for a browser resume. Non-UUID values retain the existing lenient parsing behavior. A grouped session hint on a rebill cannot bypass the saved-proof claim checks. |
| `threeDsChallenge` | enum: 'skip' \| 'return' \| 'decline' | no | Per-order browser policy for single inline authentication. PAAY double authentication exposes required browser actions even when the single-auth setting is skip; explicit decline still blocks an outstanding action. A group can need multiple same-order resumes before dispatch. |
| `browser` | object | no | EMV 3DS browserInfo for the INLINE authentication, captured in the customer's browser  -  issuers challenge less and directory servers reject fewer requests when it is real. Keys: acceptHeader (the request's Accept header), userAgent, language (navigator.language, <= 8 chars), colorDepth (screen.colorDepth), screenWidth, screenHeight, timezoneOffset (new Date().getTimezoneOffset(), minutes), javaEnabled, javascriptEnabled (true), ip (the customer's IPv4/IPv6 as seen by the checkout server). Every key optional; without the object cocoapi sends defaults (accept */*, en-US, 24-bit, 1920x1080, TZ 0, the order's useragent / ipaddress). Lenient: a malformed object is ignored. |
| `trafficSource` | string | no | Max 32, lenient (v3.9.2 section 4: `.catch(undefined)`  -  an invalid value is dropped, never a 400). "meta" \| "tiktok" \| "snapchat" \| "google" (v3.9.18) \| "" (direct/organic): a NETWORK LABEL, not a utm_source  -  it is never copied into the attribution row. Stored on the transaction for AR-by-source reporting; also sent to NMI as mdf_6 in the enriched A/B arm. |
| `storefrontUrl` | string | no | Max 256, lenient (dropped when invalid, never a 400). Stored on the transaction and on the basket rows. Not sent to any gateway. |
| `fbclid` | string | no | Max 512, lenient (v3.9.2 section 4: an over-long value is dropped from the transactions column but kept TRUNCATED in the attribution row's click_ids  -  never a 400). Meta click id. Also an input to the pre-charge filters. Superseded by attribution.click_ids.fbclid when both are sent. |
| `ttclid` | string | no | Max 512, lenient (same rule as fbclid). TikTok click id. Also an input to the pre-charge filters. Superseded by attribution.click_ids.ttclid when both are sent. |
| `attribution` | object | no | v3.9.2 section 4  -  the CAMPAIGN ATTRIBUTION of the visit, stored in transaction_attribution (one row per transaction, GET /v1/transactions/:id/details `attribution`, the UTM tab, the utmSource / utmCampaign filters, the CSV). Shape: `{ "utm": { "source", "medium", "campaign", "id", "term", "content" }, "click_ids": { "ttclid", "fbclid", "gclid", "msclkid", ... }, "landing_url", "referrer", "captured_at" }`  -  every key optional. Inside `utm` the `utm_source` spelling is accepted too; any OTHER key under `utm` (adset, ad, placement, meta_ad_id ...) is kept as the free click_ids key `utm_<key>`; EVERY key under `click_ids` is kept (fbp, fbc, ttp, sccid, ttclid_ts ...; keys lower-cased, a leading underscore stripped). Values are stored as sent (the filters match case-insensitively). LENIENT, read from the un-stripped body like `products`: over-long -> truncated (utm_* 256 chars, a click id 512 chars, a URL 2 048 BYTES, click_ids 32 keys / 2 KB in Postgres' own jsonb text form  -  the table's CHECK units, so a cut value never costs the row), malformed -> dropped, a non-object -> ignored  -  NEVER a 400. landing_url / referrer are scrubbed of the query keys email / phone / name / token / password / auth / session before storage. captured_at: an ISO-8601 string, or the Unix epoch in seconds / milliseconds as a JSON number or a digit-only string (`"1758791553"`, the ttclid_ts form)  -  kept when within +/-7 days of the request, else the request time; any other string is dropped (the request time is stamped). A row is written only when at least one value is non-empty. Precedence: attribution.* > the flat keys below > the top-level fbclid / ttclid  -  so a checkout that sends only today's fields already yields a row with its click ids. The optional write starts only after a newly claimed transaction and its checkout context have committed. It is asynchronous and non-fatal; the reporting row can appear after the charge response. Replaying an existing claim does not replace or backfill attribution. |
| `utm_source / utm_medium / utm_campaign / utm_id / utm_term / utm_content / gclid / msclkid / landing_url / referrer / captured_at (flat)` | string | no | v3.9.2 section 4  -  the FLAT spelling of the same contract, accepted at the top level of the order (`landingUrl`, `referrer_host` and `capturedAt` are aliases; `utm_adset`-style keys and the cookie-mirrored ids `_fbp` / `_fbc` / `_ttp` / `_scid` / `ScCid` / `ttclid_ts` become free click_ids keys). Same leniency, same caps, lower precedence than `attribution`. Send one shape or the other  -  the nested one is the documented one. |
| `upsells` | object[] <= 20 | no | v3.9.17  -  the upsell lines the storefront's server priced from the PUBLISHED document and the database: [{ block_id, product_id (uuid), variant_id (uuid \| null), unit_cents (int >= 0), quantity (1..99) }]. Validated (a malformed one is a 400), kept in the raw payload as validated. |
| `discount` | object | no | v3.9.17  -  the discount the server validated and reserved: { code (<= 64), amount_cents (int >= 0), redemption_id (uuid  -  reserve_discount_redemption) }. An approved sale's redemption is also confirmed by the settle hook (idempotent), so a confirmation the storefront lost never undercounts the code's limits. |
| `consents` | object[] <= 30 | no | v3.9.17  -  the checkout's consents: [{ block_id, purpose: terms \| marketing_email \| marketing_sms \| custom, key (<= 64), checked (boolean), text_hash (sha256 hex of the text as rendered) }]. |
| `subscription_optin` | object | no | v3.9.17  -  the subscription the customer opted into: { block_id, product_id (uuid  -  an ACTIVE subscription product of THIS charge's account, else 422 subscription_optin_invalid (not the account's, or deleted) or subscription_optin_inactive (switched off) before anything is charged), text_hash (sha256 hex of the disclosure as rendered), consented_at (ISO instant) }. The settle hook attaches THAT product (source optin) and none of the account's auto-attach products; Law (a) holds (a live sub of the customer answers exists). |
| `continuationToken` | string | no | Special Pre-Auth opaque ticket, single orders only. Restores verified card server-side without CVC; binds first merchandise order ID/amount/currency/basket/customer. Idempotency is scoped to the verification, including across rotated API keys. Uses normal ATRI/3DS without another subscription enrollment. |
| `fl` | boolean | no | Optional. true classifies this transaction as Friendlies instead of Straight/Subscription. false/omitted preserves ordinary classification. On /v1/charge batches, supply orders[].fl. Strict JSON boolean; strings, numbers and null return 400. Does not bypass routing, declines, idempotency or 3DS. |
| `subscription_optin.assignment_source` | cart \| subscription_block | no | Optional explicit enrollment source inside subscription_optin. The storefront resolves this from the signed cart or selected published block. special_pre_auth and percentage are assigned server-side; do not spoof them. |
| `stripeMode` | embedded\|hosted | no | Optional browser flow; routes only to a Stripe MID configured for this mode. |
| `stripePaymentMethod` | string | no | Optional account-scoped pm_ PaymentMethod for Stripe S2S instead of raw card. |
| `stripeReturnUrl` | string | no | Legacy internal browser-resume URL, maximum 4096 characters, with the same HTTPS/no-credentials rule as checkoutReturnUrl (HTTP only for localhost/127.0.0.1 development). checkoutReturnUrl takes precedence when both are supplied. Top level for a single sale or orders[].stripeReturnUrl in a sales batch. The provider receives a signed CRM return URL instead; merchant/session ownership is checked before the CRM redirects the buyer. |
| `checkoutReturnUrl` | string | no | Internal buyer-resume URL, maximum 16384 characters. HTTPS is required; HTTP is allowed only for localhost/127.0.0.1 development. Credentials in the URL are rejected. Top level for a single sale; orders[].checkoutReturnUrl for a sales batch. Stored privately, never forwarded as the provider technical return URL. The CRM relay validates the exact owned checkout session and path; the legacy store path additionally requires the owned checkoutShopId and matching checkoutCartToken. A supplied URL cannot grant ownership or confirm a payment. When absent, stripeReturnUrl remains a legacy fallback; a bound session can supply its canonical checkout path. |
| `checkoutShopId` | uuid | no | Existing store UUID for this authenticated account, supplied by the trusted checkout integration. Top level for one sale or orders[].checkoutShopId in a sales batch. Participates in store/card routing and the owned-store return binding. It is not an authorization token: current store availability, account-scoped routing and, on the prepared checkout path, exact server session/cart/order ownership remain enforced. Direct gateway targeting cannot override a store-bound checkout. |
| `checkoutCartToken` | string | no | Existing store cart token, 1-4096 characters; top level for one sale or orders[].checkoutCartToken in a sales batch. Used with checkoutShopId for pinned cart routing and legacy buyer-resume matching. On a prepared checkout it is taken from the verified server session. Never log it, treat it as standalone payment authority or reuse a customer cart for testing. |
| `shippingAddress` | object | no | Separate delivery address. Strict object: address1 (trimmed 1-256), city (trimmed 1-128), zip (trimmed 1-32), country (two letters normalized uppercase) required; firstName/lastName (max128), address2 (max256), state (max64), phone (max32) optional. Flat address fields remain billing. Omit to retain same-address behavior; protected checkout delivery restrictions still apply. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `X-Kontrol-Checkout` | uuid | no | Internal transport of the Kontrol storefront only: the prepared checkout id. With X-Kontrol-Domain it binds the charge to a prepared checkout order. When either header is present the request must be one order, the key must be the one the checkout is bound to, the checkout entry cookie must match, and orderId, amount and currency must equal the prepared quote; routing then comes from the checkout and a gateway routeID is refused. A merchant integration sends neither. |
| `X-Kontrol-Domain` | string | no | Internal transport of the Kontrol storefront only: the exact serving domain of the prepared checkout. See X-Kontrol-Checkout. |

**Request body**

```json
{
  "orderId": "KTRL-TEST-10482",
  "crm": "nmi",
  "amount": 79.9,
  "currency": "USD",
  "channel": "checkout",
  "ccnumber": "4242424242424242",
  "ccexp": "1230",
  "cvv": "123",
  "firstName": "Dana",
  "lastName": "Whitfield",
  "email": "dana.whitfield@example.com",
  "address1": "1180 Chestnut Ave",
  "city": "Portland",
  "state": "OR",
  "zip": "97209",
  "country": "US",
  "ipaddress": "203.0.113.7",
  "phone": "5035550142",
  "useragent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
  "trafficSource": "meta",
  "storefrontUrl": "https://shop.example.com/checkout",
  "fbclid": "IwAR2xQ8fJ0pLmN",
  "ttclid": "E.C.P.CvQ1wR8kZm",
  "attribution": {
    "utm": {
      "source": "tiktok",
      "medium": "paid",
      "campaign": "us_summer_broad",
      "id": "1758791553",
      "term": "",
      "content": "",
      "adset": "AS-17",
      "ad": "AD-93"
    },
    "click_ids": {
      "ttclid": "E.C.P.CvQ1wR8kZm",
      "fbclid": "",
      "gclid": "",
      "msclkid": "",
      "fbp": "fb.1.1758791553.1029384756",
      "ttp": "8XkQ2mN",
      "ttclid_ts": "1758791553"
    },
    "landing_url": "https://shop.example.com/products/recovery-serum?utm_source=tiktok&utm_medium=paid&utm_campaign=us_summer_broad&utm_id=1758791553&ttclid=E.C.P.CvQ1wR8kZm",
    "referrer": "shop.example.com",
    "captured_at": "2026-11-11T10:00:00.000Z"
  },
  "products": [
    {
      "id": "sku_884",
      "name": "Recovery Serum 30ml",
      "slug": "recovery-serum-30ml",
      "url": "https://shop.example.com/p/recovery-serum-30ml",
      "quantity": 2,
      "amount": 59.9
    },
    {
      "id": "shipping_protection",
      "name": "Shipping Protection",
      "quantity": 1,
      "amount": 20
    }
  ]
}
```

**Response**

```json
{
  "results": [
    {
      "isSuccess": true,
      "orderId": "KTRL-TEST-10482",
      "orderIdSupplier": "test-12345678",
      "declineReason": null,
      "midIdUsed": null,
      "midNameUsed": "TEST CARD (no gateway call)",
      "isTest": true
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `results` | object[] | One entry per order, in the SAME order as the input array (single shape = a 1-element array). Always present on a 200. |
| `results[].isSuccess` | boolean | true means a confirmed approval. Check processing/reconciliationRequired and threeDs.pending before interpreting false as a final refusal. HTTP 200 alone never confirms payment. Convesio automatic capture requires HTTP 2xx, a payment ID and Succeeded/Captured/Settled without a required action. |
| `results[].orderId` | string | Echo of the order id you sent. |
| `results[].orderIdSupplier` | string \| null | The provider payment ID when supplied, including on a refusal or an unconfirmed result. Null does not prove that no payment reached the provider. |
| `results[].declineReason` | string \| null | null when isSuccess is true. Otherwise a free-text reason: a real gateway decline, or an internal refusal such as 'Not sent to MID for credit card validity pre check: ...', 'Card already rejected, try another one', 'You have been blacklisted, try another email/card', 'BIN scrubbed (initial)', 'No card on file for this orderId (original order not found)', 'Unknown ATRI for this API key', 'No atri provided and no default ATRI configured', 'No eligible account available in trip', 'Duplicate request already in progress'. Do NOT parse this as a stable enum. v3.9 section 1: a pre-MID refusal keeps the very same text AND sets `rejected`  -  read `rejected`, never the text, to tell a rejection from a decline. |
| `results[].midIdUsed` | string \| null | UUID of the MID that produced the final result. null when no MID was attempted (a pre-MID rejection  -  `rejected` set  - , no eligible MID, card-on-file lookup failures). |
| `results[].midNameUsed` | string \| null | Display name of that MID. This is the exact value to send back as `preferredMid` on a later subscription charge of the same order. |
| `results[].preferredMidApplied` | boolean (key absent when no hint was sent) | Only present when the order carried `preferredMid` AND classified as a subscription charge. true = the first attempt actually went to the requested MID (it may still have cascaded away afterwards); false = the hint was ignored (unknown name, MID over cap / unsupported brand / not owned by the account). Absent means 'no hint evaluated'  -  do not read it as false. |
| `results[].rejected` | object \| absent | v3.9 section 1  -  present iff cocoapi refused the order BEFORE any MID: `{ family, reason }`. `family` in blacklist \| filter \| velocity_guard \| bin_scrub \| card_precheck \| card_cooldown \| three_ds_policy (`test_card` is reserved and never sent). `reason` is the same text as `declineReason`: for an interceptor filter both are the generic customer message ('We couldn't process your payment. Please try again later or use a different card.')  -  the rule and its threshold ('Blocked by velocity guard: N ... (limit L)') are kept on the rejections log (GET /v1/rejections) and in the Filter log, never put on the wire. Guarantees when set: `isSuccess` is false; `declineReason` is exactly the text callers received before v3.9 (your checkout behaves as today); `scrubbed: true` still accompanies family bin_scrub and the `threeDs` echo still accompanies family three_ds_policy; NO transaction row exists (a charge_rejections row does  -  GET /v1/rejections, 30-day retention); nothing is exported (PlatformPay / RB / Exify) and nothing counts as a decline anywhere. Absent on an approval, a MID decline, a technical error ('No eligible account available in trip', ambiguous gateway 5xx / timeout  -  these remain unconfirmed for Convesio), a 3DS park, a duplicate-in-progress and a card-on-file failure. |
| `results[].scrubbed` | boolean \| absent | true when the BIN scrub refused the order  -  the same fact as `rejected.family === 'bin_scrub'`, kept for the RB tool. |
| `error` | string | Only on non-200 replies. Short machine-ish message; never contains internal DB/connection detail. |
| `details` | object | Only on 400. Zod `flatten()` output: `{ formErrors: string[], fieldErrors: { <field>: string[] } }`. For a batch the field keys are index-prefixed, e.g. `"orders.0.amount"`. |
| `requestId` | string | Only on 500. Correlation id for support  -  the real error is in the server logs, never in the body. |
| `results[].threeDs` | object \| absent | Optional 3DS result metadata for inline/explicit authentication, a pending pair or consumption of stored PAAY proof: {sessionId, provider, status, liabilityShift, next?, pending?, expiresAt?, source?, applied?, authenticationCount?}. It can be absent on a no-stock rebill allowed to proceed without 3DS; the transaction still records no_token and applied=false. Read isSuccess separately for the payment result. |
| `results[].threeDs.sessionId` | string | The session to complete/resume when pending. A stored-proof result identifies the proof consumed. A strict no-token refusal can use an empty string because no proof exists. |
| `results[].threeDs.provider` | string | Provider integration key, for example paay_3ds. |
| `results[].threeDs.status` | string | Provider/session outcome or allocation result. reserved means the sole usable proof was saved and this sale carries no 3DS; no_token means no compatible saved proof exists; late means the stage deadline passed without applying proof. Other statuses include authenticated, attempted, informational, pending, method, challenge, failed, unavailable, error, invalid and consumed. Status alone does not prove that a cryptogram was sent. timeout means optional PAAY authentication exceeded its deadline and the server retired the unresolved work; read isSuccess and processing/reconciliationRequired for the actual bank result. |
| `results[].threeDs.liabilityShift` | boolean | true when the authentication carried a liability shift (EMV status Y or A). |
| `results[].threeDs.pending` | boolean \| absent | True can indicate a parked PAAY authentication before dispatch: complete/poll its named session and resume the SAME orderId. Check top-level processing/reconciliationRequired first: a Convesio action after the payment was sent is unconfirmed and requires read-only reconciliation, never a new charge. |
| `results[].threeDs.next` | object \| absent | Action when pending: method uses a hidden form/iframe, challenge uses a visible bank iframe or provider HTML/SDK as applicable, and {type:"poll"} means a concurrent provider start is still processing. Poll the requested session server-side for terminal state, then resume the same order. Browser messages are completion hints; verify the active frame/session and read the authenticated API result before considering it successful. |
| `results[].threeDs.expiresAt` | string (ISO 8601) \| absent | For a pending checkout, the one-hour browser deadline. For source=stored, the local proof holding deadline. Neither is a guarantee of issuer/network acceptance. |
| `results[] (attribution)` | - | v3.9.2 section 4  -  the attribution row is written fire-and-forget AFTER the claim and is never echoed in the result; read it back with GET /v1/transactions/:id/details `attribution`. A rejection (v3.9 section 1, no transactions row) keeps none. |
| `results[].threeDs.source` | string \| absent | checkout for PAAY pair allocation, stored for consuming a saved proof. Absent on legacy paths that do not supply this metadata. |
| `results[].threeDs.applied` | boolean \| absent | Whether this result applied the proof to the payment path. Inspect the persisted transaction three_ds_applied flag for the final recorded result, especially after a timeout or retry without 3DS. A proof marked Used is spent and is not proof that the payment was approved. |
| `results[].threeDs.authenticationCount` | integer \| absent | New provider authentications recorded for this transaction: normally 2 for a completed double-authentication pair (excluding error slots) and 0 for stored-proof consumption. It is not a count of successful payments or of browser challenges. |
| `results[].processing` | boolean \| absent | True means the submitted payment outcome remains unconfirmed. Do not book success/decline, fulfill the order or submit a replacement charge. Read the original order with GET /v1/charge/orders/:orderId using the same API key. |
| `results[].reconciliationRequired` | boolean \| absent | True requires read-only provider reconciliation of the original payment. Pending, processing, authorisation alone, required action, network uncertainty and contradictory replies cannot approve a sale. A missing supplier ID does not authorize a replacement payment. |
| `results[].threeDs.backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. |
| `results[].threeDs.pendingDeadlineAt` | string (ISO 8601) \| absent | Server-owned deadline for optional silent PAAY authentication of the current purchase, default 45 seconds from its durable creation. Secondary background work has its own lifetime and neither extends nor cancels this deadline. Resume the SAME order and session through the normal charge path; the server rechecks required authentication and current provider state. Real issuer challenges, known negative results and mandatory authentication retain their controls. This deadline never approves a sale or authorizes retrying an unknown bank result. |

**Errors**

- `400` Invalid request (single order): The bare-order body failed `singleChargeSchema`. Most common causes: missing/empty orderId, `crm` not exactly "nmi", amount <= 0 or non-numeric, `ccexp` not 4 digits, `email` not a valid address, currency not exactly 3 chars. Body carries `details` with the per-field zod errors. NOTHING was charged.
- `400` Invalid request (sales batch): `{orders:[...]}` failed `batchChargeSchema`: empty array, more than 100 entries, `orders` not an array at all (e.g. null or an object), or ANY single order invalid. It is all-or-nothing  -  one bad order rejects the entire batch and no order in it is charged.
- `400` Invalid request (subscription-charge batch): The batch was routed to the subscription-charge path (no order had `crm` or `ccnumber`) but failed `rebillBatchSchema`: missing orderId/amount, amount <= 0, currency not 3 chars, or >100 orders. Also written to rb_charge_logs with outcome 'invalid'.
- `400` invalid_charge_target: Invalid routeID UUID, conflicting values across query/envelope/order, or repeated query routeID values. No order in the request is charged.
- `400` {"error":"Continuation tokens require a single checkout order"}: continuationToken on a batch; {"error":"Checkout context requires a single order"}: X-Kontrol-Checkout or X-Kontrol-Domain on a batch.
- `401` Missing API key: Neither an `Authorization: Bearer ...` header nor a non-empty `X-Api-Key` header was present. Logged to charge_request_logs as outcome 'auth_failed'.
- `401` Invalid API key: The sha256 of the supplied key matched no row with `active = true`. Revoked and deactivated keys land here  -  indistinguishable from a wrong key by design.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account of the key has no paid or granted Kontrol subscription. Nothing is charged.
- `403` Forbidden: Global bot guard (an onRequest hook, runs BEFORE this route's auth): the User-Agent looked like a crawler/scanner/bot. Generic clients (curl, python-requests, Go-http-client, node fetch) are not matched. Send a normal or empty UA.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key lacks charges.write; {"error":"Banned","message":"..."} when the account owner is banned.
- `403` {"error":"invalid_continuation"}: the continuationToken is malformed, unknown or not this account's.
- `404` Not Found: The request arrived on a wallet host domain (wallet.<merchant>, which CNAMEs to the same service). On those hosts only the wallet routes respond and /v1/charge is hidden. Also returned by the generic not-found handler if the path/method is wrong.
- `404` {"error":"Store unavailable"}: checkoutShopId or storefrontUrl names a store that is inactive or archived, or checkoutShopId is unknown. Checked for every order of the request before any order is sent.
- `409` {"error":"Checkout session or quote is unavailable"} (or the status of the underlying refusal, 401, 403 or 404): the prepared checkout session, quote or dispatch named by X-Kontrol-Checkout does not match.
- `409` {"error":"continuation_not_ready"} or {"error":"continuation_conflict"}: the pre-auth verification is not ready for a sale, or already bound to another order.
- `410` {"error":"verification_expired"}: the pre-auth verification behind continuationToken expired.
- `422` v3.9.17  -  {"error":"subscription_optin_invalid","orders":[orderIds]}: an order's subscription_optin.product_id is not a subscription product of the key's account (or it was deleted); {"error":"subscription_optin_inactive","orders":[orderIds]}: it is one of the account's, but switched off (rebill_subscriptions.active = false). Nothing is charged  -  in a batch, no order is.
- `422` charge_target_unavailable: The supplied routeID is unknown, belongs to another account, is inactive or ambiguous (matches both an ATRI and a gateway), has no usable active account ATRI context for a direct gateway, or conflicts with a protected checkout route. All batch targets are checked before charging; no order in the request is charged and there is no default fallback. Omitting routeID is valid.
- `422` {"error":"charge_target_unavailable","message":"Gateway targets cannot override checkout routing"}, "ATRI target conflicts with the prepared checkout routing", "ATRI target conflicts with the store payment routing" or "Card payments are disabled for this store": an explicit target conflicts with the store or checkout routing. Nothing is charged.
- `429` Rate limit exceeded: Per-API-KEY limit (default 3000 requests/minute, RATE_LIMIT_CHARGE), falling back to per-IP when no key header is present  -  so anonymous callers share one bucket. Body is `{"error":"Rate limit exceeded, retry in 1 minute"}` (rewritten by the global error handler, so the usual statusCode/message envelope is NOT present).
- `500` Charge processing failed: An unexpected throw while processing the SALE path. Body is `{"error":"Charge processing failed","requestId":"..."}`  -  the real message is deliberately withheld. Orders in the batch may have been partially charged before the throw; reconcile by orderId, do NOT blind-retry (though the idempotency claim will protect same-orderId retries on the sale path).
- `500` Rebill processing failed: Same, for the SUBSCRIPTION-CHARGE path: `{"error":"Rebill processing failed","requestId":"..."}`. Also written to rb_charge_logs with outcome 'error'.
- `503` Service temporarily unavailable: The API-key lookup itself threw (database unreachable). Body is `{"error":"Service temporarily unavailable","detail":"authentication backend error"}`. Nothing was charged  -  safe to retry.
- `503` Server busy, retry: Global back-pressure: too many requests in flight on this worker. Returned by an onRequest hook before auth, with a `retry-after: 1` header and body `{"error":"Server busy, retry"}`. Nothing was charged.
- `503` The authentication backend failed, or (v3.9.17) the subscription opt-in could not be checked  -  never charged blind.
- `503` charge_target_unavailable: Target ownership/configuration lookup failed. No order in the request is charged; never silently uses a default target.
- `503` {"error":"pre_auth_unavailable"}: the pre-auth continuation could not be checked; {"error":"Store unavailable"}: the store availability check failed.

**Gotchas**

- HTTP 200 is an envelope acknowledgement, not payment approval. Inspect each result: processing/reconciliationRequired means unconfirmed; threeDs.pending can mean a parked authentication; otherwise isSuccess gives the terminal verdict. Rejected means refusal before any MID. An unconfirmed payment must never be exported as a decline or retried with a new reference.
- The three body shapes are selected STRUCTURALLY, with no discriminator field. (1) No top-level `orders` key -> single sale. (2) `orders` present AND every element lacks BOTH `crm` and `ccnumber` -> SUBSCRIPTION-CHARGE path. (3) `orders` present otherwise -> sales batch. Consequence: adding `crm:"nmi"` to a subscription-charge batch silently converts it into a sales batch, which is validated as a sale and cannot use the card-on-file lookup; missing card data is then handled by the sale pre-check or selected adapter. Conversely, forgetting `crm` on a sales batch sends real card-bearing orders down the subscription-charge branch only if ccnumber is also absent. Shapes: single = the flat object; sales batch = {"orders":[{...same fields...}]}; subscription-charge batch = {"orders":[{"orderId":"SHP-10482","amount":29.99,"routeID":"<uuid>","preferredMid":"Aurora Retail LLC"}]}.
- Sale-path idempotency is keyed on sha256(apiKeyId + ':' + orderId)  -  the AMOUNT IS NOT IN THE KEY. Calling /v1/charge twice with the same orderId and a different amount does NOT charge the second amount: it replays the stored result envelope from the first call verbatim (same orderIdSupplier, same midNameUsed) and returns 200. Use a fresh orderId for every distinct charge.
- Subscription-charge-path idempotency is DAY-SCOPED: sha256(apiKeyId + ':rebill:<orderId>:<amountCents>:<UTC yyyy-mm-dd>'). A same-day retry of the same orderId+amount is a no-op replay; the same call the next UTC day charges again. Changing the amount by one cent mints a new key and DOES charge again the same day. The day boundary is UTC, not the account timezone.
- If the first call for an orderId is still in flight, a concurrent second call returns 200 with isSuccess:false and declineReason 'Duplicate request already in progress'. That is a lock conflict, not a decline  -  the first call may still approve. Do not treat it as a final failure and do not retry immediately.
- `amount` is in MAJOR units (79.90), not cents. Every amount in the response path and in logs/DB is integer cents, but the request is not  -  sending 7990 charges $7,990.
- A batch is all-or-nothing at VALIDATION time but per-order at CHARGE time. One malformed order 400s the whole batch (nothing charged); once validated, orders run CONCURRENTLY (default 8 at a time) and you can get any mix of approvals and declines in the same 200.
- `products` is a trap with two meanings. Level III items are forwarded to the gateway; checkout basket lines ({id,name,slug,url,quantity,amount}) are stripped by zod and stored for reporting only  -  they NEVER reach NMI/Convesio. What the gateway actually receives as line items when you send a basket is a synthetic filler SKU with qty 1 and unitCost = the full order amount. A malformed `products` (string, null, object, bad entries) is silently dropped and never 400s  -  you lose reporting detail with no error.
- Basket `amount` is read as the LINE TOTAL (quantity x unit). If your checkout sends a per-unit price in `amount`, your reporting will be understated; send `unitCost` instead and it will be multiplied by quantity. Quantity is clamped to 1..100000 and rounded.
- Only the first 100 `products` entries are considered for Level III, and only the first 200 for the basket  -  extras are dropped silently.
- `channel` silently changes ENFORCEMENT, not just reporting. Any value starting with 'rebill', or exactly 'legacy', makes the order a rebill: the pre-charge order filters (email allowlist, max orders per IP, velocity) are BYPASSED ENTIRELY and BIN scrub rules switch from initial-scope to rebill-scope. Sending channel:'rebill' on a real first-time sale disables your fraud filters for that order.
- `preferredMid` is accepted, stored and completely IGNORED on straight sales  -  it is only evaluated when `channel` classifies the order as a subscription charge. On a sale you will get no `preferredMidApplied` key and normal routing, with no warning.
- The card on file of a subscription charge is the most recent card sale of that orderId that stored a card number (test-card orders excluded). An order of another account is refused before any charge (200, isSuccess:false, declineReason "order not found for this account", no transaction row) unless the account that sold it allows cross-account rebills in its settings.
- Card-on-file rebills depend on the ORIGINAL sale's raw_payload still containing the PAN. If the original order was placed through a path that never stored ccnumber (or through a different CRM), you get 'No card on file for this orderId (original order not found)'  -  a 200 with isSuccess:false and NO transaction row created, so the attempt is invisible in the transactions table (it only lands in rebill_request_logs).
- routeID is optional. Invalid UUIDs, conflicting values across query/envelope/order, and repeated query values return 400 invalid_charge_target before any charge. Every explicit batch target is validated before execution. Unknown, foreign, inactive or ambiguous IDs use 422 charge_target_unavailable; lookup failure uses 503 charge_target_unavailable. No target-validation failure silently falls back to defaults.
- Omitting routeID preserves the existing store/key/account default routing without new explicit-target lookups. When supplied, the same routeID field accepts an ATRI UUID or a gateway UUID; the server detects the type. Single body, orders[] item, batch envelope and query are supported. A common batch/query target cannot be overridden by an item target. Repeating the same UUID is allowed; different values are refused.
- `useragent` is a no-op for NMI MIDs (Convesio S2S only), and `directory_server_id` is forwarded to NMI only (the Convesio adapter ignores it). Both are accepted and stored either way.
- `ipaddress` is subject to a live A/B test: for IPv6 addresses roughly 10% of orders have the field deliberately OMITTED from the gateway call. Same for an 'enriched' payload arm that adds order_date/industry/mdf_* fields. Identical requests can therefore produce different wire payloads.
- `description` is never actually optional on the wire  -  if you omit it, NMI receives a generic synthetic filler description and a deterministic filler SKU derived from the orderId.
- Validated targets from any supported location are normalized onto each order and retained with routing evidence. Arbitrary extra per-order metadata is still stored in raw_payload; never send credentials or unnecessary sensitive data as extra fields. Batch envelope/query targeting no longer disappears silently.
- A trailing `preferredMid` pin that dies on a retryable gateway error/timeout is deliberately NOT adopted: the order falls back to normal ATRI routing and `preferredMidApplied` still reports true. So preferredMidApplied:true does not mean the pinned MID produced the final result  -  check `midNameUsed`.
- The rate limit bucket is per API KEY by design, so all your servers share one 3000/min budget; only keyless requests fall back to per-IP. The store is in-memory PER WORKER, so the effective global limit is roughly max x number of instances.
- Every request  -  including 401s and 400s  -  is written to charge_request_logs with an 11-char prefix of the key you sent. Subscription-charge batches are additionally written to rb_charge_logs and one row per order to rebill_request_logs.
- PlatformPay export fires only on the sale path, fire-and-forget after the charge; rebills never fire it. It cannot affect or delay the response.
- v3.9.2 section 4  -  NOTHING about the attribution can 400 a sale: `attribution` and the flat utm_* / click-id keys are read from the un-stripped body (like `products`), the four legacy fields are `.catch(undefined)`. What the checkout sends today (trafficSource / storefrontUrl / fbclid / ttclid) yields a row with click ids only  -  the UTMs reach cocoapi ONLY through `attribution` (or the flat keys): a `utm_source` in the landing URL is NOT parsed out of `storefrontUrl` (origin only). A subscription charge (the rebill batch) never carries attribution: it inherits a COPY of its sale's row (source "rebill"), keyed on order_id, else on the subscription.
- v3.9.7  -  a parked charge (`threeDs.pending`) carries `threeDs.expiresAt`: poll GET /v1/3ds/sessions/:id until then while the overlay is up (the French issuers confirm out of band, no CRes message), then re-submit with threeDsSessionId. A card issued in the SCA zone (EEA / UK / CH) that is declined WITH a cryptogram is never re-tried without it, whatever the integration's "retry once without 3DS" says.
- v3.9.17  -  the builder fields (upsells, discount, consents, subscription_optin) are the storefront SERVER's figures, read from the published document and the database; the API records them with the charge and does not re-price the amount. A wallet sale (Apple Pay / Google Pay) never reaches the subscription attach (no card on file): an opt-in there attaches nothing.
- Checkout subscription priority is explicit Special Pre-Auth > subscription product in the signed cart > selected Subscription product block > account product percentage attachment. Only one winning subscription is attached to a sale. Multiple signed-cart products choose the lowest sorted product UUID; conflicting selected blocks use the first matching document offer. Overlapping percentage matches choose the oldest configured matching product, then UUID.
- A pre-auth continuation suppresses new enrollment during the merchandise sale. Its subscription was attached after verification reversal. The merchandise sale uses normal ATRI routing; the verified subscription remains bound to its original verification MID.
- PAAY rebills use the shared saved-proof pool before dispatch, with exact account, original order, card hash/expiry, amount, currency, provider configuration and routed merchant checks. Claims are atomic and single use. No compatible proof records no_token/applied=false and proceeds without 3DS unless a strict account/BIN policy requires authentication.
- PAAY double authentication starts two independent durable slots. The primary usable proof can authorize the current sale without waiting for the secondary. The secondary can finish in the background; it never rewrites the proof or payment result already dispatched. optimizeThreeDsTokens reserves a sole usable proof only once both results are terminal and authentication is optional. A ready primary with a still-pending sibling is used for the sale. Strict account/BIN requirements remain enforced.
- Stripe browser/3DS actions are not approval. Keep the order pending and poll /v1/charge/orders/:orderId; never send a fresh payment on timeout. See the *Stripe gateway* section of llm.md.
- A gateway UUID in routeID pins an immutable gateway ID, not a reusable display name. An active account ATRI is needed as the risk/profile context; missing context refuses the target. BIN scrubbing, blacklist, limits, supported-card checks and 3DS still run. A decline, cap or unavailable gateway never moves the payment to another gateway. An ATRI UUID retains that ATRI ordinary dispatch and BIN reroute behavior.
- Public targeting cannot override protected checkout or verified credential routing. Keep the same orderId for retries of a payment; changing targeting never authorizes a second debit for the same idempotent sale.
- Direct gateway targeting applies only to API charges without checkoutShopId, prepared checkout headers or a pre-auth continuation. A gateway UUID in routeID on those protected flows returns 422 charge_target_unavailable, even if it matches the current store gateway. The separate POST /v1/checkout/pre-auth endpoint rejects nested order.routeID with 400 invalid_charge_target; verification uses store payment settings.
- A direct gateway-targeted charge parked for 3DS stores its original gateway target durably. Resume with the same orderId and routeID; omitting or changing that gateway target is refused before any gateway send and never falls back to the default. Existing ATRI-routed and no-target 3DS resume rules are unchanged.
- For checkout calls naming their existing ATRI context, a store-configured single-gateway source remains enforced. An explicit ATRI does not widen this protected store restriction; a different ATRI is refused before the batch starts.
- Technical provider return URLs use the fixed API_PUBLIC_URL (or RENDER_EXTERNAL_URL) and a signed CRM reference. Store destinations stay internal; returning does not confirm, retry or settle a payment. Required merchant identity and registered wallet domains remain unchanged.
- The example is one simulated approval for one input order, with TEST_CARD_ENABLED=true and the default approve PAN. The test branch returns isTest:true, midIdUsed:null and midNameUsed:"TEST CARD (no gateway call)"; orderIdSupplier uses test- plus the first eight transaction-ID characters. Normal authentication, ownership and applicable pre-test checks still apply. No processor or 3DS request is sent. This is not a PSP sandbox or evidence that live bank, wallet or 3DS processing works; confirm simulation is enabled before using a test PAN.
- Campaign attribution is optional reporting data. A newly claimed payment publishes its attribution only after its transaction/context commit, using an asynchronous non-fatal write. A missing or delayed attribution row is not a payment failure and never authorizes another charge. Same-order replays preserve the existing attribution; this change does not backfill historical rows.
- An explicit threeDsSessionId whose browser step was abandoned (POST /v1/3ds/sessions/:id/complete with abandon:true and no result recovered from the provider) is refused before any MID with `3DS authentication failed (Browser authentication abandoned)`, even when the integration does not require a liability shift. Other failed explicit sessions still follow the policy.
- Checkout orders that carry a prepared V5 checkout context: the card submission claims the order's single initial-payment dispatch (card channel) before any transaction or 3DS park is created. When the same order was already dispatched through the wallet channel, no card attempt is made and the request fails (500 `Charge processing failed` with a requestId); observe the existing wallet payment instead of retrying.
- When an order names a store (checkoutShopId) without an explicit target and that store has card payments disabled, the request fails with 500 {"error":"Charge processing failed"}: no order of the request is charged by that store.

##### `GET /v1/charge/orders/:orderId`

**Scope** `charges.read` - **Read a submitted payment or recover its saved bank challenge**

Read the outcome of a payment this same key submitted with POST /v1/charge, by its orderId: complete (with isSuccess) or unconfirmed. With challenge=1, an unconfirmed payment waiting on a saved 3-D Secure browser challenge returns that challenge. Read-only; never contacts a processor.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | string | **yes** | The orderId you sent to POST /v1/charge, 1..128 characters of A-Z a-z 0-9 _ -. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `challenge` | string | no | Send 1 to recover the saved bank challenge of an unconfirmed payment (never creates a new authentication); other values are ignored. |

**Response**

```json
{
  "state": "complete",
  "orderId": "order-0001",
  "result": {
    "isSuccess": true,
    "orderId": "order-0001",
    "orderIdSupplier": "1234567890",
    "declineReason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `state` | string | complete (terminal), unconfirmed (unknown or still in flight: never a permission to charge again), or challenge (with challenge=1). |
| `result` | object | When complete: isSuccess, orderId, orderIdSupplier (gateway id or null), declineReason ("Payment declined" or null). |
| `stripe` | object\|absent | Unconfirmed Stripe payment only: {mode, publishableKey, clientSecret\|url} to resume the same operation. |
| `challenge` | object\|absent | With challenge=1: sessionId, provider, status, next {type,url}, createdAt, expiresAt, amountCents, currency, maskedCard, and for an eligible PAAY session pendingTimedOut / pendingDeadlineAt. |

**Errors**

- `400` {"error":"Invalid order reference"}: orderId not 1..128 characters of A-Z a-z 0-9 _ -.
- `401` {"error":"Invalid API key"}: no key, or unknown key.
- `403` {"error":"Account unavailable"} (key owner banned) or {"error":"API key scope denied"} (no charges.read scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `429` 120 requests per minute per IP.
- `503` {"error":"Payment status temporarily unavailable"}: the read failed or ran past its budget; retry.

**Gotchas**

- The explicit recovery query returns saved challenge state without a provider call or payment replay. Omitting the query preserves the existing terminal/unconfirmed response contract.
- No credentials, private provider state, cryptograms, PAN or CVV returned. Naturally expired, consumed or mismatched sessions stay unconfirmed. An optional PAAY session retired at its authentication deadline is recoverable only when the server returns pendingTimedOut=true for the same pre-dispatch payment.
- For an unconfirmed Convesio payment, read the same original order only. state=unconfirmed cannot authorize retry, fulfillment or a decline. The durable provider worker resolves a verified terminal payment and updates the stored result; state=complete then contains its final isSuccess.
- An unconfirmed Stripe payment can include stripe:{mode,publishableKey,clientSecret|url}. This only resumes the existing operation; state=complete is the terminal authority.
- Only payments submitted with THIS key are visible: another key of the same account gets state unconfirmed for the same orderId.
- Rate limit: 120 requests per minute per IP.

##### `POST /v1/charge/status`

**Scope** `charges.read` - **Recover the status of charges**

Read-only status recovery for up to 100 charge references made with this same API key: a sale by its orderId, a rebill by orderId + the UTC day it was sent + its amount. Each reference comes back complete (the stored final result) or unconfirmed. It never dispatches, retries or claims a payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `orders` | array (1-100) | **yes** | References to look up, answered in the same order. |
| `orders[].kind` | enum: sale \| rebill | **yes** | sale = a POST /v1/charge sale; rebill = a rebill sent by this key. |
| `orders[].orderId` | string (1-128) | **yes** | The orderId the charge was sent with. |
| `orders[].day` | string (YYYY-MM-DD, a real UTC day) | no | rebill only, required there: the server UTC day the rebill was sent. |
| `orders[].amountCents` | integer (> 0) | no | rebill only, required there: the rebill amount in cents. |

**Request body**

```json
{
  "orders": [
    {
      "kind": "sale",
      "orderId": "ORDER-1001"
    },
    {
      "kind": "rebill",
      "orderId": "ORDER-0990",
      "day": "2026-11-23",
      "amountCents": 2999
    }
  ]
}
```

**Response**

```json
{
  "results": [
    {
      "kind": "sale",
      "orderId": "ORDER-1001",
      "state": "complete",
      "result": {
        "isSuccess": true,
        "orderId": "ORDER-1001",
        "orderIdSupplier": "10342998871",
        "declineReason": null
      }
    },
    {
      "kind": "rebill",
      "orderId": "ORDER-0990",
      "day": "2026-11-23",
      "amountCents": 2999,
      "state": "unconfirmed"
    }
  ]
}
```

**Errors**

- `400` `{"error":"Invalid payment references"}` when the body fails the schema (strict: unknown fields refused, sale with day / amountCents, rebill without them, more than 100 references).
- `401` `{"error":"Invalid API key"}` when no key is sent or the key is unknown or revoked.
- `403` `{"error":"Account unavailable"}` when the key owner is banned; `{"error":"API key scope denied"}` when a scoped key lacks the scope this route needs.
- `413` Body over 64 KiB.
- `429` More than 60 calls per minute from one IP.
- `503` `{"error":"Payment status temporarily unavailable"}` when the bounded read (10 seconds) fails or expires.

**Gotchas**

- unconfirmed covers missing, pending, unknown and still-reconciling charges: it never means you may charge again. Resend the original charge request with its original idempotency instead.
- A charge waiting for a 3DS challenge adds challengePending true. A Stripe charge in unknown state may carry its stripe block.
- declineReason is always the generic `Payment declined`.
- Sent with Cache-Control: no-store.

##### `POST /v1/checkout/pre-auth`

**Scope** `charges.write` - **Verify a card for an explicitly selected subscription**

Verifies a card for the subscription the customer explicitly selected in a special pre-auth checkout: charges exactly USD 0.99 on an NMI gateway of the store's payment route, requests an immediate void (a refund only when the gateway says the sale already settled), enrolls the selected subscription once on that same gateway, and returns a continuationToken for the normal merchandise sale (POST /v1/charge) once the reversal is bank-confirmed and the enrollment done. Requires a published checkout whose payment block is in special-pre-auth mode with the selected subscription product.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `order` | object | **yes** | The checkout order, same schema as the body of POST /v1/charge (single order), minus gatewayId, midId and routeID. checkoutShopId, subscription_optin, ccnumber and ccexp are required here. The verification ignores amount, currency, products and channel and charges exactly USD 0.99 with its own order id "pa-<verificationId>". |
| `order.orderId` | string 1..128 | **yes** | The checkout order id of this verification. Deduplication key with the account and the shop: a second call with the same orderId and the same inputs replays the same verification; with different inputs it is a 409 verification_conflict. |
| `order.crm` | "nmi" | **yes** | Must be "nmi". |
| `order.amount` | number > 0, <= 2 decimals | **yes** | Validated like a charge amount but not used: the verification is always USD 0.99. |
| `order.checkoutShopId` | uuid | **yes** | The store whose published checkout holds the special pre-auth payment block. Missing = 422 subscription_consent_required. An archived, inactive or unknown store = 404 "Store unavailable". |
| `order.checkoutCartToken` | string 1..4096 | no | Cart token: selects the store routing (and an A/B test checkout) for this cart. |
| `order.ccnumber` | string 12..19 | **yes** | Card number. Missing = 422 card_required. Encrypted at rest for the subscription; never logged. |
| `order.ccexp` | string MMYY | **yes** | Card expiry, 4 digits. Missing = 422 card_required. |
| `order.cvv` | string 3..4 | no | Security code, sent with the verification charge, never stored. |
| `order.subscription_optin` | object | **yes** | The subscription the customer selected. Missing = 422 subscription_consent_required. |
| `order.subscription_optin.block_id` | string 1..128 | **yes** | Id of the published checkout.payment block in special-pre-auth mode (422 subscription_consent_required when it is not that block). |
| `order.subscription_optin.product_id` | uuid | **yes** | Subscription product of the account; must equal the block's subscriptionProduct (422 pre_auth_not_configured otherwise) and be active (422 subscription_unavailable). |
| `order.subscription_optin.assignment_source` | "cart" \| "subscription_block" | no | Accepted (charge schema); the enrollment is recorded as special pre-auth whatever it says. |
| `order.subscription_optin.text_hash` | 64 lower-case hex | **yes** | SHA-256 of consentText (422 subscription_consent_mismatch when it differs). |
| `order.subscription_optin.consented_at` | ISO-8601 datetime with offset | **yes** | When the customer consented. |
| `order.consents` | object[] <= 30 | **yes** | The checkbox records. Every required checkout.checkbox block of the published checkout needs a checked entry with its block_id, purpose and key (422 required_consent_missing otherwise; a checkout with no required checkbox is refused the same way). |
| `order.consents[].block_id` | string 1..128 | **yes** | Checkbox block id. |
| `order.consents[].purpose` | "terms" \| "marketing_email" \| "marketing_sms" \| "custom" | **yes** | Must equal the block's purpose (default terms). |
| `order.consents[].key` | string 1..64 | **yes** | Must equal the block's key (default terms). |
| `order.consents[].checked` | boolean | **yes** | Must be true for a required block. |
| `order.consents[].text_hash` | 64 lower-case hex | **yes** | SHA-256 of the checkbox text as rendered. |
| `order.threeDsSessionId` | uuid | no | A completed /v1/3ds session. Re-submit the same body with it after a 3DS challenge (status awaiting_3ds) to continue the verification. An invalid value is dropped. |
| `order.threeDsChallenge` | "skip" \| "return" \| "decline" | no | Per-order override of the 3DS integration's browser-step setting. An invalid value is dropped. |
| `order.browser` | object | no | 3DS browser data: acceptHeader (<= 2048), userAgent (<= 2048), language (<= 8), colorDepth, screenWidth, screenHeight, timezoneOffset (integers), javaEnabled, javascriptEnabled (booleans), ip (<= 45). Invalid = dropped. |
| `order.cavv / eci / xid / cardholder_auth / three_ds_version / directory_server_id` | string (<= 512 / 8 / 512 / 32 / 16 / 128) | no | External 3DS result passthrough, as on POST /v1/charge. |
| `order.firstName / lastName` | string <= 128 | no | Cardholder name. |
| `order.email` | e-mail <= 256 | no | Customer e-mail. |
| `order.address1 / city / state / zip / country` | string (<= 256 / 128 / 64 / 32 / 64) | no | Billing address. |
| `order.shippingAddress` | object (strict) | no | firstName, lastName (<= 128), address1 (required, 1..256), address2 (<= 256), city (required, 1..128), state (<= 64), zip (required, 1..32), country (required, 2 letters), phone (<= 32). Unknown keys are a 400. |
| `order.phone / ipaddress / useragent` | string (<= 32 / 64 / 1024) | no | Fraud-scoring fields forwarded with the verification charge. |
| `order.currency` | string, 3 chars | no | Validated, not used (always USD). |
| `order.channel / preferredMid / description / fl` | string <= 32 / string <= 256 / string <= 256 / boolean | no | Accepted by the charge schema; the verification sets its own channel (pre-auth) and pins its own gateway. |
| `order.atri` | uuid | no | Accepted but not used: the route comes from the store's payment configuration. |
| `order.stripeMode / stripePaymentMethod / checkoutReturnUrl / stripeReturnUrl` | see POST /v1/charge | no | Accepted by the charge schema, not used by the verification (NMI only). |
| `order.products / upsells / discount` | see POST /v1/charge | no | Accepted and validated (upsells <= 20 lines, discount {code, amount_cents, redemption_id}), not used by the verification (products is dropped). |
| `order.trafficSource / storefrontUrl / fbclid / ttclid` | string (<= 32 / 256 / 512 / 512) | no | Attribution; storefrontUrl also helps resolve the store. Invalid values are dropped. |
| `order.gatewayId / midId` | never | no | Refused: 400 {"error":"invalid_charge_target","message":"Gateway targeting is not supported for pre-auth; use the store payment configuration"}. |
| `order.routeID` | never | no | Refused: 400 {"error":"invalid_charge_target","message":"Route targeting is not supported for pre-auth; use the store payment configuration"}. |
| `idempotencyKey` | string 8..128 | **yes** | Stable key of this checkout attempt. Deduplication is by account, shop and order.orderId, even when this key changes. |
| `consentText` | string 1..16384 | **yes** | The exact recurring-consent text shown to the customer; its SHA-256 must equal subscription_optin.text_hash. Stored for audit with the checkbox records. |

**Request body**

```json
{
  "order": {
    "orderId": "example-verification-001",
    "crm": "nmi",
    "amount": 0.99,
    "currency": "USD",
    "checkoutShopId": "66666666-7777-4888-8999-aaaaaaaaaaaa",
    "checkoutCartToken": "example-cart-token",
    "ccnumber": "4111111111111111",
    "ccexp": "1230",
    "cvv": "123",
    "subscription_optin": {
      "block_id": "payment",
      "product_id": "77777777-8888-4999-8aaa-bbbbbbbbbbbb",
      "text_hash": "9998b12437bdfbd29c75aff2d05c3243cf34bb1e4c8e78edb9409e80954454c3",
      "consented_at": "2026-10-18T12:00:00Z"
    },
    "consents": [
      {
        "block_id": "subscription-consent",
        "purpose": "terms",
        "key": "terms",
        "checked": true,
        "text_hash": "9998b12437bdfbd29c75aff2d05c3243cf34bb1e4c8e78edb9409e80954454c3"
      }
    ]
  },
  "idempotencyKey": "example-verification-001",
  "consentText": "I agree to the example subscription at USD 9.99 per month, beginning today, until cancelled."
}
```

**Response**

```json
{
  "verificationId": "44444444-5555-4666-8777-888888888888",
  "status": "ready",
  "result": {
    "isSuccess": true,
    "orderId": "pa-44444444-5555-4666-8777-888888888888",
    "orderIdSupplier": "10000001",
    "declineReason": null,
    "midIdUsed": "55555555-6666-4777-8888-999999999999",
    "midNameUsed": "Example MID 1"
  },
  "continuationToken": "44444444-5555-4666-8777-888888888888.Zm9vYmFyZm9vYmFyZm9vYmFyZm9vYmFyZm9vYmFyZm9v",
  "card": {
    "brand": "visa",
    "last4": "1111",
    "maskedNumber": "•••• •••• •••• 1111"
  }
}
```

| response field | type | description |
|---|---|---|
| `verificationId` | uuid | The verification (one per account, shop and order.orderId). |
| `status` | created \| charging \| awaiting_3ds \| declined \| charge_unknown \| reversing \| reversal_failed \| reversal_unknown \| reversed \| enrolling \| enrollment_failed \| ready \| sale_started | Persisted state. Continue the merchandise sale only when status is ready or sale_started and continuationToken is present. awaiting_3ds: run the 3DS step and re-submit the same body with order.threeDsSessionId. charge_unknown / reversal_unknown: the bank outcome is not known; never start a new verification or charge, wait for reconciliation. A test card always ends declined. |
| `result` | object | The gateway result of the USD 0.99 verification charge, when one was made: isSuccess, orderId ("pa-<verificationId>"), orderIdSupplier, declineReason, midIdUsed, midNameUsed, and threeDs / rejected / isTest when they apply (same shape as a POST /v1/charge result). |
| `continuationToken` | string | Only with ready or sale_started: "<verificationId>.<43-char MAC>". Send it on the single normal POST /v1/charge order, without card number, security code or subscription_optin. Bound to the account and shop, and on first use to that order's id, amount, currency, basket and customer. Expires 30 minutes after the verification was created. |
| `card` | object | Only with the token: brand, last4 and maskedNumber of the verified card. |

**Errors**

- `400` {"error":"Invalid pre-auth request"}: the body fails the schema (for example idempotencyKey shorter than 8, consentText missing, a bad order field).
- `400` {"error":"invalid_charge_target","message":"Route targeting is not supported for pre-auth; use the store payment configuration"} when order.routeID is present; same error with "Gateway targeting is not supported for pre-auth; use the store payment configuration" for order.gatewayId or order.midId. Nothing is started.
- `401` {"error":"Invalid API key"}: no key, an unknown or inactive key, or a key without an account.
- `403` {"error":"Banned","message":"..."} when the account owner is banned; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"card_payments_disabled"} when card payments are off for the store's payment route.
- `404` {"error":"Store unavailable"}: the store is unknown, inactive or archived.
- `409` {"error":"verification_conflict"} (same account, shop and orderId with a different card, product or consent), {"error":"verification_in_progress"} (a concurrent call holds the verification), {"error":"verification_state_conflict"}.
- `410` {"error":"verification_expired"}: the verification is older than 30 minutes.
- `422` {"error":"<code>"} with code subscription_consent_required (no checkoutShopId or subscription_optin, or the opt-in does not match the special pre-auth block), subscription_consent_mismatch (consentText hash differs), card_required, pre_auth_not_configured (no published special-pre-auth payment block with this product), required_consent_missing, subscription_unavailable, pre_auth_route_unavailable (no active payment route owned by the account), pre_auth_mid_unavailable (no NMI gateway on the route).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 30 requests per minute from one IP (route limit).
- `503` {"error":"pre_auth_unavailable","requestId":"..."} for any unexpected failure, or {"error":"verification_claim_failed"}. Never assume the charge or the reversal failed at the bank: replay the same body.

**Gotchas**

- Replay, never retry fresh: send the same body (same order.orderId and card) to read or resume a verification. A replay never charges twice: only a verification in created state (or awaiting_3ds with a threeDsSessionId) is charged.
- A refusal raised while charging (for example card_payments_disabled or pre_auth_mid_unavailable) leaves the verification in charge_unknown: a replay then answers 200 with status charge_unknown and does not charge. Fix the configuration and use a new order.orderId.
- Only NMI gateways can run the verification (immediate void and the stored-credential chain for later rebills). A mixed ATRI pins the verification to an eligible NMI gateway; none = pre_auth_mid_unavailable.
- Transactions are reported with source pre-auth, apart from sales, recoveries and rebills. The reversal is booked as a refund of 99 cents without blacklisting or subscription cancellation.
- Card number and expiry are encrypted at rest for the subscription; the security code is never stored. Later subscription charges use the original gateway and USD only.
- A test card never reaches ready: the verification ends declined.
- The enrollment failing leaves status enrollment_failed; a replay retries the enrollment only (no new charge).
- Checkout subscription priority: special pre-auth > subscription product in the signed cart > selected subscription product block > account product percentage attachment. Only one subscription is attached to a sale.
- The example uses fake ids and a test card. Take block, product ids and consent text only from the published checkout and the customer's real consent.

##### `GET /v2/rebill-batches`

**Scope** `charges.read` - **List reference rebill batches**

List up to 20 batches created by this key, unfinished ones first, then newest. With requestId, find the batch admitted for that request (to recover a lost 202).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Only the batch created with this requestId. |

**Response**

```json
{
  "batches": [
    {
      "id": "44444444-4444-4444-8444-444444444444",
      "request_id": "11111111-1111-4111-8111-111111111111",
      "operation_day": "2026-11-24",
      "cancel_requested": false,
      "created_at": "2026-11-24T10:00:00.000Z",
      "updated_at": "2026-11-24T10:05:00.000Z",
      "total": 100,
      "processed": 40,
      "unknown": 0,
      "actionRequired": 0,
      "failed": 2,
      "queued": 59,
      "running": 1
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `batches[]` | object[] | id, request_id, operation_day, cancel_requested, created_at, updated_at, total, processed, unknown, actionRequired, failed, queued, running. |

**Errors**

- `400` `Invalid batch request` (malformed id or body).
- `401` `Invalid API key` when no key is sent.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key unavailable` (unknown or inactive key, a login token, or a key without an owner); `API key scope denied` when the key lacks charges.read; `Account unavailable` when the owner is banned or has no role.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Batch outcome unavailable; reconnect using the same request ID` when the 15-second control transaction or the database fails; nothing is acknowledged, so read the batch again (or replay the same requestId) before acting.

**Gotchas**

- List rows carry counts only (total, processed, unknown, actionRequired, failed, queued, running), no items, status, approved, declined or cancelled: read GET /v2/rebill-batches/:id for those.
- An empty list for a requestId means that request was never admitted: it is safe to send it again with the same requestId.

##### `POST /v2/rebill-batches`

**Scope** `charges.write` - **Queue reference rebills**

Admit a batch of 1-100 rebills, each referencing an existing card transaction of this account, for background dispatch. No card data is sent: the card of the source transaction is reused. Answers 202 after the batch is durably stored.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Stable retry identity for this key. Replaying the same requestId with the same orders returns the existing batch; different orders answer 409. |
| `orders` | object[] | **yes** | 1-100 strict items (an unknown key is a 400). |
| `orders[].orderId` | string | **yes** | 1-128 characters, must not start with "pa-". Must equal the order id of the source transaction. |
| `orders[].sourceTransactionId` | uuid | **yes** | An NMI, non-test transaction of this account that kept its card data. |
| `orders[].amountCents` | integer | **yes** | Amount in minor units, 1-100000000. |
| `orders[].currency` | string | **yes** | Three letters, uppercased. |
| `orders[].atri` | uuid | no | Active ATRI of this account to route through. Omitted: the key's default ATRI, else the account's default active ATRI (422 when none). |
| `orders[].preferredMid` | string | no | Name of an activated MID of this account to prefer, 1-256 characters after trim. |
| `orders[].fl` | boolean | no | Friendlies classification carried to the charge. false or omitted leaves the request fingerprint unchanged. |

**Request body**

```json
{
  "requestId": "11111111-1111-4111-8111-111111111111",
  "orders": [
    {
      "orderId": "ORDER-10001",
      "sourceTransactionId": "22222222-2222-4222-8222-222222222222",
      "amountCents": 1999,
      "currency": "USD",
      "fl": false
    }
  ]
}
```

**Response** `202`

```json
{
  "batch": {
    "id": "44444444-4444-4444-8444-444444444444",
    "request_id": "11111111-1111-4111-8111-111111111111",
    "operation_day": "2026-11-24",
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "total": 1,
    "processed": 0,
    "queued": 1,
    "running": 0,
    "approved": 0,
    "declined": 0,
    "failed": 0,
    "unknown": 0,
    "actionRequired": 0,
    "cancelled": 0,
    "status": "queued",
    "items": [
      {
        "position": 0,
        "order_id": "ORDER-10001",
        "source_transaction_id": "22222222-2222-4222-8222-222222222222",
        "amount_cents": 1999,
        "currency": "USD",
        "atri": "33333333-3333-4333-8333-333333333333",
        "preferred_mid": null,
        "fl": false,
        "state": "queued",
        "transaction_id": null,
        "intent_id": null,
        "reason": null,
        "updated_at": "2026-11-24T10:00:00.000Z"
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `batch.status` | string | running (or cancelling) while an item is dispatching; queued while items wait; needs_review when an item is unknown or action_required; cancelled after a cancel; else complete. |
| `batch.total / processed / queued / running` | integer | Item counts; processed = total - queued - running. |
| `batch.approved / declined / failed / unknown / actionRequired / cancelled` | integer | Items per final state; failed counts items refused before payment (state rejected). |
| `batch.items[]` | object[] | position, order_id, source_transaction_id, amount_cents, currency, atri, preferred_mid, fl, state (queued, dispatching, approved, declined, rejected, unknown, action_required, cancelled), transaction_id, intent_id, reason, updated_at. No card data. |

**Errors**

- `400` `Invalid batch request` (malformed id or body).
- `401` `Invalid API key` when no key is sent.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `{"error":"API key unavailable"}` (unknown or inactive key, a login token, or a key without an owner); `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"}` when the key lacks charges.write; `{"error":"Account unavailable"}` when the owner is banned or has no role. Checked before anything else, including the admission switch.
- `409` `Request ID already used with different references`; `Another reference rebill batch is active` (the account still has queued or dispatching items); `A reference operation already belongs to another batch` (same order id and amount already used by this key on the same UTC day).
- `413` Body over 64 KiB.
- `422` `Duplicate financial operation in batch` (same order id and amount twice); `One or more source references are unavailable`; `No owned active routing reference configured`; `One or more routing references are unavailable`; `One or more MID references are unavailable`.
- `429` More than 20 creations per minute from one IP.
- `503` `{"error":"Reference rebill batch admission is disabled"}` when background jobs are off (answered only to a key that may create batches); `{"error":"Batch outcome unavailable; reconnect using the same request ID"}` when the 15-second control transaction or the database fails; nothing is acknowledged, so read the batch again (or replay the same requestId) before acting.

**Gotchas**

- All references are validated before anything is stored: one bad item rejects the whole batch.
- One financial operation per key, order id, amount and UTC day: resubmitting it in a new batch is a 409.
- Only one batch per account can be dispatching at a time.
- An unknown outcome is never retried automatically: it means the payment may have happened (reason `Payment outcome unconfirmed; do not resubmit`). Reconcile it; do not submit the same order again.
- The background worker charges each item as a rebill (channel rebill) on the stored card of its source transaction; creation needs background jobs on, while reads, cancel and resume keep working when they are paused.

##### `GET /v2/rebill-batches/:id`

**Scope** `charges.read` - **Read a reference rebill batch**

Read one batch of this key with its counters, status and every item (at most 100), without card data.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Batch id from the creation or list answer. |

**Response**

```json
{
  "batch": {
    "id": "44444444-4444-4444-8444-444444444444",
    "request_id": "11111111-1111-4111-8111-111111111111",
    "operation_day": "2026-11-24",
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "total": 1,
    "processed": 1,
    "queued": 0,
    "running": 0,
    "approved": 1,
    "declined": 0,
    "failed": 0,
    "unknown": 0,
    "actionRequired": 0,
    "cancelled": 0,
    "status": "complete",
    "items": [
      {
        "position": 0,
        "order_id": "ORDER-10001",
        "source_transaction_id": "22222222-2222-4222-8222-222222222222",
        "amount_cents": 1999,
        "currency": "USD",
        "atri": "33333333-3333-4333-8333-333333333333",
        "preferred_mid": null,
        "fl": false,
        "state": "approved",
        "transaction_id": "55555555-5555-4555-8555-555555555555",
        "intent_id": "66666666-6666-4666-8666-666666666666",
        "reason": null,
        "updated_at": "2026-11-24T10:00:00.000Z"
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `batch.status` | string | running (or cancelling) while an item is dispatching; queued while items wait; needs_review when an item is unknown or action_required; cancelled after a cancel; else complete. |
| `batch.total / processed / queued / running` | integer | Item counts; processed = total - queued - running. |
| `batch.approved / declined / failed / unknown / actionRequired / cancelled` | integer | Items per final state; failed counts items refused before payment (state rejected). |
| `batch.items[]` | object[] | position, order_id, source_transaction_id, amount_cents, currency, atri, preferred_mid, fl, state (queued, dispatching, approved, declined, rejected, unknown, action_required, cancelled), transaction_id, intent_id, reason, updated_at. No card data. |

**Errors**

- `400` `Invalid batch request` (malformed id or body).
- `401` `Invalid API key` when no key is sent.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key unavailable` (unknown or inactive key, a login token, or a key without an owner); `API key scope denied` when the key lacks charges.read; `Account unavailable` when the owner is banned or has no role.
- `404` `Batch not found` (unknown id, or a batch of another key or account).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Batch outcome unavailable; reconnect using the same request ID` when the 15-second control transaction or the database fails; nothing is acknowledged, so read the batch again (or replay the same requestId) before acting.

**Gotchas**

- An unknown outcome is never retried automatically: it means the payment may have happened (reason `Payment outcome unconfirmed; do not resubmit`). Reconcile it; do not submit the same order again.
- action_required means a 3-D Secure challenge would be needed; it cannot be completed in a batch.

##### `POST /v2/rebill-batches/:id/cancel`

**Scope** `charges.write` - **Cancel undispatched rebills**

Mark the batch cancelled and cancel its queued items (reason `Cancelled before dispatch`). Items already dispatching or finished are not touched or retried.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Batch id. |

**Response**

```json
{
  "batch": {
    "id": "44444444-4444-4444-8444-444444444444",
    "request_id": "11111111-1111-4111-8111-111111111111",
    "operation_day": "2026-11-24",
    "cancel_requested": true,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "total": 1,
    "processed": 1,
    "queued": 0,
    "running": 0,
    "approved": 0,
    "declined": 0,
    "failed": 0,
    "unknown": 0,
    "actionRequired": 0,
    "cancelled": 1,
    "status": "cancelled",
    "items": [
      {
        "position": 0,
        "order_id": "ORDER-10001",
        "source_transaction_id": "22222222-2222-4222-8222-222222222222",
        "amount_cents": 1999,
        "currency": "USD",
        "atri": "33333333-3333-4333-8333-333333333333",
        "preferred_mid": null,
        "fl": false,
        "state": "cancelled",
        "transaction_id": null,
        "intent_id": null,
        "reason": "Cancelled before dispatch",
        "updated_at": "2026-11-24T10:00:00.000Z"
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `batch.status` | string | running (or cancelling) while an item is dispatching; queued while items wait; needs_review when an item is unknown or action_required; cancelled after a cancel; else complete. |
| `batch.total / processed / queued / running` | integer | Item counts; processed = total - queued - running. |
| `batch.approved / declined / failed / unknown / actionRequired / cancelled` | integer | Items per final state; failed counts items refused before payment (state rejected). |
| `batch.items[]` | object[] | position, order_id, source_transaction_id, amount_cents, currency, atri, preferred_mid, fl, state (queued, dispatching, approved, declined, rejected, unknown, action_required, cancelled), transaction_id, intent_id, reason, updated_at. No card data. |

**Errors**

- `400` `Invalid batch request` (malformed id or body).
- `401` `Invalid API key` when no key is sent.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key unavailable` (unknown or inactive key, a login token, or a key without an owner); `API key scope denied` when the key lacks charges.write; `Account unavailable` when the owner is banned or has no role.
- `404` `Batch not found` (unknown id, or a batch of another key or account).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Batch outcome unavailable; reconnect using the same request ID` when the 15-second control transaction or the database fails; nothing is acknowledged, so read the batch again (or replay the same requestId) before acting.

**Gotchas**

- Idempotent: cancelling again returns the same batch.
- The status reads cancelling while an item is still dispatching.

##### `POST /v2/rebill-batches/:id/resume`

**Scope** `charges.write` - **Re-check unresolved rebills**

Schedule an immediate reconciliation of the batch's unknown and action_required items, then return the batch with dispatchRetried: false. Nothing is charged again.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Batch id. |

**Response**

```json
{
  "batch": {
    "id": "44444444-4444-4444-8444-444444444444",
    "request_id": "11111111-1111-4111-8111-111111111111",
    "operation_day": "2026-11-24",
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "total": 1,
    "processed": 1,
    "queued": 0,
    "running": 0,
    "approved": 0,
    "declined": 0,
    "failed": 0,
    "unknown": 1,
    "actionRequired": 0,
    "cancelled": 0,
    "status": "needs_review",
    "items": [
      {
        "position": 0,
        "order_id": "ORDER-10001",
        "source_transaction_id": "22222222-2222-4222-8222-222222222222",
        "amount_cents": 1999,
        "currency": "USD",
        "atri": "33333333-3333-4333-8333-333333333333",
        "preferred_mid": null,
        "fl": false,
        "state": "unknown",
        "transaction_id": null,
        "intent_id": null,
        "reason": "Payment outcome unconfirmed; do not resubmit",
        "updated_at": "2026-11-24T10:00:00.000Z"
      }
    ]
  },
  "dispatchRetried": false
}
```

| response field | type | description |
|---|---|---|
| `batch.status` | string | running (or cancelling) while an item is dispatching; queued while items wait; needs_review when an item is unknown or action_required; cancelled after a cancel; else complete. |
| `batch.total / processed / queued / running` | integer | Item counts; processed = total - queued - running. |
| `batch.approved / declined / failed / unknown / actionRequired / cancelled` | integer | Items per final state; failed counts items refused before payment (state rejected). |
| `batch.items[]` | object[] | position, order_id, source_transaction_id, amount_cents, currency, atri, preferred_mid, fl, state (queued, dispatching, approved, declined, rejected, unknown, action_required, cancelled), transaction_id, intent_id, reason, updated_at. No card data. |
| `dispatchRetried` | boolean | Always false. |

**Errors**

- `400` `Invalid batch request` (malformed id or body).
- `401` `Invalid API key` when no key is sent.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key unavailable` (unknown or inactive key, a login token, or a key without an owner); `API key scope denied` when the key lacks charges.write; `Account unavailable` when the owner is banned or has no role.
- `404` `Batch not found` (unknown id, or a batch of another key or account).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Batch outcome unavailable; reconnect using the same request ID` when the 15-second control transaction or the database fails; nothing is acknowledged, so read the batch again (or replay the same requestId) before acting.

**Gotchas**

- Observation only: it never re-dispatches an intent or a cancelled item. Read the batch again later to see reconciled states.

#### 3-D Secure

Run a 3-D Secure authentication session before a charge. The 3-D Secure integrations and their analytics are under Settings > Integrations.

##### `POST /v1/3ds/sessions`

**Scope** `charges.write` - **Start a 3DS authentication session**

Starts 3DS for a card, order and real browser context with the effective account/shop provider. With PAAY doubleRebillAuthentication enabled, creates or resumes a pair: one authentication for the straight amount and a second controlled by secondThreeDsAmountMode (same_as_original, subscription_product or custom). The intended future subscription amount is recorded separately from its authentication amount. Returns a current session plus sessions[] and groupId for the pair; other integrations and single mode retain {session}. Call POST /v1/charge with the same orderId and threeDsSessionId to allocate and consume proofs.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | string | **yes** | 1..128 chars. Your order reference (also the provider's merchant transaction reference). |
| `amount` | number | **yes** | Positive finite amount in MAJOR units (49.99). Converted to cents. |
| `currency` | string; default `USD` | no | 3-letter ISO 4217 (upper-cased). |
| `ccnumber` | string | **yes** | Card PAN, 12..19 characters (non-digits are stripped). Never stored in clear (masked first6..last4 on the session). |
| `ccexp` | string | **yes** | Expiry MMYY (4 digits). |
| `firstName / lastName` | string | no | <=128 each; joined as the cardholder name. |
| `email` | string | no | Valid email <=256 - strongly improves frictionless odds. |
| `phone` | string | no | <=32. v3.9.7 - sent to the provider as EMV mobilePhone { cc, subscriber }: the calling code follows `country` (FR 33, BE 32, CH 41, DE 49, ES 34, IT 39, GB 44, NL 31, US / CA 1 ...), a number written +33 ... / 0033 ... names its own code, the national trunk prefix is dropped, and a number that cannot be normalised is omitted. |
| `address1 / city / state / zip / country` | string | no | Billing address (<=256 / <=128 / <=64 / <=32 / <=64). country alpha-2 preferred; common names are normalised. v3.9.2 section 2 - `country` is also the customer country the ATRI's 3DS profile's `country` rules match on (folded to ISO-2 by the engine; the card's BIN feeds the BIN / issuer / issuer_country rules), recorded on this session's decision row. v3.9.7 - `state` reaches the provider only as an ISO 3166-2 subdivision code: a US / CA two-letter code (or a state / province name) as its code, a French region or departement name mapped to its region code (Ile-de-France -> IDF, Loire-Atlantique -> PDL, Corse -> 20R, the overseas departements -> 971-976), any other value omitted - never truncated to three characters (the directory server refused every French authentication that way, errorCode 304). Send what your storefront holds; cocoapi maps. |
| `ipaddress` | string; default `request IP` | no | <=64. Cardholder IP; used as browser.ip when that is absent (else the request IP). |
| `useragent` | string | no | <=2048. Used as browser.userAgent when that is absent. |
| `browser` | object; default `{}` | no | EMV browserInfo collected client-side: {acceptHeader <=2048, userAgent <=2048, language <=8, colorDepth int, screenWidth int, screenHeight int, timezoneOffset int (minutes, positive = behind UTC), javaEnabled bool, javascriptEnabled bool, ip <=45}. Unknown keys stripped. Without it a server-to-server call gets a best-effort authentication (some providers then answer unavailable). |
| `challengePreference` | enum: no-preference\|no-challenge\|challenge-requested\|challenge-mandated; default `integration's challengePreference` | no | EMV threeDSRequestorChallengeInd. Overrides the integration's configured default for this session; the issuer has the final say. A BIN Intelligence 3DS rule of the ATRI (challenge requested / mandated) overrides this value - see `atri`. |
| `atri` | uuid; default `API key's default_trip_id, then the account's default ATRI` | no | ATRI the charge will route on, so its 3DS rule profile (BIN, issuer, issuer country and customer country rules: challenge requested or mandated) sets this session's challenge preference. Must belong to the key's account, else 400 `Unknown ATRI for this API key`. A no_3ds rule cannot un-start a session the checkout asked for (logged as not applied). |
| `checkoutShopId` | uuid | no | Optional owned checkout shop context used to resolve its 3DS provider selection. |
| `subscriptionProductId` | uuid | no | Optional active subscription product of this account. Its first configured plan step and USD currency determine the intended future payment. The second authentication amount follows the PAAY integration setting. An unavailable explicit product fails rather than guessing another subscription. |
| `storefrontUrl` | string | no | Optional absolute URL, at most 2048 characters, used to match automatic subscription attachment rules when no subscriptionProductId is supplied. |

**Request body**

```json
{
  "orderId": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
  "amount": 49.99,
  "currency": "USD",
  "ccnumber": "4111111111111111",
  "ccexp": "1228",
  "firstName": "Jane",
  "lastName": "Doe",
  "email": "jane.doe@example.com",
  "phone": "+12345550100",
  "address1": "1 Main St",
  "city": "Austin",
  "state": "TX",
  "zip": "78701",
  "country": "US",
  "ipaddress": "203.0.113.10",
  "browser": {
    "acceptHeader": "text/html,application/xhtml+xml,*/*;q=0.8",
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...",
    "language": "en-US",
    "colorDepth": 24,
    "screenWidth": 1440,
    "screenHeight": 900,
    "timezoneOffset": 300,
    "javaEnabled": false,
    "javascriptEnabled": true
  },
  "challengePreference": "no-preference"
}
```

**Response**

```json
{
  "session": {
    "sessionId": "00000000-0000-4000-8000-000000000001",
    "provider": "paay_3ds",
    "status": "challenge",
    "next": {
      "type": "challenge",
      "url": "https://acs.example.invalid/challenge",
      "fields": {
        "creq": "EXAMPLE_CHALLENGE_REQUEST"
      }
    },
    "auth": null,
    "usable": false,
    "expiresAt": "2026-10-25T13:00:00.000Z"
  },
  "sessions": [
    {
      "sessionId": "00000000-0000-4000-8000-000000000001",
      "provider": "paay_3ds",
      "status": "challenge",
      "next": {
        "type": "challenge",
        "url": "https://acs.example.invalid/challenge",
        "fields": {
          "creq": "EXAMPLE_CHALLENGE_REQUEST"
        }
      },
      "auth": null,
      "usable": false,
      "expiresAt": "2026-10-25T13:00:00.000Z"
    },
    {
      "sessionId": "00000000-0000-4000-8000-000000000002",
      "provider": "paay_3ds",
      "status": "authenticated",
      "next": null,
      "auth": {
        "status": "Y",
        "cavv": "EXAMPLE_AUTHENTICATION_VALUE",
        "eci": "05",
        "dsTransId": "00000000-0000-4000-8000-000000000003",
        "acsTransId": null,
        "threeDsServerTransId": null,
        "version": "2.2.0",
        "liabilityShift": true,
        "reason": null,
        "flow": "frictionless"
      },
      "usable": true,
      "expiresAt": "2026-10-25T13:00:00.000Z"
    }
  ],
  "groupId": "00000000-0000-5000-a000-000000000004"
}
```

| response field | type | description |
|---|---|---|
| `session.sessionId` | uuid | The current session ID. Pass it as threeDsSessionId when resuming the same order through POST /v1/charge. A PAAY pair can require the other session on the next resume. |
| `session.provider` | enum: evervault_3ds\|paay_3ds\|threedsecureio_3ds\|vgs_3ds | The account's active 3DS integration. |
| `session.status` | string | pending, method or challenge means work remains; authenticated, attempted or informational is a terminal provider result, but usable is the authoritative proof check; failed, unavailable, error, expired and consumed are not usable. An error means the provider refused the authentication request and it is excluded from the recorded authentication count. |
| `session.next` | object \| null | Provider-neutral browser action. method: POST fields to url in a hidden iframe, then complete stage=method with methodCompleted reflecting callback or timeout. challenge: show the bank iframe using url/fields or supplied provider HTML, then complete stage=challenge. sdk: run the specified provider SDK/hosted URL, then complete stage=challenge. Optional done is only a completion-message hint: verify the expected active frame/source/origin and confirm the result through the authenticated API. Null when this slot has no browser action; another slot in sessions[] may still have one. |
| `session.auth` | object \| null | Normalized terminal outcome: status, cavv, eci, dsTransId, acsTransId, threeDsServerTransId, version, liabilityShift, reason and optional flow. Null before an outcome exists. Cryptogram material is cleared from the session atomically on consumption, while outcome metadata remains for history. Treat this API-key-authenticated response as server-side payment data; the admin customer inventory never returns the cryptogram. |
| `session.usable` | boolean | True only for authenticated/attempted/informational status, a stored CAVV and ECI, no consumption, and an unexpired local proof deadline. Group readiness here describes the provider result; checkout allocation must still settle both slots before making an unused proof eligible for rebill. |
| `session.expiresAt` | string (ISO 8601) | The browser-session deadline, one hour from request creation. Stop browser work at this deadline. A successful grouped proof has a separate local holding deadline, shown by the admin customer inventory; expiresAt here is not a network or issuer validity guarantee. |
| `sessions` | array \| absent | Present for a PAAY double-authentication group. Full SessionView for each recorded slot, in straight-then-rebill order. Normally two slots; a partial creation failure may leave fewer. Each has its own sessionId, outcome and next action. Completing or abandoning one slot does not complete the other. No purpose field is added to SessionView. |
| `groupId` | uuid \| absent | Identifier binding the two PAAY authentication slots to this checkout/card/payment context. Repeating the same start context reuses the group rather than starting another pair. |
| `session.checkoutAuthentication` | object \| absent | Display metadata for a grouped checkout slot: step, total, purpose, amountCents and currency describe the authentication actually shown by the bank. The second slot can additionally carry intendedRebillAmountCents and intendedRebillCurrency for the separately bound future payment. None of these display fields authorize a different sale amount. |
| `session.pendingTimedOut` | boolean \| absent | True only after the server atomically retired optional PAAY work at its recorded deadline. Distinguishes this recoverable timeout from a naturally expired session. It is response metadata, not a request permission: recovery must re-read this API state and resume the same order/session with the existing idempotency key. It neither confirms bank approval nor authorizes retrying an unknown payment. |
| `backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. |
| `session.pendingDeadlineAt` | string (ISO 8601) \| absent | Server-owned deadline for optional silent PAAY authentication of the current purchase, default 45 seconds from its durable creation. Secondary background work has its own lifetime and neither extends nor cancels this deadline. Resume the SAME order and session through the normal charge path; the server rechecks required authentication and current provider state. Real issuer challenges, known negative results and mandatory authentication retain their controls. This deadline never approves a sale or authorizes retrying an unknown bank result. |

**Errors**

- `400` `Invalid request` with `details` (zod flatten) for a missing orderId, amount, ccnumber or ccexp, ccexp not MMYY, a bad email, URL or UUID, or an unknown challengePreference; `Unknown ATRI for this API key` when atri is not an ATRI of the key's account.
- `401` `Missing API key` or `Invalid API key`. `API key is not attached to an account` for a legacy key without an account.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned.
- `409` `3DS authentication is disabled for straight payments` (code `three_ds_straight_disabled`) when the straight 3DS mode is off; `No 3DS provider enabled for this account` (with a `hint` pointing to the Integrations 3DS page) when no fully configured 3DS integration is enabled.
- `429` Per-IP rate limit exceeded (RATE_LIMIT_CHARGE, default 3000 requests per minute for each of these session routes).
- `500` `Internal Server Error` with a `requestId`, for example when a PAAY authentication pair cannot be created (the subscriptionProductId is unavailable, the custom second amount is invalid).
- `503` `Service temporarily unavailable` (detail `authentication backend error`) when the key lookup fails.

**Gotchas**

- Flow: start -> (next.type method -> /complete {stage:"method"}) -> (next.type challenge|sdk -> /complete {stage:"challenge"}) -> status authenticated/attempted/informational with usable:true -> POST /v1/charge {..., threeDsSessionId}. GET /v1/3ds/sessions/:id can replace /complete when the ACS callback already landed.
- A provider error is NOT a 5xx: the session ends status "unavailable" (the directory server / the issuer could not authenticate) or - v3.9.7 - "error" (the provider / the directory server refused cocoapi's own request: a 4xx on the payload, a network failure before any ACS; never billed, never a card cooldown on the decline that follows), both with auth.reason and usable:false (200). Decide yourself whether to charge without 3DS.
- `amount` is in major units, unlike amount_cents everywhere in the admin API.
- One session = one charge: consuming stamps it "consumed"; a re-submitted parked order re-uses the same session id (the dispatcher handles that), but a second distinct charge needs a new session.
- Callbacks the ACS will hit are built from API_PUBLIC_URL (or the request origin): the API must be publicly reachable at that base for challenges to complete.
- PAAY double authentication starts two independent durable slots. The primary usable proof can authorize the current sale without waiting for the secondary. The secondary can finish in the background; it never rewrites the proof or payment result already dispatched. optimizeThreeDsTokens reserves a sole usable proof only once both results are terminal and authentication is optional. A ready primary with a still-pending sibling is used for the sale. Strict account/BIN requirements remain enforced.
- Browser work expires after one hour. Successful grouped proofs use the configured local holding limit (rebillTokenValidityDays, 1-90 days from request creation); issuer/network/processor acceptance can be shorter. Consumption is atomic and single use. Used proofs are not restored after a declined or uncertain payment.
- Authentication fees are calculated at read time from the current provider rate and the recorded authentication count: a completed pair normally records two attempts, an error slot is excluded, and later consumption of a saved proof records zero new authentications. Explicit sessions that are never attached to a transaction remain visible in the session inventory rather than a transaction fee total.
- The double-authentication toggle controls creation of new pairs. Turning it off does not discard compatible existing stock while PAAY remains active. The sole-proof optimization applies only after both results are terminal; it never withholds an already usable primary merely because its sibling is pending.
- PAAY secondThreeDsAmountMode defaults to subscription_product for existing settings. same_as_original uses the original final purchase amount and currency; subscription_product uses the first matching subscription plan step (or the original purchase when no plan matches); custom uses secondThreeDsCustomAmount in the original purchase currency. Only the second slot gets the separate intended future-payment binding. Rebill consumption matches that intended amount, requires both authentication and intended currencies to match the actual payment, and preserves card, merchant, integration, expiry and one-time-use checks. Existing proofs are unchanged. This configuration does not change the actual subscription charge.
- Straight context settings also govern explicit starts: straightThreeDsMode=off refuses a new session with 409 and code three_ds_straight_disabled. Single/double overrides the legacy pair switch; double is PAAY only. Existing session read and completion remain available after settings are changed.
- An explicit Straight challenge preference configured by the owner overrides the request body; a matching BIN challenge rule remains higher precedence. A no-challenge preference cannot guarantee frictionless authentication.
- For PAAY, POST every returned Method into a real hidden nonzero-size browser iframe. Immediately call /complete with stage:"method",methodCompleted:false to record that the iframe was submitted, then poll the same session; false does not assert successful fingerprint completion. GET returns a newly discovered Method before provider long-polling so the browser can execute it. PAAY owns its Method callback, so do not wait for a Kontrol-specific message before polling. Keep one read chain per session and follow actual challenge actions. Other providers retain their method-completion contract.
- Paired PAAY creation returns the primary session after both durable slots exist, potentially while the provider POSTs are still in flight. Poll the returned session instead of starting a replacement pair. The response is not payment approval.

##### `GET /v1/3ds/sessions/:id`

**Scope** `charges.read` - **Get / advance a 3DS session**

Returns and advances the requested owned session using any recorded callback or provider poll. Terminal sessions return their current view. When the session belongs to a PAAY pair, also returns snapshots of every recorded slot as sessions[] and its groupId; this request advances only the requested session.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id from POST /v1/3ds/sessions. Must belong to the key's account (else 404). |

**Response**

```json
{
  "session": {
    "sessionId": "a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91",
    "provider": "threedsecureio_3ds",
    "status": "authenticated",
    "next": null,
    "auth": {
      "status": "Y",
      "cavv": "AAABBWcSNIdjeUZThmNHAAAAAAA=",
      "eci": "05",
      "dsTransId": "f38c7b1e-2a4d-4c6e-9b0f-1d2e3f4a5b6c",
      "acsTransId": "9d1e2a4b-...",
      "threeDsServerTransId": "c4a1e2d3-...",
      "version": "2.2.0",
      "liabilityShift": true,
      "reason": null,
      "flow": "challenge"
    },
    "usable": true,
    "expiresAt": "2026-09-27T09:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `session.sessionId` | uuid | The current session ID. Pass it as threeDsSessionId when resuming the same order through POST /v1/charge. A PAAY pair can require the other session on the next resume. |
| `session.provider` | enum: evervault_3ds\|paay_3ds\|threedsecureio_3ds\|vgs_3ds | The account's active 3DS integration. |
| `session.status` | string | pending, method or challenge means work remains; authenticated, attempted or informational is a terminal provider result, but usable is the authoritative proof check; failed, unavailable, error, expired and consumed are not usable. An error means the provider refused the authentication request and it is excluded from the recorded authentication count. |
| `session.next` | object \| null | Provider-neutral browser action. method: POST fields to url in a hidden iframe, then complete stage=method with methodCompleted reflecting callback or timeout. challenge: show the bank iframe using url/fields or supplied provider HTML, then complete stage=challenge. sdk: run the specified provider SDK/hosted URL, then complete stage=challenge. Optional done is only a completion-message hint: verify the expected active frame/source/origin and confirm the result through the authenticated API. Null when this slot has no browser action; another slot in sessions[] may still have one. |
| `session.auth` | object \| null | Normalized terminal outcome: status, cavv, eci, dsTransId, acsTransId, threeDsServerTransId, version, liabilityShift, reason and optional flow. Null before an outcome exists. Cryptogram material is cleared from the session atomically on consumption, while outcome metadata remains for history. Treat this API-key-authenticated response as server-side payment data; the admin customer inventory never returns the cryptogram. |
| `session.usable` | boolean | True only for authenticated/attempted/informational status, a stored CAVV and ECI, no consumption, and an unexpired local proof deadline. Group readiness here describes the provider result; checkout allocation must still settle both slots before making an unused proof eligible for rebill. |
| `session.expiresAt` | string (ISO 8601) | The browser-session deadline, one hour from request creation. Stop browser work at this deadline. A successful grouped proof has a separate local holding deadline, shown by the admin customer inventory; expiresAt here is not a network or issuer validity guarantee. |
| `sessions` | array \| absent | Present for a PAAY double-authentication group. Full SessionView for each recorded slot, in straight-then-rebill order. Normally two slots; a partial creation failure may leave fewer. Each has its own sessionId, outcome and next action. Completing or abandoning one slot does not complete the other. No purpose field is added to SessionView. |
| `groupId` | uuid \| absent | Identifier binding the two PAAY authentication slots to this checkout/card/payment context. Repeating the same start context reuses the group rather than starting another pair. |
| `session.checkoutAuthentication` | object \| absent | Display metadata for a grouped checkout slot: step, total, purpose, amountCents and currency describe the authentication actually shown by the bank. The second slot can additionally carry intendedRebillAmountCents and intendedRebillCurrency for the separately bound future payment. None of these display fields authorize a different sale amount. |
| `session.pendingTimedOut` | boolean \| absent | True only after the server atomically retired optional PAAY work at its recorded deadline. Distinguishes this recoverable timeout from a naturally expired session. It is response metadata, not a request permission: recovery must re-read this API state and resume the same order/session with the existing idempotency key. It neither confirms bank approval nor authorizes retrying an unknown payment. |
| `backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. |
| `session.pendingDeadlineAt` | string (ISO 8601) \| absent | Server-owned deadline for optional silent PAAY authentication of the current purchase, default 45 seconds from its durable creation. Secondary background work has its own lifetime and neither extends nor cancels this deadline. Resume the SAME order and session through the normal charge path; the server rechecks required authentication and current provider state. Real issuer challenges, known negative results and mandatory authentication retain their controls. This deadline never approves a sale or authorizes retrying an unknown bank result. |

**Errors**

- `400` `A value has an invalid format.` when the id is not a UUID.
- `401` `Missing API key` or `Invalid API key`.
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned.
- `404` `Unknown session` for an unknown ID, another account's session or a session without owner.
- `429` Per-IP rate limit exceeded (RATE_LIMIT_CHARGE, default 3000 requests per minute for each of these session routes).
- `503` `Service temporarily unavailable` (detail `authentication backend error`) when the key lookup fails.

**Gotchas**

- NOT a pure read: it may call the provider (resume/poll), flip an expired session to "expired", and turn a session into "unavailable" when the account has since disabled or switched its 3DS provider. A session already final (authenticated / attempted / informational / failed / unavailable / error / consumed) is returned as is, without a provider call.
- For PAAY, POST every returned Method into a real hidden nonzero-size browser iframe. Immediately call /complete with stage:"method",methodCompleted:false to record that the iframe was submitted, then poll the same session; false does not assert successful fingerprint completion. GET returns a newly discovered Method before provider long-polling so the browser can execute it. PAAY owns its Method callback, so do not wait for a Kontrol-specific message before polling. Keep one read chain per session and follow actual challenge actions. Other providers retain their method-completion contract.
- auth.cavv IS returned here (the checkout never needs it - pass the sessionId to /v1/charge instead), unlike the admin session list which strips it.
- A malformed :id (not a UUID) is a 400 "A value has an invalid format." from the DB mapper, not 404.
- v3.9.7 - THE OUT-OF-BAND CHALLENGE: a French ACS (Worldline for BPCE / BNP / Credit Mutuel) asks the shopper to confirm in the banking app; the iframe never posts the "CRes" message the PAAY flow relies on. While the challenge overlay is up, poll this endpoint every 5 s (10 s after the first minute), at once on document visibilitychange (the shopper comes back from the app), and stop at session.expiresAt; the moment status leaves challenge/method, re-submit the same order with threeDsSessionId. A PAAY 404 round leaves the row unchanged and costs no fee, so polling is safe. One failed round never settles the session (review): a network failure between cocoapi and the provider hands the row back as it is, and PAAY's transient answers on its updates long-poll (a 5xx, the intermittent 401 on the JWT, a 408 / 429) are "no result yet" exactly like the 404 - only the directory server's own 400 on the request ends it (status error). Budget the call for the provider's hold: a round can take up to 15 s before PAAY answers "not yet" (cocoapi's own provider timeout is 25 s), so give it 20 s; the 5 s / 10 s interval is the pause BETWEEN rounds. A round that fails on your side is simply polled again.
- PAAY double authentication starts two independent durable slots. The primary usable proof can authorize the current sale without waiting for the secondary. The secondary can finish in the background; it never rewrites the proof or payment result already dispatched. optimizeThreeDsTokens reserves a sole usable proof only once both results are terminal and authentication is optional. A ready primary with a still-pending sibling is used for the sale. Strict account/BIN requirements remain enforced.
- Browser work expires after one hour. Successful grouped proofs use the configured local holding limit (rebillTokenValidityDays, 1-90 days from request creation); issuer/network/processor acceptance can be shorter. Consumption is atomic and single use. Used proofs are not restored after a declined or uncertain payment.
- Authentication fees are calculated at read time from the current provider rate and the recorded authentication count: a completed pair normally records two attempts, an error slot is excluded, and later consumption of a saved proof records zero new authentications. Explicit sessions that are never attached to a transaction remain visible in the session inventory rather than a transaction fee total.
- No subscription check here: polling an existing session keeps working when the platform subscription lapses.

##### `POST /v1/3ds/sessions/:id/complete`

**Scope** `charges.write` - **Complete a browser step of a 3DS session**

Resumes the requested owned session after its method or challenge browser step, or, with abandon=true, ends an unfinished session (single session or one PAAY pair slot alike) after first asking the provider for a late result. Returns the updated session and, for PAAY pairs, sessions[] plus groupId. Other slots remain independent and may still need browser work.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id (owner-checked -> 404 otherwise). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `stage` | enum: method\|challenge; default `inferred from status` | no | Which step finished. Default: 'method' when the session status is method, else 'challenge'. |
| `methodCompleted` | boolean | no | Whether the browser observed Method completion. For PAAY, false with stage:"method" can be sent immediately after the real iframe POST to record Method start and begin polling; it does not fabricate a successful fingerprint or an authentication result. |
| `abandon` | boolean; default `false` | no | For a session still pending, method or challenge (a grouped PAAY slot or a single session), the server first polls the provider: a terminal result already available is returned intact (a late success is not turned into a failure). Otherwise the session is marked failed (auth.status N, reason 'Browser authentication abandoned') and its browser action cleared. A concurrent terminal success wins. Does not cancel the other slot of a pair and does not discard another usable proof. |
| `abandonReason` | enum: timeout\|cancel\|acs_no_load\|unsupported | no | Optional with abandon:true: why the browser step ended. Stored as raw.browserAbandonReason ('unspecified' when omitted) and logged without card data. Older clients may omit it. |

**Request body**

```json
{
  "stage": "challenge"
}
```

**Response**

```json
{
  "session": {
    "sessionId": "a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91",
    "provider": "paay_3ds",
    "status": "attempted",
    "next": null,
    "auth": {
      "status": "A",
      "cavv": "kBMI...",
      "eci": "06",
      "dsTransId": "...",
      "acsTransId": null,
      "threeDsServerTransId": "...",
      "version": "2.2.0",
      "liabilityShift": true,
      "reason": null,
      "flow": "attempt"
    },
    "usable": true,
    "expiresAt": "2026-09-27T09:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `session.sessionId` | uuid | The current session ID. Pass it as threeDsSessionId when resuming the same order through POST /v1/charge. A PAAY pair can require the other session on the next resume. |
| `session.provider` | enum: evervault_3ds\|paay_3ds\|threedsecureio_3ds\|vgs_3ds | The account's active 3DS integration. |
| `session.status` | string | pending, method or challenge means work remains; authenticated, attempted or informational is a terminal provider result, but usable is the authoritative proof check; failed, unavailable, error, expired and consumed are not usable. An error means the provider refused the authentication request and it is excluded from the recorded authentication count. |
| `session.next` | object \| null | Provider-neutral browser action. method: POST fields to url in a hidden iframe, then complete stage=method with methodCompleted reflecting callback or timeout. challenge: show the bank iframe using url/fields or supplied provider HTML, then complete stage=challenge. sdk: run the specified provider SDK/hosted URL, then complete stage=challenge. Optional done is only a completion-message hint: verify the expected active frame/source/origin and confirm the result through the authenticated API. Null when this slot has no browser action; another slot in sessions[] may still have one. |
| `session.auth` | object \| null | Normalized terminal outcome: status, cavv, eci, dsTransId, acsTransId, threeDsServerTransId, version, liabilityShift, reason and optional flow. Null before an outcome exists. Cryptogram material is cleared from the session atomically on consumption, while outcome metadata remains for history. Treat this API-key-authenticated response as server-side payment data; the admin customer inventory never returns the cryptogram. |
| `session.usable` | boolean | True only for authenticated/attempted/informational status, a stored CAVV and ECI, no consumption, and an unexpired local proof deadline. Group readiness here describes the provider result; checkout allocation must still settle both slots before making an unused proof eligible for rebill. |
| `session.expiresAt` | string (ISO 8601) | The browser-session deadline, one hour from request creation. Stop browser work at this deadline. A successful grouped proof has a separate local holding deadline, shown by the admin customer inventory; expiresAt here is not a network or issuer validity guarantee. |
| `sessions` | array \| absent | Present for a PAAY double-authentication group. Full SessionView for each recorded slot, in straight-then-rebill order. Normally two slots; a partial creation failure may leave fewer. Each has its own sessionId, outcome and next action. Completing or abandoning one slot does not complete the other. No purpose field is added to SessionView. |
| `groupId` | uuid \| absent | Identifier binding the two PAAY authentication slots to this checkout/card/payment context. Repeating the same start context reuses the group rather than starting another pair. |
| `session.checkoutAuthentication` | object \| absent | Display metadata for a grouped checkout slot: step, total, purpose, amountCents and currency describe the authentication actually shown by the bank. The second slot can additionally carry intendedRebillAmountCents and intendedRebillCurrency for the separately bound future payment. None of these display fields authorize a different sale amount. |
| `session.pendingTimedOut` | boolean \| absent | True only after the server atomically retired optional PAAY work at its recorded deadline. Distinguishes this recoverable timeout from a naturally expired session. It is response metadata, not a request permission: recovery must re-read this API state and resume the same order/session with the existing idempotency key. It neither confirms bank approval nor authorizes retrying an unknown payment. |
| `backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. |
| `session.pendingDeadlineAt` | string (ISO 8601) \| absent | Server-owned deadline for optional silent PAAY authentication of the current purchase, default 45 seconds from its durable creation. Secondary background work has its own lifetime and neither extends nor cancels this deadline. Resume the SAME order and session through the normal charge path; the server rechecks required authentication and current provider state. Real issuer challenges, known negative results and mandatory authentication retain their controls. This deadline never approves a sale or authorizes retrying an unknown bank result. |

**Errors**

- `400` `Invalid request` with `details` when stage is not method or challenge, methodCompleted or abandon is not a boolean, or abandonReason is outside its enum; `A value has an invalid format.` when the id is not a UUID.
- `401` `Missing API key` or `Invalid API key`.
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned.
- `404` `Unknown session`.
- `429` Per-IP rate limit exceeded (RATE_LIMIT_CHARGE, default 3000 requests per minute for each of these session routes).
- `503` `Unable to verify authentication result; retry completion` when abandon:true and the pre-abandon provider check could not read the session (nothing was ended; retry the same call); `Service temporarily unavailable` (detail `authentication backend error`) when the key lookup fails.

**Gotchas**

- Call it AFTER the coco3ds postMessage (or the provider-specific `done` message) - calling before the ACS result reached cocoapi makes the provider report the challenge as not returned.
- Idempotent on a final session: it just returns the view (no provider call).
- The body may be empty ({}); stage is then inferred from the current status.
- After the method stage the response can carry a NEW next (type challenge) - loop until `next` is null.
- A provider 5xx / exception during the resume ends the session "unavailable" (200 with auth.status U and reason), never a 5xx; v3.9.7 - a 4xx on cocoapi's own request (a refused billAddrState, a validation error on the payload) ends it "error" instead: same 200, auth.status U, usable false, and it is not billed. A plain GET /v1/3ds/sessions/:id poll never does: a transient provider answer there leaves the session as it is (review).
- PAAY double authentication starts two independent durable slots. The primary usable proof can authorize the current sale without waiting for the secondary. The secondary can finish in the background; it never rewrites the proof or payment result already dispatched. optimizeThreeDsTokens reserves a sole usable proof only once both results are terminal and authentication is optional. A ready primary with a still-pending sibling is used for the sale. Strict account/BIN requirements remain enforced.
- Browser work expires after one hour. Successful grouped proofs use the configured local holding limit (rebillTokenValidityDays, 1-90 days from request creation); issuer/network/processor acceptance can be shorter. Consumption is atomic and single use. Used proofs are not restored after a declined or uncertain payment.
- Authentication fees are calculated at read time from the current provider rate and the recorded authentication count: a completed pair normally records two attempts, an error slot is excluded, and later consumption of a saved proof records zero new authentications. Explicit sessions that are never attached to a transaction remain visible in the session inventory rather than a transaction fee total.
- After an explicit primary challenge cancellation, re-submit only the unchanged order and existing session identity. The server enforces the authoritative outcome and required-authentication policy. Never start a new payment to complete an optional secondary authentication.
- For PAAY, POST every returned Method into a real hidden nonzero-size browser iframe. Immediately call /complete with stage:"method",methodCompleted:false to record that the iframe was submitted, then poll the same session; false does not assert successful fingerprint completion. GET returns a newly discovered Method before provider long-polling so the browser can execute it. PAAY owns its Method callback, so do not wait for a Kontrol-specific message before polling. Keep one read chain per session and follow actual challenge actions. Other providers retain their method-completion contract.
- Abandon example: {"stage":"challenge","abandon":true,"abandonReason":"timeout"}. When the provider already holds a terminal result, the reply is {session, sessions?, groupId?} with that result (no backgroundAuthentications on this early return). Allow about 30 seconds for this final check.
- An abandoned session is a refusal at charge time: a POST /v1/charge that names it in threeDsSessionId is blocked before any gateway call (3DS authentication failed (Browser authentication abandoned)), whatever the integration's liability-shift policy. Start a new authentication instead of resubmitting with that session.
- No subscription check here: completing an existing session keeps working when the platform subscription lapses.

#### Gateways

The card gateways (MIDs) of the account, their categories and reference lists (processors, acquiring banks, companies), credentials and post-purchase payment readiness.

- Lists are complete (no paging): the page filters by category, type, status, processor, bank, company and text in the browser. The only server filter is `archived` (`false` by default, `true`, `all`).
- Archive and delete coexist. `POST /v1/accounts/:id/archive` keeps the gateway for its history: it is switched off and leaves `GET /v1/accounts`; `DELETE /v1/accounts/:id` erases it for good (live or archived), and its transactions lose their gateway. `GET /v1/accounts?archived=true` lists the archived ones; `POST /v1/accounts/:id/restore` brings one back, still off (`PATCH /v1/accounts/:id { "activated": true }` switches it on). An archived gateway cannot be switched on (409) and keeps its name. The dashboard shows the two lists as the Gateways and Archived tabs.
- Duplicate MID number warning: detected in the browser by comparing the MID numbers of `GET /v1/accounts`.
- CSV / PDF exports are built in the browser from `GET /v1/accounts`.

##### `GET /v1/accounts`

**Scope** `routing.read` - **List card gateways (MIDs) with this month's usage**

Lists the account's card gateways (MIDs) with this month's usage against their caps; wallet MIDs (Apple Pay / Google Pay) are listed by GET /v1/wallet-providers. List the gateways owned by the caller's account (the live ones by default; archived=true for the archived ones, archived=all for both), with this calendar month's usage against its cap, its linked categories, booleans saying whether credentials are stored, and, for a gateway managed by KontrolPay, the state of its KontrolPay account. Credentials themselves are never returned here.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `archived` | string (true\|false\|all); default `false` | no | false (or absent): the live gateways only, the ones you route with. true: the archived gateways only (archived with POST .../archive, kept for history; a deleted row is gone). all: both; each row says which it is in archived_at. Any other value answers 400. |

**Response**

```json
{
  "accounts": [
    {
      "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
      "name": "Acme Processing MID 1",
      "gateway_type": "nmi",
      "stripe_mode": "s2s",
      "activated": true,
      "archived_at": null,
      "monthly_cap_cents": "50000000",
      "used_cents": "1284350",
      "has_security_key": true,
      "has_login": false,
      "supports_amex": false,
      "supports_mastercard": true,
      "supports_visa": true,
      "supports_discover": false,
      "mc_refund_fee_cents": "35",
      "visa_refund_fee_cents": "30",
      "discount_fee_bps": 295,
      "transaction_fee_cents": "25",
      "reserve_rate_bps": 1000,
      "campaign_id": null,
      "product_id": null,
      "mid_number": "517432000012345",
      "soft_descriptor": "ACME* SUPPORT",
      "hard_descriptor": "ACME LLC",
      "mcc": "5967",
      "bank_page": "shop.acme.example",
      "product_matching_enabled": true,
      "descriptor_enabled": true,
      "acquirer_bin": null,
      "caid": null,
      "processor_id": "5b1e7a02-3c44-4d2f-9e8a-6f0b2c9d1a11",
      "processor_name": "EXAMPLE PROCESSOR",
      "acquiring_bank_id": "c7d3e9f1-8a2b-4c6d-9e0f-1a2b3c4d5e6f",
      "acquiring_bank_name": "EXAMPLE BANK",
      "company_id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
      "company_name": "EXAMPLE COMPANY LLC",
      "created_at": "2026-07-02T14:31:08.442Z",
      "categories": [
        {
          "id": "3f0c8d21-55ab-4f9e-9c10-7ab2e4f61d38",
          "name": "Nutra"
        }
      ],
      "kontrolpay_account_id": null,
      "kontrolpay_application_id": null,
      "kontrolpay_status": null,
      "kontrolpay_payouts_paused": null
    },
    {
      "id": "0c8e5f3a-7d2b-4c1e-a9f6-3b4d5e6f7a08",
      "name": "KontrolPay - Northwind Outfitters",
      "gateway_type": "kontrolpay",
      "stripe_mode": "s2s",
      "activated": false,
      "monthly_cap_cents": "15000000",
      "used_cents": "0",
      "has_security_key": false,
      "has_login": false,
      "supports_amex": false,
      "supports_mastercard": false,
      "supports_visa": false,
      "supports_discover": false,
      "mc_refund_fee_cents": "0",
      "visa_refund_fee_cents": "0",
      "discount_fee_bps": 790,
      "transaction_fee_cents": "45",
      "reserve_rate_bps": 1000,
      "campaign_id": null,
      "product_id": null,
      "mid_number": null,
      "soft_descriptor": null,
      "hard_descriptor": null,
      "mcc": null,
      "bank_page": null,
      "product_matching_enabled": false,
      "descriptor_enabled": true,
      "acquirer_bin": null,
      "caid": null,
      "processor_id": null,
      "processor_name": null,
      "acquiring_bank_id": null,
      "acquiring_bank_name": null,
      "company_id": null,
      "company_name": null,
      "created_at": "2026-11-20T15:00:00.000Z",
      "categories": [],
      "kontrolpay_account_id": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "kontrolpay_application_id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
      "kontrolpay_status": "provisioning",
      "kontrolpay_payouts_paused": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `accounts` | object[] | All gateways owned by the caller's account, ordered by name ascending. An empty array when none, never null. |
| `accounts[].id` | string (uuid) | Gateway id: the :id of the update, delete, credentials and duplicate routes. |
| `accounts[].name` | string | Gateway display name, unique within the account. |
| `accounts[].gateway_type` | string | The type of the row: one of the types that can be created (listed on POST /v1/accounts, field gatewayType), or kontrolpay. |
| `accounts[].gateway_type = kontrolpay` | string | `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API. |
| `accounts[].stripe_mode` | s2s \| embedded \| hosted | Integration mode of a Stripe gateway; s2s on every other row. |
| `accounts[].activated` | boolean | Whether the gateway may take live traffic. On a kontrolpay row it is set by KontrolPay only. |
| `accounts[].monthly_cap_cents` | string (bigint as string) | Monthly cap in integer cents. "0" = unlimited. Serialised as a JSON STRING (a bigint column). On a kontrolpay row: the monthly limit approved by KontrolPay. |
| `accounts[].used_cents` | string (bigint as string) | Cents charged on this gateway in the CURRENT UTC calendar month (period key YYYYMM). "0" when there is no usage row. Also a JSON string. |
| `accounts[].has_security_key` | boolean | True when a security key is stored. The key itself is never returned by this route. Always false on a kontrolpay row, which holds no credential. |
| `accounts[].has_login` | boolean | True when a login is stored. There is no has_password field: the presence of a password is not reported. Always false on a kontrolpay row. |
| `accounts[].supports_amex` | boolean | Card network flag: American Express. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `accounts[].supports_mastercard` | boolean | Card network flag: Mastercard. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `accounts[].supports_visa` | boolean | Card network flag: Visa. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `accounts[].supports_discover` | boolean | Card network flag: Discover. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `accounts[].mc_refund_fee_cents` | string (bigint as string) | Mastercard refund and chargeback flat fee, integer cents, as a JSON string. |
| `accounts[].visa_refund_fee_cents` | string (bigint as string) | Visa refund and chargeback flat fee, integer cents, as a JSON string. |
| `accounts[].discount_fee_bps` | number (integer) | Merchant discount rate in BASIS POINTS (1% = 100). An integer column: a real JSON number, not a string. On a kontrolpay row: the KontrolPay discount rate in force. |
| `accounts[].transaction_fee_cents` | string (bigint as string) | Flat fee per attempt, integer cents, as a JSON string. On a kontrolpay row: the KontrolPay per-attempt fee in force. |
| `accounts[].reserve_rate_bps` | number (integer) | Rolling reserve rate in basis points. A real JSON number. On a kontrolpay row: the KontrolPay reserve rate in force. |
| `accounts[].campaign_id` | string \| null | CheckoutChamp campaignId (a plain identifier, not a secret). |
| `accounts[].product_id` | string \| null | CheckoutChamp product1_id (a plain identifier). |
| `accounts[].mid_number` | string \| null | Processor MID number (a plain identifier, shown in the dashboard and by the refund API). |
| `accounts[].soft_descriptor` | string \| null | Dynamic descriptor, sent to NMI while descriptor_enabled is true. |
| `accounts[].hard_descriptor` | string \| null | Bank-side descriptor (descriptive; not sent). |
| `accounts[].mcc` | string \| null | Merchant category code. It is not sent to the gateway with the descriptor. |
| `accounts[].descriptor_enabled` | boolean | Whether the dynamic descriptor is sent. It switches off by itself when the processor refuses custom descriptors; PATCH descriptorEnabled turns it back on. |
| `accounts[].acquirer_bin` | string \| null | Acquirer BIN of the gateway (digits; set with PATCH acquirerBin). null when never set. |
| `accounts[].caid` | string \| null | CAID (Card Acceptor ID) of the gateway (set with PATCH caid). null when never set. |
| `accounts[].processor_id` | string (uuid) \| null | The PROCESSOR behind the gateway (a row of the processors reference list). null when the gateway has none set; the row is never dropped for it. |
| `accounts[].processor_name` | string \| null | Display name of that processor, as the reference list spells it (for example "EXAMPLE PROCESSOR"). null when processor_id is null. Filters, breakdowns and entity chips key on the id and show this name. |
| `accounts[].acquiring_bank_id` | string (uuid) \| null | The ACQUIRING BANK or service behind the gateway (a row of the acquiring banks reference list). null when unset. |
| `accounts[].acquiring_bank_name` | string \| null | Display name of that acquiring bank (for example "EXAMPLE BANK"). null when acquiring_bank_id is null. |
| `accounts[].company_id` | string (uuid) \| null | The COMPANY behind the gateway (a row of the companies reference list): the legal entity it is boarded under. null when unset; the row is never dropped for it. |
| `accounts[].company_name` | string \| null | Display name of that company (for example "EXAMPLE COMPANY LLC"). null when company_id is null. Filters, breakdowns and entity chips key on the id and show this name. |
| `accounts[].bank_page` | string \| null | The website or storefront the gateway is registered under. Stored verbatim as typed (the scheme, the path and a leading `wallet.` are only stripped at match time). |
| `accounts[].product_matching_enabled` | boolean | When true, a charge on this gateway is described to the processor as a basket drawn from the catalog of the bank page (storefront host = normalised bank_page), matched on the amount, instead of one generic line. Returned ONLY by this route. |
| `accounts[].created_at` | string (ISO 8601) | Row creation timestamp. |
| `accounts[].categories` | object[] | Linked categories as { id, name }, ordered by name. [] when none. |
| `accounts[].kontrolpay_account_id` | string (uuid) \| null | KontrolPay account of this gateway. Null on every other gateway type. |
| `accounts[].kontrolpay_application_id` | string (uuid) \| null | The approved application the gateway was created by. Null on every other gateway type. |
| `accounts[].kontrolpay_status` | string \| null | KontrolPay account status: provisioning (activation pending), active, suspended, banned or closed. Null on every other gateway type. |
| `accounts[].kontrolpay_payouts_paused` | boolean \| null | Whether KontrolPay payouts of the account are on hold. Null on every other gateway type. |
| `accounts[].archived_at` | string (ISO 8601) \| null | When the gateway was archived (POST /v1/accounts/:id/archive); null for a live gateway. An archived gateway is always off (activated false). |

**Errors**

- `400` {"error":"archived must be true, false or all"}: the archived query value is not one of the three.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` Statement timeout: the request took too long and was cancelled. Narrow the range and retry.

**Gotchas**

- `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API.
- A kontrolpay row is read-only here except for its categories: PATCH answers 409 for any other field, DELETE, credentials and duplicate answer 409.
- Every caller that lists gateways reads the KontrolPay state from this row; no other call is needed to label it.
- NO query parameter exists. There is no pagination, search, filter, activated-only or gateway_type filter: the whole owned list comes back in one array and the query string is ignored entirely.
- Money fields backed by a bigint column (monthly_cap_cents, used_cents, mc_refund_fee_cents, visa_refund_fee_cents, transaction_fee_cents) arrive as JSON STRINGS. discount_fee_bps and reserve_rate_bps are integer columns and arrive as numbers. Coerce before arithmetic: "50000000" > 100 is a string comparison.
- Rates here are BASIS POINTS (integer, 1% = 100 bps, at most 1000000), not 0..1 ratios. Every *_cents field is integer cents.
- used_cents resets on the 1st of each month in UTC (period key = UTC year * 100 + month), so it can appear to drop to 0 in the middle of a day in another time zone.
- A gateway whose owner_email is NULL (legacy rows) is invisible to EVERY caller: the scope predicate compares owner_email with the account e-mail and never matches null.
- If the scope of the request failed to load, the account e-mail of the caller may be null: the list is then empty rather than an error (fail closed).
- product_matching_enabled is returned only here: the POST, PATCH and duplicate responses omit it. Read it back with this route after changing it.
- This is the only gateway route that exposes has_login and has_security_key; use GET /v1/accounts/:id/credentials for the values.
- There is no single-gateway read: filter this list by id.
- Archived gateways are left out unless you ask for them (archived=true or archived=all). Their past transactions, attempts and reports keep naming them.

##### `POST /v1/accounts`

**Scope** `routing.write` - **Create gateway**

Create one gateway (MID) of the caller's account: its credentials (encrypted at rest), monthly cap, fee schedule, descriptors, card networks, reporting references and category links. Only what the gateway type needs to charge is required: a name plus, for Stripe, a publishable key and a secret key; for every other type a security key, or a login and a password; for CheckoutChamp also campaignId and productId. Also creates an empty storefront row for the bank page. The managed gateway type is never created here: it comes from an approved application.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Gateway display name, 1 to 128 characters, stored as sent (not trimmed). Unique within the account (index on owner_email and name): a name already used by another gateway of the account answers 409. The dashboard form generates a name when its field is left empty; the API does not. Archived gateways keep their name: rename or restore the archived one to reuse it. |
| `login` | string | no | Stripe: the publishable key (pk_test_... or pk_live_...), required. NMI: the username. CheckoutChamp: the loginId. ConvesioPay: the merchant e-mail, used only by the connect route (charges use the secret key and the ConvesioPay integration id of the account). Encrypted (AES-256-GCM) before storage; an empty string is stored as null. On a Stripe gateway the value is trimmed first; for every other type it is stored exactly as sent, spaces included. |
| `password` | string | no | Stripe: the optional webhook signing secret (whsec_...); omit it or send "" when no webhook is configured. Other types: the password that goes with login. Encrypted; an empty string is stored as null. Trimmed on a Stripe gateway only. |
| `securityKey` | string | no | Stripe: the secret key (sk_test_ or sk_live_, or a restricted rk_ or rkcs_ key), required, in the same test or live mode as the publishable key. NMI: the security key. ConvesioPay: the S2S secret key (minted by POST /v1/accounts/convesio/connect), which is what charges use. Encrypted; an empty string is stored as null. Trimmed on a Stripe gateway only. |
| `activated` | boolean; default `true` | no | Whether the MID is live. Omitted -> true. |
| `monthlyCapCents` | integer >= 0; default `0` | no | Monthly spend cap in integer cents. 0 = unlimited. |
| `categoryIds` | string[] (uuid) | no | Category ids to link (many to many, at most 64, each a uuid). Only categories of the account of the caller are linked: an unknown id or a category of another account is ignored without an error. Duplicates in the array are harmless. |
| `gatewayType` | enum: 'nmi' \| 'convesio' \| 'stripe' \| 'other' \| 'checkoutchamp'; default `'nmi'` | no | Gateway adapter. Any other value answers 400, the managed gateway type included: such a gateway is created by an approved application, never through this route. |
| `stripeMode` | enum: 's2s' \| 'embedded' \| 'hosted'; default `'s2s'` | no | Stripe integration mode: s2s (server-to-server, the default), embedded or hosted. Stored as stripe_mode on every type (used by Stripe gateways only). Any other value is a 400. |
| `campaignId` | string | no | CheckoutChamp campaignId, at most 128 characters. REQUIRED (with productId) when gatewayType is checkoutchamp. Stored as campaign_id. |
| `productId` | string | no | CheckoutChamp product1_id, at most 128 characters. Required with campaignId when gatewayType is checkoutchamp. Stored as product_id. |
| `midNumber` | string | no | Processor MID number, at most 64 characters. Plain identifier, returned by the list and refund APIs. Stored as mid_number. |
| `bankPage` | string | no | The website or storefront this gateway is registered under, at most 256 characters. Stored verbatim as bank_page; this is the host productMatchingEnabled matches baskets against. Also creates an EMPTY storefront row keyed on the normalised host (scheme, path and a leading wallet. stripped, lowercased). |
| `productMatchingEnabled` | boolean; default `true` | no | true = charges on this gateway are described to the processor as a basket drawn from the catalog of the bank page, matched on the amount, instead of one generic line (it also needs the Smart product matching integration of the account and an active catalog for that host). An absent key means true; false is stored as false. Stored as product_matching_enabled. |
| `softDescriptor` | string | no | Dynamic descriptor sent to NMI as descriptor while descriptorEnabled is true, at most 64 characters stored (NMI receives the first 25, whitespace collapsed). Stored as soft_descriptor. |
| `hardDescriptor` | string | no | Bank-side descriptor, at most 64 characters, descriptive only. Stored as hard_descriptor. |
| `mcc` | string | no | Merchant category code, at most 8 characters (a string, not a number). Stored as mcc. Not sent to the gateway with the descriptor; when both acquirerBin and caid are set, a 3DS authentication names it with them as the acquirer. |
| `descriptorEnabled` | boolean; default `true` | no | Whether the soft descriptor is sent. It switches off by itself when the processor refuses custom descriptors. Stored as descriptor_enabled. |
| `acquirerBin` | string (digits) | no | Acquirer BIN of the MID - the 6-digit (up to 16) BIN of the acquiring bank behind this merchant account, digits only (regex ^\d*$, else 400 "Acquirer BIN must be digits"). Informational: shown on the gateway (dashboard Gateways -> MID -> Acquirer BIN), never sent to the processor. Send "" to clear (stored as null) -> column nmi_accounts.acquirer_bin. |
| `caid` | string | no | CAID (Card Acceptor ID) of the MID - the merchant identifier the acquirer issued, max 32 chars, any format. Informational: shown on the gateway, never sent to the processor. Send "" to clear (stored as null) -> column nmi_accounts.caid. |
| `processorId` | string (uuid) \| null; default `null` | no | v3.9 section 0 - id of the PROCESSOR behind the MID: a row of the global `processors` reference table (the list served under /v1/processors; names are stored as the operator's list spells them, e.g. "PRIORITY", "CONVESIO PAY"). A select field, never free text: an id that is not in the table is refused with 400 `{"error":"Unknown processor"}`. Optional at creation, in the API and in the dashboard form alike (the form stopped requiring it on 2026-11-06). Omitted = null. -> column nmi_accounts.processor_id. |
| `acquiringBankId` | string (uuid) \| null; default `null` | no | v3.9 section 0 - id of the ACQUIRING BANK / service behind the MID: a row of the global `acquiring_banks` reference table (served under /v1/acquiring-banks; e.g. "SYNOVUS", "CHESAPEAK", "FFB BANK"). Same rules as processorId: uuid or null, unknown id -> 400 `{"error":"Unknown acquiring bank"}`. Optional at creation, in the API and in the dashboard form alike. Omitted = null. -> column nmi_accounts.acquiring_bank_id. |
| `companyId` | string (uuid) \| null; default `null` | no | v3.9.2 section 0 - id of the COMPANY behind the MID, the legal entity (LLC) it is boarded under: a row of the global `companies` reference table (served under /v1/companies; e.g. "STELLAR TIDE LLC", "JM GRATEFUL LLC"). Same rules as processorId: uuid or null, unknown id -> 400 `{"error":"Unknown company"}`. Optional at creation, in the API and in the dashboard form alike. Omitted = null. -> column nmi_accounts.company_id. |
| `supportsAmex` | boolean; default `false` | no | Card network flag (Amex). Routing skips this gateway for a card of a network it does not support; all four flags false (the default) means every network. |
| `supportsMastercard` | boolean; default `false` | no | Card network flag (Mastercard). Routing skips this gateway for a card of a network it does not support; all four flags false (the default) means every network. |
| `supportsVisa` | boolean; default `false` | no | Card network flag (Visa). Routing skips this gateway for a card of a network it does not support; all four flags false (the default) means every network. |
| `supportsDiscover` | boolean; default `false` | no | Card network flag (Discover). Routing skips this gateway for a card of a network it does not support; all four flags false (the default) means every network. |
| `mcRefundFeeCents` | integer >= 0; default `0` | no | Mastercard refund/chargeback flat fee in integer cents. |
| `visaRefundFeeCents` | integer >= 0; default `0` | no | Visa refund/chargeback flat fee in integer cents. |
| `discountFeeBps` | integer 0..1000000; default `0` | no | Merchant discount rate in BASIS POINTS (1% = 100 bps). Not a 0..1 ratio and not a percent. Used, with transactionFeeCents, by the cost routing strategy. |
| `transactionFeeCents` | integer >= 0; default `0` | no | Flat fee per attempt in integer cents. Used, with discountFeeBps, by the cost routing strategy. |
| `reserveRateBps` | integer 0..1000000; default `0` | no | Rolling reserve rate in BASIS POINTS. |

**Request body**

```json
{
  "name": "Acme Processing MID 3",
  "gatewayType": "nmi",
  "securityKey": "example-nmi-security-key",
  "activated": true,
  "monthlyCapCents": 50000000,
  "midNumber": "000000000012345",
  "bankPage": "shop.acme.example",
  "softDescriptor": "ACME* SUPPORT",
  "mcc": "5967",
  "supportsVisa": true,
  "supportsMastercard": true,
  "discountFeeBps": 295,
  "transactionFeeCents": 25,
  "reserveRateBps": 1000,
  "categoryIds": [
    "3f0c8d21-55ab-4f9e-9c10-7ab2e4f61d38"
  ]
}
```

**Response**

```json
{
  "account": {
    "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
    "name": "Acme Processing MID 3",
    "activated": true,
    "monthly_cap_cents": "50000000",
    "created_at": "2026-08-30T16:41:02.887Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `account.id` | string (uuid) | New gateway id. |
| `account.name` | string | The stored name. |
| `account.activated` | boolean | Effective activated value (true unless you passed false). |
| `account.monthly_cap_cents` | string (bigint as string) | Effective cap in integer cents, as a JSON string. |
| `account.created_at` | string (ISO 8601) | Creation timestamp. |

**Errors**

- `400` {"error":"Invalid","details":<validation details>}: a field fails its own type or length check (name missing or over 128 characters, a gatewayType outside the list, a non-integer amount, a categoryIds entry that is not a uuid, an acquirerBin with a non-digit...). While any field fails here, the credential and CheckoutChamp rules below are not evaluated. {"error":"Invalid","details":{"formErrors":["Provide either securityKey or both login and password"],"fieldErrors":{}}}: a gateway that is not Stripe has no securityKey and not both login and password (an empty string counts as missing). "CheckoutChamp gateways require campaignId and productId" lands in formErrors the same way. Stripe: {"error":<sentence>,"details":{"formErrors":[],"fieldErrors":{"login"|"securityKey"|"password":[<sentence>]}}}. error is the sentence of the first failing key, in the order login, securityKey, password; each failing key has its own entry in fieldErrors. The sentences: "Enter the Stripe publishable key." / "Stripe publishable keys must start with pk_test_ or pk_live_." (login), "Enter the Stripe secret key." / "Enter a Stripe secret key starting with sk_test_ or sk_live_, or a restricted rk_ or rkcs_ key." / "Stripe publishable and secret keys must both use test mode or both use live mode." (securityKey), "Stripe webhook signing secrets must start with whsec_. Leave this field empty if no webhook is configured." (password). No credential value is ever echoed. {"error":"Unknown processor"} / {"error":"Unknown acquiring bank"} / {"error":"Unknown company"}: processorId / acquiringBankId / companyId is a well formed uuid but not a row of its reference list. {"error":"Provide a security key, or both a username and password."}, {"error":"Unknown gateway type."} or {"error":"A field failed a database validation check."}: database check safety nets; the validation above normally answers first.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `409` `{"error":"A gateway named \"<name>\" already exists - rename it or edit the existing one (an archived gateway keeps its name: look in the Archived tab)."}` - unique violation on nmi_accounts_name_key. `{"error":"A gateway with these details already exists."}` - some other unique violation. The sentence that starts with "Your account record is incomplete": the account e-mail of the caller is not a known account (owner_email foreign key). Rare.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unrecognised failure; the id is persisted to error_log.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Required fields depend on the type, and only what a charge needs is required (since 2026-11-06): Stripe needs login (publishable key) and securityKey (secret key), password (webhook secret) is optional, and the generic securityKey-or-login-and-password rule does not apply to it; NMI, ConvesioPay and other need securityKey, or login and password; CheckoutChamp also needs campaignId and productId. Processor, acquiring bank, company, descriptors, fees and card networks are all optional.
- Stripe keys are trimmed before they are checked and stored (whitespace from copying is not part of a key). Credentials of every other type are stored exactly as sent, spaces included.
- ConvesioPay: charges use securityKey and the ConvesioPay integration id of the account (account settings); the login stored on the gateway is not used to charge. A gateway created with only login and password passes validation but cannot charge until a secret key is stored (POST /v1/accounts/convesio/connect, then PATCH /v1/accounts/:id {"securityKey": ...}).
- The 201 body returns only 5 fields (id, name, activated, monthly_cap_cents, created_at). Everything else you sent (fees, descriptors, bank_page, gateway_type, categories) is stored but NOT echoed. Re-read with GET /v1/accounts to confirm.
- Credentials are not echoed back by this route; GET /v1/accounts/:id/credentials returns them in clear to a caller that may edit gateways (no-store, audited).
- Empty-string credentials are stored as null, not as "": {"securityKey": ""} alone fails the credential rule with a 400.
- Category links: only the categories of the account are linked; an unknown id or an id of another account is ignored without an error. Compare categories on GET /v1/accounts after the create.
- `bankPage` also creates an EMPTY storefront row (host normalised: scheme, path and leading `wallet.` stripped, lowercased) so the MID shows up under /v1/storefronts with 0 products. That bookkeeping never throws - if it fails, the MID is still created and no error is surfaced.
- Basis points vs cents: discountFeeBps and reserveRateBps are basis points (1% = 100), every *Cents field is integer cents. Every amount must be an integer: 0.0295 for a 2.95% rate is a 400.
- What changes charges: activated and monthlyCapCents gate routing; the four card network flags filter gateways by card brand; discountFeeBps and transactionFeeCents order gateways under the cost routing strategy; softDescriptor and descriptorEnabled go to the gateway; bankPage and productMatchingEnabled shape how the charge is described. hardDescriptor, midNumber, the references and the other fees are descriptive.
- Unknown body keys are silently stripped by zod - a typo'd field name (e.g. `bankpage`) is NOT an error, it is simply ignored.
- Every successful create is written to the action log (action create, object type account, object name = the name of the body, page NMI Accounts; the account acted as is recorded too).
- Stripe: gatewayType=stripe; stripeMode=s2s|embedded|hosted (default s2s); login=publishable key, securityKey=secret key, password=optional webhook secret. Matching test/live environments required.
- gatewayType checkoutchamp and other are accepted and stored, but no charge adapter exists for them yet: such a MID cannot process a charge (the dashboard does not offer them).

##### `PATCH /v1/accounts/:id`

**Scope** `routing.write` - **Update gateway**

Partially update one gateway you own: rename it, activate or deactivate it, rotate its credentials, change its cap, fees, descriptors, bank page and references, replace its category links, and switch productMatchingEnabled so charges are described as a basket from the catalog of the bank page. On a gateway managed by KontrolPay only the category links can be changed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Gateway id. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | New display name, 1 to 128 characters. Unique within the account. |
| `login` | string | no | Replaces the stored login. Sending "" CLEARS it (an empty string is stored as null). On a Stripe gateway (its current type, or gatewayType stripe in the same body) this is the publishable key: it is trimmed before the check and before storage, and "" (or only spaces) is refused with 400 "Enter the Stripe publishable key." instead of clearing it. |
| `password` | string | no | Replaces the stored password. "" clears it. On a Stripe gateway this is the optional webhook signing secret (whsec_...): trimmed, and "" (or only spaces) clears it. |
| `securityKey` | string | no | Replaces the stored security key. "" clears it. A secret key minted by the connect route of the gateway form is stored here. On a Stripe gateway this is the secret key (sk_, rk_ or rkcs_, in the same test or live mode as the publishable key): trimmed, and "" is refused with 400 "Enter the Stripe secret key.". |
| `activated` | boolean | no | Enable or disable live traffic on this gateway. On an archived gateway, true is refused with 409 (restore it first with POST /v1/accounts/:id/restore); the other fields of an archived gateway can still be edited. |
| `monthlyCapCents` | integer >= 0 | no | Monthly cap in integer cents; 0 = unlimited. Changing it does NOT reset used_cents. |
| `categoryIds` | string[] (uuid) | no | REPLACES the whole category link set (delete all, then insert). At most 64 items. [] unlinks every category. Omit the key to leave the links untouched. The one field accepted on a kontrolpay row. |
| `gatewayType` | enum | no | Changes the adapter: one of the types that can be created (listed on POST /v1/accounts, field gatewayType). kontrolpay is not accepted: 400. The create-time rules do not run here: a switch to checkoutchamp WITHOUT campaignId and productId succeeds. |
| `campaignId` | string | no | CheckoutChamp campaignId, at most 128 characters. Stored as campaign_id. |
| `productId` | string | no | CheckoutChamp product1_id, at most 128 characters. Stored as product_id. |
| `midNumber` | string | no | Processor MID number, at most 64 characters. Stored as mid_number. |
| `bankPage` | string | no | Bank page or storefront URL, at most 256 characters. Stored as bank_page. Changing it also ensures an empty storefront exists for the new normalised host and invalidates the catalog cache of that host. This is the host productMatchingEnabled matches baskets against. |
| `productMatchingEnabled` | boolean | no | true = charges on this gateway are described to the processor as a basket drawn from the catalog of the bank page (storefront host = normalised bank_page), matched on the amount, instead of one generic line. Stored as product_matching_enabled. The charge falls back silently to the generic line when the bank page is empty, has no catalog, or no set of prices sums exactly to the amount. |
| `softDescriptor` | string | no | Dynamic descriptor sent to NMI while descriptorEnabled is true, at most 64 characters. Stored as soft_descriptor. |
| `hardDescriptor` | string | no | Bank-side descriptor, at most 64 characters, descriptive only. Stored as hard_descriptor. |
| `mcc` | string | no | Merchant category code, at most 8 characters (a string, not a number). Stored as mcc. It is not sent to the gateway with the descriptor. |
| `descriptorEnabled` | boolean | no | Whether the dynamic descriptor is sent. It switches off by itself when the processor refuses custom descriptors; true turns it back on. |
| `acquirerBin` | string (digits) | no | Acquirer BIN of the gateway: the BIN of the acquiring bank behind this merchant account, digits only, at most 16 (anything else answers 400 "Acquirer BIN must be digits"). "" clears it (stored as null). Stored as acquirer_bin. |
| `caid` | string | no | CAID (Card Acceptor ID) of the gateway: the merchant identifier the acquirer issued, at most 32 characters, any format. "" clears it (stored as null). Stored as caid. |
| `processorId` | string (uuid) \| null | no | Id of the PROCESSOR behind the gateway: a row of the processors reference list (served under /v1/processors). A select field, never free text: an id that is not in the list answers 400 {"error":"Unknown processor"}. Explicit null CLEARS the field (the "None" row of the picker); omitted leaves it unchanged. Stored as processor_id. |
| `acquiringBankId` | string (uuid) \| null | no | Id of the ACQUIRING BANK or service behind the gateway: a row of the acquiring banks reference list (served under /v1/acquiring-banks). A select field, never free text: an id that is not in the list answers 400 {"error":"Unknown acquiring bank"}. Explicit null CLEARS the field (the "None" row of the picker); omitted leaves it unchanged. Stored as acquiring_bank_id. |
| `companyId` | string (uuid) \| null | no | Id of the COMPANY behind the gateway, the legal entity it is boarded under: a row of the companies reference list (served under /v1/companies). A select field, never free text: an id that is not in the list answers 400 {"error":"Unknown company"}. Explicit null CLEARS the field (the "None" row of the picker); omitted leaves it unchanged. Stored as company_id. |
| `supportsAmex` | boolean | no | Card network flag: American Express. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `supportsMastercard` | boolean | no | Card network flag: Mastercard. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `supportsVisa` | boolean | no | Card network flag: Visa. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `supportsDiscover` | boolean | no | Card network flag: Discover. Routing skips a gateway for a card network it does not support; all four flags false means every network. |
| `mcRefundFeeCents` | integer >= 0 | no | Mastercard refund and chargeback flat fee, integer cents. |
| `visaRefundFeeCents` | integer >= 0 | no | Visa refund and chargeback flat fee, integer cents. |
| `discountFeeBps` | integer 0..1000000 | no | Merchant discount rate in BASIS POINTS (1% = 100). Not a 0..1 ratio and not a percent. |
| `transactionFeeCents` | integer >= 0 | no | Flat fee per attempt, integer cents. |
| `reserveRateBps` | integer 0..1000000 | no | Rolling reserve rate in BASIS POINTS. |
| `stripeMode` | enum: 's2s' \| 'embedded' \| 'hosted' | no | Stripe integration mode: s2s, embedded or hosted. Stored as stripe_mode. Any other value is a 400. |

**Request body**

```json
{
  "productMatchingEnabled": true,
  "bankPage": "https://shop.acme.example/checkout",
  "monthlyCapCents": 75000000,
  "categoryIds": [
    "3f0c8d21-55ab-4f9e-9c10-7ab2e4f61d38"
  ]
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. The route returns NO representation of the updated row: read it back with GET /v1/accounts to see the new state. |

**Errors**

- `400` {"error":"Invalid","details":<validation details>}: a field failed the schema (wrong type, over its maximum length, not an integer, negative, or a gatewayType outside the list, kontrolpay included). {"error":"No fields to update"}: the parsed body set no recognised field (an empty body {} or a body of only unknown keys). {"error":"Provide a security key, or both a username and password."}: the update would leave the row without valid credentials (a database check). On a Stripe gateway: {"error":<sentence>,"details":{"formErrors":[],"fieldErrors":{"login"|"securityKey"|"password":[<sentence>]}}}. The keys are checked as they would be stored: a key in the body (trimmed), else the stored one. error is the sentence of the first failing key, in the order login, securityKey, password. The sentences: "Enter the Stripe publishable key." / "Stripe publishable keys must start with pk_test_ or pk_live_." (login), "Enter the Stripe secret key." / "Enter a Stripe secret key starting with sk_test_ or sk_live_, or a restricted rk_ or rkcs_ key." / "Stripe publishable and secret keys must both use test mode or both use live mode." (securityKey), "Stripe webhook signing secrets must start with whsec_. Leave this field empty if no webhook is configured." (password). Nothing is written. {"error":"Unknown processor"}, {"error":"Unknown acquiring bank"} or {"error":"Unknown company"}: processorId, acquiringBankId or companyId is a well formed uuid but not a row of its reference list. {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"}: no gateway with that id is owned by the account of the caller (an unknown id and an id of another account both land here).
- `409` {"error":"This gateway is managed by KontrolPay. Only its categories can be changed here."} when the gateway is of type kontrolpay and the body carries any field other than categoryIds. Nothing is written. The new name is already taken by a gateway of the account: the sentence starts with A gateway named "<name>" already exists and tells to rename it or edit the existing one (an archived gateway keeps its name: look in the Archived tab). The sentence that starts with "Your account record is incomplete": the owner of the gateway is not a known account. Rare. {"error":"This gateway is archived. Restore it before switching it on."} when activated is true on an archived gateway. Nothing is written.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Unrecognised database error: {"error":"Internal Server Error","requestId":"..."}.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API.
- On a kontrolpay row { "categoryIds": [...] } alone is accepted and answers { "ok": true }: categories are the routing labels of the account and move no money. Name, activation, cap, fees, reserve, descriptors, references and credentials are set by KontrolPay.
- productMatchingEnabled: this is the route that changes it on an existing gateway. POST /v1/accounts writes it at creation (on when the key is absent) and duplicate copies it from the source. Verify with GET /v1/accounts (product_matching_enabled).
- Turning productMatchingEnabled on is not sufficient by itself: the gateway needs a bankPage, that normalised host needs an ACTIVE product catalog (managed at PUT /v1/storefronts/:id/products), and the Smart product matching integration of the account must be on. With no catalog, or no basket whose prices sum exactly to the charge amount, the charge falls back to the generic line SILENTLY, with no error and no signal on this response.
- The basket is matched on the AMOUNT ALONE against the catalog of the gateway's own bank page. It is never derived from what the customer actually bought, and the bank page is read from the database at charge time, not from the request.
- Category links are REPLACED wholesale (delete all, then insert again). categoryIds [] silently unlinks everything; omitting the key is the only way to keep the existing links. Only categories of the account are linked: an id of another account is ignored.
- Credential fields are set or cleared, never merged: { "login": "" } clears the stored login. Combined with the database check, clearing the wrong one answers 400 and the whole transaction rolls back (nothing is applied). On a Stripe gateway the publishable key and the secret key cannot be cleared ("" answers 400); only the webhook secret can.
- The create-time rules do not run on update: gatewayType can be switched to checkoutchamp without campaignId and productId, or to another type without its key. The write succeeds and the charge path fails later. One exception: a Stripe gateway has its keys checked on every update. Because the stored keys are checked when the body does not replace them, a Stripe gateway whose stored keys fail the rules refuses every PATCH, a rename included, until valid keys are sent in the same body.
- owner_email cannot be changed through this API; there is no ownership transfer field.
- A request that carries only category links ({ "categoryIds": [...] }) is valid: no column is updated, the links are replaced and the response is { "ok": true }.
- The storefront of bankPage is ensured AFTER the transaction commits and only when bankPage was present in the body. It never fails the request: if it fails, the bank page of the gateway is changed anyway and the storefront row is silently missing.
- Field names in the body are camelCase; the values read back from GET /v1/accounts are snake_case column names. They do not round-trip verbatim.
- Every successful PATCH is audit-logged (action update, object type account, object id = :id, object name = the body's name when present).
- acquirerBin and caid are the ACQUIRER identity of the gateway (the BIN of the acquiring bank and the Card Acceptor ID it issued). They are not sent to the gateway. When BOTH are set, a 3DS authentication started for a charge whose first route is this gateway names them, with mcc, as the acquirer; a gateway that lacks one of them keeps the identity configured on the 3DS integration. The response is { "ok": true } with no echo: read GET /v1/accounts and check acquirer_bin and caid on the row.
- Stripe: gatewayType=stripe; stripeMode=s2s|embedded|hosted (default s2s); login=publishable key, securityKey=secret key, password=optional webhook secret. Matching test or live environments are required.
- gatewayType checkoutchamp and other are accepted and stored, but no charge adapter exists for them yet: such a MID cannot process a charge (the dashboard does not offer them).

##### `DELETE /v1/accounts/:id`

**Scope** `routing.write` - **Delete gateway**

Permanently delete one gateway owned by the caller's account, live or archived. No confirmation step. To keep its history, archive it instead (POST /v1/accounts/:id/archive). A gateway managed by KontrolPay cannot be deleted.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Gateway id. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. |

**Response** `204`

No example body: see the purpose above for what the response carries.

| response field | type | description |
|---|---|---|
| `(none)` | empty | 204 with an empty body on success. Do not parse JSON: parsing the empty body throws. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"}: no row matched (unknown id, already deleted, or owned by another account).
- `409` {"error":"A KontrolPay gateway cannot be deleted."} when the gateway is managed by KontrolPay (type kontrolpay with its KontrolPay account). Nothing is deleted.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API.
- A kontrolpay gateway is closed by KontrolPay with its account; the row is kept for history.
- Irreversible and immediate: no confirm parameter, no dry run. POST /v1/accounts/:id/archive is the reversible alternative.
- The delete CASCADES: the gateway is removed from every ATRI membership, and its category links, its monthly usage counters and its BIN routing entries all disappear. Removing a gateway from a live failover pool changes routing at once.
- Past transactions are NOT deleted but are DETACHED: the final gateway of the transaction and the gateway of each attempt are set to null, so past charges lose their gateway attribution and reports by gateway go blank for those rows.
- Deleting a gateway does not delete the storefront row created from its bank page; that catalog remains under /v1/storefronts (its gateway count just drops).
- 204 means the body is empty; the audit log still records the action delete on the object type account.
- Prefer PATCH { "activated": false } when the aim is only to stop traffic: it is reversible and keeps history.
- Archive and delete coexist: an archived gateway (GET /v1/accounts?archived=true) can still be deleted here.

##### `POST /v1/accounts/:id/archive`

**Scope** `routing.write` - **Archive gateway**

Archive one gateway owned by the caller's account instead of deleting it: it is switched off, leaves the live list and every picker, and keeps its history. Answers the archived row. Undo it with POST /v1/accounts/:id/restore; DELETE /v1/accounts/:id erases it for good. A gateway managed by KontrolPay cannot be archived.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Gateway id. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. |

**Response** `200`

```json
{
  "account": {
    "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
    "name": "Acme Processing MID 1",
    "activated": false,
    "archived_at": "2026-11-24T14:05:12.640Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `account.id` | string (uuid) | The gateway id. |
| `account.name` | string | Its name, unchanged. |
| `account.activated` | boolean | Always false: an archived gateway is off. |
| `account.archived_at` | string (ISO 8601) | When it was archived (the first archive when it already was). |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"}: no row matched (unknown id, or owned by another account).
- `409` {"error":"A KontrolPay gateway cannot be archived."} when the gateway is managed by KontrolPay (type kontrolpay with its KontrolPay account). Nothing is archived.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Nothing is erased: past transactions, attempts, refunds and reports keep naming the gateway, and its credentials, fees, categories and ATRI memberships stay as they were.
- Routing stops at once: the gateway is switched off (activated false), so no ATRI, BIN pin or rebill route picks it. In the ATRIs it belongs to it stays listed as a member, off, until you remove it or restore it.
- GET /v1/accounts leaves it out; GET /v1/accounts?archived=true lists it. An archived gateway keeps its name: a new gateway cannot take that name until the archived one is renamed.
- POST /v1/accounts/:id/restore brings it back, still off: switch it on with PATCH /v1/accounts/:id { "activated": true } once reviewed.
- Idempotent: archiving an archived gateway keeps the date of the first archive.
- A gateway managed by KontrolPay is never archived (409); it is closed with its KontrolPay account.
- There is no request body; anything sent is ignored.

##### `GET /v1/accounts/:id/credentials`

**Scope** `routing.write` - **Read gateway credentials**

Decrypts and returns one gateway's stored credentials in clear (to fill an edit form or to copy a configuration), only to a caller that may edit the gateway; no-store and audited. A gateway managed by KontrolPay has no credentials.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Gateway id. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. |

**Response**

```json
{
  "login": "acme_api",
  "password": "example-password",
  "securityKey": ""
}
```

| response field | type | description |
|---|---|---|
| `login` | string | Decrypted login of the gateway (an NMI user name, a CheckoutChamp loginId, a Stripe publishable key, or the merchant e-mail of another type). An EMPTY STRING when not set, never null. |
| `password` | string | Decrypted password. Empty string when not set. |
| `securityKey` | string | Decrypted security key or secret key. Empty string when not set. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"}: the key lacks routing.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Not found"}: unknown id or a gateway owned by another account.
- `409` {"error":"A KontrolPay gateway has no credentials."} when the gateway is of type kontrolpay: answered before any decryption, and no audit row is written.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: decryption failed (a wrong or rotated CREDENTIAL_ENC_KEY, or a corrupt stored value); the route does not catch decryption errors.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API.
- Absent credentials come back as "" (empty string), not null: test emptiness on the string, never on null.
- A decryption failure is an uncaught 500, not an empty string. If the encryption key was rotated, every credentials read of an older row answers 500 while GET /v1/accounts keeps working (it only tests whether a value is stored).
- The response has no id and no name: pair it with GET /v1/accounts to know which gateway it belongs to.
- The answer carries LIVE secrets in clear: it is sent with Cache-Control: no-store and Pragma: no-cache. Never log it, never cache it, never echo it into a transcript.
- Each call that returns at least one value writes ONE audit row: action view_secret, the caller (an API key is recorded as apikey:<id>), the object type and id, and the object name followed by the NAMES of the fields shown, never a value. A call on a gateway with nothing stored returns empty values and writes no row.

##### `POST /v1/accounts/:id/duplicate`

**Scope** `routing.write` - **Duplicate gateway**

Clone one gateway you own: every column, including the encrypted credentials, the fee schedule, the descriptors, the bank page, the processor, the acquiring bank and the company, the owner and the category links, under a unique "(copy)" name and forced DEACTIVATED, so the clone cannot take live traffic until reviewed. A gateway managed by KontrolPay cannot be duplicated.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Id of the gateway to clone. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. There is no request body; anything sent is ignored. |

**Response** `201`

```json
{
  "account": {
    "id": "e2a71d55-9f38-42c7-b6d1-0c4a8e5f1b73",
    "name": "Acme Processing MID 1 (copy 2)",
    "activated": false,
    "monthly_cap_cents": "50000000",
    "created_at": "2026-08-30T17:05:12.640Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `account.id` | string (uuid) | Id of the newly created clone. |
| `account.name` | string | "<source name> (copy)", or "<source name> (copy N)" for N = 2..99 when earlier names are taken in the account. |
| `account.activated` | boolean | Always false: the clone is created deactivated, whatever the source. |
| `account.monthly_cap_cents` | string (bigint as string) | Copied from the source, in integer cents, as a JSON string. |
| `account.created_at` | string (ISO 8601) | Creation timestamp of the clone (fresh, not copied). |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"}: unknown id or a gateway owned by another account.
- `409` {"error":"A KontrolPay gateway cannot be duplicated. Add a new application instead."} when the gateway is of type kontrolpay. No gateway is created. {"error":"A gateway with this name already exists in this account."}: the route maps no error itself, so a name collision reaches the global database error handler (every "(copy N)" name is taken, or two concurrent duplicates of the same gateway).
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Unrecognised database error: {"error":"Internal Server Error","requestId":"..."}.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- `kontrolpay`: managed by KontrolPay, created by an approved application, never created or converted through this API.
- For another website or business line on KontrolPay, add a new application: each approved application is its own gateway.
- product_matching_enabled, descriptor_enabled and the Stripe mode are copied from the source like every other column.
- The clone is always activated: false. Nothing goes live until PATCH { "activated": true }.
- Credentials ARE copied (the encrypted values are copied as they are), so the clone charges through the same processor credentials as the source. Rotate them if the copy is meant for another merchant account.
- Category links are copied too, but the clone is NOT added to any ATRI: routing membership is created again by hand.
- The name is probed one candidate at a time and the probe is racy: two concurrent duplicates of the same gateway can pick the same name, and the loser answers 409. The last candidate, "(copy 99)", is not probed before the insert, so a gateway that already has 99 copies answers 409.
- The probe looks at the gateways of the account only: a name held by a gateway of another account does not change the suffix.
- No request body is read: the name, the activation or any other field cannot be overridden at duplicate time; do it with a follow-up PATCH.
- Like create, the 201 body carries only five fields; read the full row back with GET /v1/accounts.
- Unlike create, this route does NOT ensure a storefront: the copied bank_page relies on the storefront row the source already created.
- processor_id, acquiring_bank_id and company_id are copied as they are, so the clone reports under the same processor, acquiring bank and company in every filter and breakdown until PATCH { processorId, acquiringBankId, companyId } on the new id.

##### `POST /v1/accounts/:id/restore`

**Scope** `routing.write` - **Restore an archived gateway**

Bring an archived gateway back to the live list (GET /v1/accounts) and the pickers. It stays OFF: switch it on with PATCH /v1/accounts/:id { "activated": true } once reviewed, then add it back to the ATRIs that should route to it if you removed it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Gateway id. Not validated by a schema: a value that is not a uuid reaches the database and answers 400 "A value has an invalid format.", not 404. |

**Response** `200`

```json
{
  "account": {
    "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
    "name": "Acme Processing MID 1",
    "activated": false,
    "archived_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `account.id` | string (uuid) | The gateway id. |
| `account.name` | string | Its name, unchanged. |
| `account.activated` | boolean | false: a restored gateway stays off until you switch it on. |
| `account.archived_at` | null | null: the gateway is live again. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a valid uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"}: no row matched (unknown id, or owned by another account).
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Restoring a gateway that is not archived changes nothing and answers the row.
- Its ATRI memberships were kept while it was archived: once switched on, it routes again in every ATRI it is still an active member of.
- There is no request body; anything sent is ignored.

##### `POST /v1/accounts/convesio/connect`

**Scope** `routing.write` - **Mint ConvesioPay secret key**

ConvesioPay S2S onboarding: Basic-auth to ConvesioPay's /integrations/connect with the merchant's email+password and the server-held account-wide integration id, register the bank page as an integration domain with its webhook, and return the minted per-MID secretKey.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string | **yes** | ConvesioPay merchant account email, 1..256 chars. Used as the Basic-auth username upstream. No email-format validation is applied. |
| `password` | string | **yes** | ConvesioPay merchant account password, 1..256 chars. Used as the Basic-auth password upstream. |
| `bankPage` | string | **yes** | The MID's bank page, 1..256 chars. Sent upstream as `domain` after prefixing `https://` when no http(s):// scheme is present - the value is otherwise used AS TYPED (path and any `wallet.` prefix are NOT stripped here, unlike storefront host normalisation). |
| `integrationName` | string | no | Optional label for the ConvesioPay integration, max 128. Trimmed; if omitted or blank after trimming, the derived `domain` is used as the name. |

**Request body**

```json
{
  "email": "merchant@example.com",
  "password": "correct-horse-battery",
  "bankPage": "shop.example.com",
  "integrationName": "Acme EU storefront"
}
```

**Response**

```json
{
  "secretKey": "cvp_sk_live_EXAMPLE"
}
```

| response field | type | description |
|---|---|---|
| `secretKey` | string | The minted per-MID ConvesioPay S2S secret key, passed straight through from ConvesioPay's response. NOT persisted by this route - you must store it yourself. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten()>}` - email/password/bankPage missing, empty, or over their max length.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `409` {"error":"No ConvesioPay integration id is configured for this account yet (Settings)."} when the account has no ConvesioPay integration id; nothing is sent upstream.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `502` ConvesioPay returned a non-2xx: `{"error":"<ConvesioPay's own message, e.g. site already connected>","detail":"<first 300 chars of the raw body>"}`, falling back to `{"error":"ConvesioPay returned HTTP 409", ...}` when no message can be parsed. NOTE: an upstream 401/409 is reported to you as 502. `{"error":"ConvesioPay returned a non-JSON response."}` - 2xx body that would not parse as JSON. `{"error":"ConvesioPay response contained no secretKey.","keys":["..."]}` - 2xx JSON without a string `secretKey`; `keys` lists the top-level keys that were present. `{"error":"ConvesioPay request failed: <message>"}` - network failure or the 20 s AbortSignal timeout (message is typically 'The operation was aborted due to timeout').
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- THE SECRET IS NOT SAVED. This route mints and returns it only; nothing is written to nmi_accounts. Persist it yourself with PATCH /v1/accounts/:id {"securityKey": "<secretKey>"} or the connection is lost when you drop the response.
- It takes no MID id and is not bound to any account row - it is keyed on `bankPage` alone. Calling it twice for the same domain typically yields an upstream 'already connected' error surfaced as a 502.
- Every upstream failure is flattened to 502 regardless of its real status - bad merchant credentials (upstream 401) are indistinguishable from a real gateway outage except by reading `error`/`detail`.
- The webhook is registered for you as `<domain>/payment-status` with eventTypes ['payment','paymentMethods'] - you cannot override the URL or the event list.
- `domain` is derived from `bankPage` verbatim after adding a scheme, so a bankPage containing a path (`shop.example.com/checkout`) registers that whole string as the domain and builds the webhook URL from it.
- No merchantApiKey is sent - this flow does not bind a merchant sub-user.
- Upstream base URL is CONVESIO_API_BASE (default https://api.convesiopay.com/v1), with a hard 20 s timeout; the call is not retried.
- The merchant password is sent in the request body of a mutating admin call - it is not logged by the route, but treat it as a credential-bearing request.
- Charges on a ConvesioPay gateway use its securityKey (this secretKey) and the ConvesioPay integration id of the account; the stored login (merchant e-mail) is not used to charge.

##### `POST /v1/accounts/import`

**Scope** `routing.write` - **Bulk-import gateways**

Create up to 1000 gateways from an 8 MiB JSON body. Uses the same validation and encrypted credential mapping as single-create, bounded insert batches, and per-row validation/conflict errors.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `accounts` | object[] | **yes** | 1..1000 objects. The outer schema accepts each element as an arbitrary record; each element is then validated against the FULL create schema (same fields, same defaults, same credential rules as POST /v1/accounts, Stripe rules included: a Stripe row needs its publishable and secret keys, which are trimmed, and is not subject to the securityKey-or-login-and-password rule). Despite the source comment about ';'-separated lines, this endpoint takes parsed JSON objects - the dashboard does the text parsing client-side. Rows may also carry `processorId` / `acquiringBankId` (uuid or null, v3.9 section 0) and `companyId` (uuid or null, v3.9.2 section 0 - the company, i.e. the legal entity the MID is boarded under; same rules as POST /v1/accounts); a row whose id is unknown fails ALONE with error "Unknown processor" / "Unknown acquiring bank" / "Unknown company" while the other rows are still created. |

**Request body**

```json
{
  "accounts": [
    {
      "name": "Acme MID 10",
      "securityKey": "example-nmi-security-key",
      "monthlyCapCents": 25000000,
      "bankPage": "shop.example.com",
      "supportsVisa": true
    },
    {
      "name": "Acme MID 11",
      "login": "acme_api",
      "password": "example-password",
      "gatewayType": "checkoutchamp",
      "campaignId": "42",
      "productId": "777"
    },
    {
      "name": "Broken row"
    }
  ]
}
```

**Response**

```json
{
  "created": [
    {
      "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
      "name": "Acme MID 10",
      "activated": true,
      "monthly_cap_cents": "25000000",
      "created_at": "2026-08-30T16:44:19.204Z"
    },
    {
      "id": "b47ac10b-58cc-4372-a567-0e02b2c3d479",
      "name": "Acme MID 11",
      "activated": true,
      "monthly_cap_cents": "0",
      "created_at": "2026-08-30T16:44:19.331Z"
    }
  ],
  "errors": [
    {
      "index": 2,
      "name": "Broken row",
      "error": "Provide either securityKey or both login and password"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `created` | object[] | One entry per successfully inserted row, in input order, each with the same 5 fields as POST /v1/accounts (id, name, activated, monthly_cap_cents, created_at). |
| `errors` | object[] | One entry per rejected row. Empty array when everything succeeded. |
| `errors[].index` | number | 0-based index of the row in the submitted `accounts` array. |
| `errors[].name` | string \| null | The row's `name` if it was a string, else null (e.g. name missing or not a string). |
| `errors[].error` | string | For a validation failure: the message of the FIRST issue only (or 'Invalid row'); for a Stripe row with a bad key, the sentence of its first failing key, for example 'Enter the Stripe secret key.'. For a DB failure: the mapped message (duplicate name / owner FK / check), or 'Insert failed' when the DB error is unrecognised. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten()>}` - the envelope itself is bad (missing `accounts`, empty array, more than 1000 elements, or an element that is not an object). `{"created":[],"errors":[...]}` - the request was well-formed but NOT ONE row was inserted. Same body shape as the 201; only the status differs.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Unrecognised failure outside the per-row try/catch.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Status 201 means at least one confirmed row was created; inspect errors even on success. Status 400 can include an uncertain commit outcome: check the gateway list before retrying when that message is present.
- Each insert batch has at most 100 rows and is atomic. Earlier successful batches remain if a later batch fails. Known validation/constraint failures are isolated; connection failures or uncertain commits are never automatically replayed and stop remaining batches.
- Only the first validation error per input row is reported. Unknown input keys are stripped, as in single-create.
- The first successfully inserted occurrence of a name wins. Names are unique within the owner account. Reference IDs are validated before writes; concurrent changes remain checked by database constraints.
- Category links are filtered to the gateway owner. productMatchingEnabled is honored; omission defaults true. Credential values are encrypted before batch execution.
- Successful batches create missing storefront records for normalized bank-page hosts on a best-effort basis. No payment is made by importing a gateway.
- The limit remains 1000 rows; split larger files. Imports use the atomic batch implementation without a per-row rollout switch.

##### `GET /v1/acquiring-banks`

**Scope** `routing.read` - **List acquiring banks**

Returns the GLOBAL reference list of acquiring banks - the ACQUIRING BANK / service behind the MID - that every gateway's "Acquiring bank" select field draws from (v3.9 §0, migration 138). Ordered by name, active rows only unless ?includeInactive=1, each with how many gateways (nmi_accounts) and wallet providers point at it. Read-only; nothing changes.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `includeInactive` | string | no | `1` or `true` also returns rows a super_admin deactivated (active = false). Anything else, or absent, = active rows only. |

**Response**

```json
{
  "rows": [
    {
      "id": "5a8c3e17-9b2d-4f60-a1e4-7c3b0d9f2e88",
      "name": "ADYEN",
      "aliases": [],
      "active": true,
      "source": "seed",
      "gateway_count": 5,
      "wallet_count": 16,
      "in_use": true
    },
    {
      "id": "c1e6f4b9-3a7d-4e25-9c08-6b2d1f8a3e07",
      "name": "CHESAPEAK",
      "aliases": [
        "CHESAPEAKE",
        "CHESAPEAKE BANK"
      ],
      "active": true,
      "source": "seed",
      "gateway_count": 16,
      "wallet_count": 0,
      "in_use": true
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Every acquiring bank the filter admits, ordered by name. Never null; an empty array only before migration 138 seeded the list. |
| `rows[].id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.processor_id / acquiring_bank_id) and a wallet provider stores (wallet_providers, same two columns). |
| `rows[].name` | string | Canonical name, stored UPPERCASE as the operator's list spells it ("PRIORITY", "COASTAL PAY", "FFB BANK"). Unique case-insensitively (unique index on lower(name)). |
| `rows[].aliases` | string[] | Alternate tokens the name is known by ("CONVESIOPAY", "MV", "FFB"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `rows[].active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `rows[].source` | string | `seed` (migration 138, the operator's list), `airtable` (an acquirer only the Airtable MID sheet named) or `manual` (created through POST - Add unlisted). |
| `rows[].gateway_count` | number | v3.9.9 - the caller's ACCOUNT's MIDs referencing the row (the table is global). |
| `rows[].wallet_count` | number | v3.9.9 - the caller's account's wallet providers referencing the row. |
| `rows[].in_use` | boolean | v3.9.9 - whether ANY gateway / wallet provider (any account) references the row: the delete guard's question (DELETE answers in_use). |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund, {"error":"No access - ask an admin to grant you a role"} for a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- The list is global, not per account: every account sees the same acquiring bank rows. gateway_count and wallet_count count only the caller's account's gateways and wallet providers; in_use says whether any account references the row (what DELETE checks).
- Names and aliases are UPPERCASE by construction; match them case-insensitively anyway when you resolve a token (the API does: name OR alias, lower() on both sides).
- This is the ONLY way to obtain the id a gateway field takes - POST/PATCH /v1/accounts and the wallet-provider routes take it as `acquiringBankId` (uuid, camelCase - the body key, not the acquiring_bank_id column) from this list, never a free-text name. Their schemas strip unknown keys, so a snake_case `acquiring_bank_id` is silently ignored and the field stays null.
- No pagination, search or sort parameters: the whole list (a few dozen rows) comes back on every call. Filter client-side.
- A deactivated row stays referenced by the gateways that already chose it - deactivation hides it from pickers, it does not detach anything. Use DELETE (only when nothing references it) to remove one.
- Ordering is `order by r.name asc` under the database collation; with all-uppercase names that is plain alphabetical.

##### `POST /v1/acquiring-banks`

**Scope** `routing.write` - **Add an unlisted acquiring bank**

"Add unlisted" from the Acquiring bank picker: creates an acquiring bank that is not in the list yet, stamped source `manual` and created_by = the caller. DEDUPES instead of refusing: when the name (trimmed, uppercased) already is the name OR an alias of an existing row, case-insensitively, that row comes back with 200 and `existing: true` - no duplicate, no 409. A brand-new row answers 201 with `existing: false`.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | The name as the operator types it. Trimmed BEFORE validation (1 to 64 characters after the trim); then inner whitespace is collapsed to single spaces and the result UPPERCASED for storage - "convesio pay" is stored as CONVESIO PAY and is the same row as "Convesio Pay". The length check runs on the trimmed value only, so a 66-character name padded with double spaces is a 400 even though it would collapse under 64. |
| `aliases` | string[]; default `[]` | no | Optional alternate tokens (up to 50, each up to 64 chars). Normalised like the name; empties, duplicates and the name itself are dropped. Ignored when the name resolves to an existing row (its aliases are NOT extended). An alias another row already answers to is refused with 409. |

**Request body**

```json
{
  "name": "new bank",
  "aliases": [
    "nb"
  ]
}
```

**Response**

```json
{
  "row": {
    "id": "a3f1d8c5-2e6b-4a97-b0d4-9c7e5f2a1b63",
    "name": "NEW BANK",
    "aliases": [
      "NB"
    ],
    "active": true,
    "source": "manual",
    "gateway_count": 0,
    "wallet_count": 0
  },
  "existing": false
}
```

| response field | type | description |
|---|---|---|
| `row` | object | The acquiring bank - the new row (201) or the existing one the name resolved to (200). |
| `row.id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.processor_id / acquiring_bank_id) and a wallet provider stores (wallet_providers, same two columns). |
| `row.name` | string | Canonical name, stored UPPERCASE as the operator's list spells it ("PRIORITY", "COASTAL PAY", "FFB BANK"). Unique case-insensitively (unique index on lower(name)). |
| `row.aliases` | string[] | Alternate tokens the name is known by ("CONVESIOPAY", "MV", "FFB"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `row.active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `row.source` | string | `seed` (migration 138, the operator's list), `airtable` (an acquirer only the Airtable MID sheet named) or `manual` (created through POST - Add unlisted). |
| `row.gateway_count` | integer | Number of nmi_accounts rows referencing this entry - every account's, not just the caller's (the list is global). A JSON number (cast ::int). |
| `row.wallet_count` | integer | Number of wallet_providers rows referencing this entry, platform-wide. A JSON number. |
| `existing` | boolean | false = created now (status 201). true = the name already was a name or an alias, this is that row (status 200) and nothing was written. |

**Errors**

- `400` Zod validation failed: `name` missing, not a string, blank once trimmed, or longer than 64 characters; `aliases` not an array of strings, more than 50 of them, or one longer than 64. Body is `{ "error": "Invalid", "details": <zod flatten()> }`.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"} when the key's scopes lack routing.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (gate, then the handler's own check).
- `409` Two cases. (a) One of the `aliases` already belongs to another row (as its name or one of its aliases): `{ "error": "\"FFB\" is already used by FFB BANK" }`. (b) The name resolves to a DEACTIVATED row (active=false): `{ "error": "\"NUVEI\" is deactivated" }` - deactivation is a super_admin control, so "Add unlisted" never hands the row back; a super_admin restores it with PATCH { "active": true } first. An ACTIVE taken name never 409s - it returns that row with 200. A unique-index race (23505, two callers adding the same name at once) is resolved the same way: the winner comes back as `existing: true`.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Two success codes: 201 when created, 200 when deduped. Read `existing` rather than the status if you need to know which - both carry the full row.
- GLOBAL side effect: a row added here is visible to every account on the platform (the list is not per tenant). This is why a member with role user cannot grow the list, and why rename, deactivate and delete are kept for the platform operator.
- Dedupe matches aliases too: POST { "name": "chesapeake bank" } returns CHESAPEAK (existing: true) because the token is one of its aliases. Send the canonical name or any alias - you get the same id.
- The stored name is the NORMALISED value (trim, single spaces, UPPERCASE), so `row.name` may differ from what you sent. Do not compare it to your input; use `row.id`.
- An API key can add entries (it acts as role admin of its account); a key without routing.write cannot.
- Every successful call is written to the admin action log (objectType `acquiring_bank`, page Gateways, objectName = the body `name`), including the 200 dedupe answers - the hook logs any 2xx mutation.
- Not idempotent in the REST sense but safe to retry: a repeated POST of the same name is a 200 dedupe, never a duplicate.

##### `GET /v1/categories`

**Scope** `routing.read` - **List categories**

Returns every gateway category owned by the caller's account, alphabetically by name, each with a count of how many gateways (nmi_accounts) are linked to it. Read-only; nothing changes.

*No parameters.*

**Response**

```json
{
  "categories": [
    {
      "id": "3f2b9c14-7a55-4e8d-9b21-0c6d8e4a1f77",
      "name": "felham",
      "created_at": "2026-03-11T09:42:18.221Z",
      "gateway_count": 4
    },
    {
      "id": "a91d0e63-2c48-4f10-8ab7-5d33e9c07b02",
      "name": "high-risk",
      "created_at": "2026-01-28T16:05:03.884Z",
      "gateway_count": 0
    },
    {
      "id": "c74e5518-9d06-4b3a-a1cf-62b8470de935",
      "name": "subscriptions",
      "created_at": "2026-05-02T11:19:47.500Z",
      "gateway_count": 2
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `categories` | object[] | All categories owned by the caller's account. Never null; an empty array when the account owns none. |
| `categories[].id` | uuid | Category primary key. Use this in the PATCH/DELETE path and when linking gateways. |
| `categories[].name` | string | Display name. Unique per owner, not globally - another tenant can hold the same name. |
| `categories[].created_at` | timestamptz (ISO 8601 string) | When the category row was created. |
| `categories[].gateway_count` | integer | Number of rows in nmi_account_categories pointing at this category. Cast ::int in SQL, so it is a JSON number, NOT a bigint-as-string. Zero when nothing is linked. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard); generic HTTP clients are not matched.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (Postgres statement timeout).

**Gotchas**

- The ownership filter is ALWAYS applied - there is no unscoped mode. `ownerScope()` in routes/v1/ownership.ts never returns null/empty, so the `${owner ? \`where ${owner}\` : ''}` ternary is a dead branch. Every caller sees ONLY categories where owner_email = their own account email.
- Categories with `owner_email IS NULL` (the old 'global' rows) are INVISIBLE TO EVERYONE. The generated predicate is `c.owner_email = $1`, and SQL `=` never matches NULL. The comment at the top of the file claiming 'Admin sees/manages all (owner null = global)' is stale - migration 064 backfilled owners and the code no longer has that path.
- If the caller's account email is null the query becomes `owner_email = NULL`, which matches nothing: you get HTTP 200 with `{"categories": []}`, not an error. An empty list can mean 'no categories' OR 'scope failed to load'. The gate fails closed by design.
- `gateway_count` is a raw link count from nmi_account_categories with NO filter on the gateway side - it does not exclude inactive/disabled MIDs, and it is not restricted to MIDs your account owns. Do not read it as 'active gateways available'.
- No pagination, no search, no filter, no sort parameters exist. The route reads neither req.query nor req.params. Sending any query string is silently ignored, and the full owned set is returned on every call.
- Ordering is `order by c.name asc` using the database collation - under the C/POSIX collation uppercase names sort before all lowercase ones. Do not assume case-insensitive alphabetical order.

##### `POST /v1/categories`

**Scope** `routing.write` - **Create a category**

Creates a new gateway category owned by the caller's account. The owner is stamped from the authenticated caller, never from the request body. Returns the created row with gateway_count hardcoded to 0.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Category name, 1 to 128 characters. Validated by zod BEFORE trimming, then `.trim()` is applied before insert. Must be unique among the categories your account already owns. |

**Request body**

```json
{
  "name": "subscriptions"
}
```

**Response**

```json
{
  "category": {
    "id": "c74e5518-9d06-4b3a-a1cf-62b8470de935",
    "name": "subscriptions",
    "created_at": "2026-05-02T11:19:47.500Z",
    "gateway_count": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `category.id` | uuid | Server-generated primary key (gen_random_uuid()). |
| `category.name` | string | The stored name - the TRIMMED value, which may differ from what you sent. |
| `category.created_at` | timestamptz (ISO 8601 string) | Creation timestamp from the database default now(). |
| `category.gateway_count` | integer | Always the literal 0 - hardcoded in the handler, not read back from the database. A brand-new category has no gateway links, so it happens to be correct. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: name missing, not a string, empty or longer than 128 characters (checked before trimming).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard); generic HTTP clients are not matched.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `409` {"error":"A category with this name already exists"}: the account already owns a category with this exact (trimmed) name.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Whitespace-only names slip through. Zod checks `min(1)` on the RAW string, and `.trim()` runs afterwards - so `{"name":"   "}` passes validation and inserts a category whose name is the empty string. Same ordering issue with max(128): a 130-char string that trims to 126 is still rejected.
- Uniqueness is PER OWNER, not global. The index is `categories (coalesce(owner_email,''), name)` (migration 050). Getting 201 does not mean the name is free platform-wide, and getting 409 only tells you about your own account's categories.
- You cannot create a global / NULL-owner category through this endpoint. owner_email always comes from `ownerForInsert(req)` = the caller's account email. Any `owner_email` you put in the body is ignored - the zod schema only picks up `name` and drops every other key.
- The success status is 201, not 200. The response envelope key is `category` (singular), while GET returns `categories` (plural).
- Not idempotent and there is no idempotency key. Retrying a request whose response you missed will either create a duplicate (different name) or return 409 (same name) - a 409 on retry usually means your first call actually succeeded.
- Every successful mutation is written to the account action log (action, object type categories, objectName = the name sent in the body, the acting user or key).

##### `PATCH /v1/categories/:id`

**Scope** `routing.write` - **Rename a category**

Renames one category the caller's account owns. `name` is the only mutable field. Gateway links are untouched - the category id stays the same, so every linked gateway follows the rename automatically.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Id of the category to rename. Read via `req.params.id` and passed straight to Postgres as a uuid - a non-uuid string produces a database cast error, not a route-level validation message. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | New name, 1 to 128 characters. Validated by zod BEFORE trimming, then `.trim()` is applied before the UPDATE. Must not collide with another category your account owns. |

**Request body**

```json
{
  "name": "subscriptions-eu"
}
```

**Response**

```json
{
  "category": {
    "id": "c74e5518-9d06-4b3a-a1cf-62b8470de935",
    "name": "subscriptions-eu",
    "created_at": "2026-05-02T11:19:47.500Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `category.id` | uuid | Unchanged primary key - a rename never reissues the id. |
| `category.name` | string | The stored name after trimming. |
| `category.created_at` | timestamptz (ISO 8601 string) | Original creation timestamp; a rename does not update it, and there is no updated_at column. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: name missing, empty or longer than 128 characters. A malformed :id (not a uuid) answers 400 {"error":"A value has an invalid format."} from the global database error mapping.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard); generic HTTP clients are not matched.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: no category with that id in this account (another account's id answers the same).
- `409` {"error":"A category with this name already exists"}: the account already owns another category with the new name.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The success response OMITS `gateway_count`, while GET and POST both include it. The returning clause is only `id, name, created_at`. Do not write a shared parser that assumes a uniform category shape across the three endpoints.
- 404 is ambiguous by design and leaks nothing: 'no such id' and 'that id belongs to another tenant' are indistinguishable. The ownership predicate `and owner_email = $3` is always appended (ownerScope never returns empty). Rows with owner_email NULL can never be renamed by anyone.
- Whitespace-only names slip through: zod's min(1) runs on the untrimmed string, then `.trim()` runs before the UPDATE, so `{"name":"   "}` renames the category to an empty string.
- A bad `:id` does NOT come back as a clean route error. The try/catch here only handles 23505; a malformed uuid (22P02) escapes to the global error handler and returns the generic 'A value has an invalid format.' message.
- Renaming does not touch nmi_account_categories. Linked gateways keep pointing at the same category id, so every gateway silently shows the new name - there is no way to rename 'for new gateways only'.
- `name` is the only patchable field. Any other key in the body is silently dropped by the zod object (non-strict), so an attempt to reassign owner_email looks like a success but changes nothing.
- This is a full replace of the name, not a merge, and there is no optimistic-concurrency check: two concurrent PATCHes both return 200 and last-write-wins.

##### `DELETE /v1/categories/:id`

**Scope** `routing.write` - **Delete a category**

Permanently deletes one category the caller's account owns. Because nmi_account_categories has ON DELETE CASCADE, this also removes the category from every gateway that was linked to it. The gateways themselves are not deleted.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Id of the category to delete. Read via `req.params.id` and passed straight to Postgres as a uuid; a non-uuid value produces a database cast error rather than a route-level validation message. |

**Response** `204`

```json
HTTP 204 No Content (empty response body)
```

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a uuid (global database error mapping).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard); generic HTTP clients are not matched.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: no category with that id in this account (another account's id answers the same).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 204 No Content with a COMPLETELY EMPTY body. Do not call .json() on the response - it will throw. Check the status code only.
- This silently unlinks the category from every gateway. nmi_account_categories.category_id is `references categories(id) on delete cascade` (migration 017), so all link rows vanish. There is no 'category still in use' check, no confirmation step, no force flag, and the response does not tell you how many gateways were affected - call GET /v1/categories first and read gateway_count if that matters.
- Not reversible and not soft-deleted. There is no deleted_at column and no restore endpoint; the row is gone.
- Not idempotent in the usual REST sense: the first call returns 204, an immediate repeat returns 404. A 404 on retry after a dropped connection most likely means your first call succeeded.
- 404 is ambiguous by design: 'no such id' and 'owned by another tenant' are indistinguishable. The ownership predicate `and owner_email = $2` is always appended (ownerScope never returns empty), so rows with owner_email NULL can never be deleted through this API.
- Unlike POST and PATCH there is no try/catch here, so any constraint error is mapped only by the generic global handler and you get a generic message with no category-specific wording.
- The audit hook logs this as action 'delete', objectType 'categories', objectName null (there is no request body to read a name from) - the audit trail records WHICH id was deleted but not what it was called.

##### `GET /v1/companies`

**Scope** `routing.read` - **List companies**

Returns the GLOBAL reference list of companies - the legal entity (LLC) a MID is boarded under, the Airtable MID sheet's "Company" column - that every gateway's "Company" select field draws from (v3.9.2 §0, migration 147: the third reference kind next to processors and acquiring banks, same table shape, same routes). Ordered by name, active rows only unless ?includeInactive=1, each with how many gateways (nmi_accounts) and wallet providers point at it. Read-only; nothing changes.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `includeInactive` | string | no | `1` or `true` also returns rows a super_admin deactivated (active = false). Anything else, or absent, = active rows only. |

**Response**

```json
{
  "rows": [
    {
      "id": "2b6f1a84-9c3d-4e72-8a15-6d0e4f9b3c21",
      "name": "GAPO ECOM SCALE LLC",
      "aliases": [
        "GAPO"
      ],
      "active": true,
      "source": "airtable",
      "gateway_count": 6,
      "wallet_count": 1,
      "in_use": true
    },
    {
      "id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
      "name": "STELLAR TIDE LLC",
      "aliases": [],
      "active": true,
      "source": "airtable",
      "gateway_count": 21,
      "wallet_count": 0,
      "in_use": true
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Every company the filter admits, ordered by name. Never null; an empty array only before migration 147 seeded the list. |
| `rows[].id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.company_id) and a wallet provider stores (wallet_providers.company_id). |
| `rows[].name` | string | Canonical name, stored UPPERCASE as the Airtable MID sheet spells the legal entity ("STELLAR TIDE LLC", "GAPO ECOM SCALE LLC", "JM GRATEFUL LLC"). Unique case-insensitively (unique index on lower(name)). |
| `rows[].aliases` | string[] | Alternate tokens the name is known by - the "LLC"-less spelling the wallet-provider names carry in parentheses ("GAPO", "HEUR DIGIMEDIA", "BRYBAA AD"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `rows[].active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `rows[].source` | string | `airtable` (migration 147: the 11 companies of the Airtable MID sheet's Company column) or `manual` (created through POST - Add unlisted). `seed` is the column default and unused for companies. |
| `rows[].gateway_count` | number | v3.9.9 - the caller's ACCOUNT's MIDs referencing the row (the table is global). |
| `rows[].wallet_count` | number | v3.9.9 - the caller's account's wallet providers referencing the row. |
| `rows[].in_use` | boolean | v3.9.9 - whether ANY gateway / wallet provider (any account) references the row: the delete guard's question (DELETE answers in_use). |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund, {"error":"No access - ask an admin to grant you a role"} for a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- The list is global, not per account: every account sees the same company rows. gateway_count and wallet_count count only the caller's account's gateways and wallet providers; in_use says whether any account references the row (what DELETE checks).
- Names and aliases are UPPERCASE by construction; match them case-insensitively anyway when you resolve a token (the API does: name OR alias, lower() on both sides). The aliases are the "LLC"-less tokens ("GAPO" -> GAPO ECOM SCALE LLC), so a wallet-provider name's parenthesised token resolves.
- This is the ONLY way to obtain the id a gateway field takes - POST/PATCH /v1/accounts and the wallet-provider routes take it as `companyId` (uuid, camelCase - the body key, not the company_id column) from this list, never a free-text name. Their schemas strip unknown keys, so a snake_case `company_id` is silently ignored and the field stays null.
- No pagination, search or sort parameters: the whole list (a dozen rows) comes back on every call. Filter client-side.
- A deactivated row stays referenced by the gateways that already chose it - deactivation hides it from pickers, it does not detach anything. Use DELETE (only when nothing references it) to remove one.
- Migration 147 backfilled 81 of 89 gateways (76 by MID number on the Airtable sheet, 5 by the store's sibling MIDs) and 9 of 21 wallet providers (the token in the name); the rest are null until set from the Gateways page - a filter on the Company dimension shows them as (unset).
- Ordering is `order by r.name asc` under the database collation; with all-uppercase names that is plain alphabetical.

##### `POST /v1/companies`

**Scope** `routing.write` - **Add an unlisted company**

"Add unlisted" from the Company picker: creates a company (legal entity) that is not in the list yet, stamped source `manual` and created_by = the caller. DEDUPES instead of refusing: when the name (trimmed, uppercased) already is the name OR an alias of an existing row, case-insensitively, that row comes back with 200 and `existing: true` - no duplicate, no 409. A brand-new row answers 201 with `existing: false`. Same implementation as POST /v1/processors and /v1/acquiring-banks (v3.9.2 §0).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | The name as the operator types it. Trimmed BEFORE validation (1 to 64 characters after the trim); then inner whitespace is collapsed to single spaces and the result UPPERCASED for storage - "stellar tide llc" is stored as STELLAR TIDE LLC and is the same row as "Stellar Tide LLC". The length check runs on the trimmed value only, so a 66-character name padded with double spaces is a 400 even though it would collapse under 64. |
| `aliases` | string[]; default `[]` | no | Optional alternate tokens (up to 50, each up to 64 chars). Normalised like the name; empties, duplicates and the name itself are dropped. Ignored when the name resolves to an existing row (its aliases are NOT extended). An alias another row already answers to is refused with 409. |

**Request body**

```json
{
  "name": "ty urban peak llc",
  "aliases": [
    "ty urban peak"
  ]
}
```

**Response**

```json
{
  "row": {
    "id": "a3f1d8c5-2e6b-4a97-b0d4-9c7e5f2a1b63",
    "name": "TY URBAN PEAK LLC",
    "aliases": [
      "TY URBAN PEAK"
    ],
    "active": true,
    "source": "manual",
    "gateway_count": 0,
    "wallet_count": 0
  },
  "existing": false
}
```

| response field | type | description |
|---|---|---|
| `row` | object | The company - the new row (201) or the existing one the name resolved to (200). |
| `row.id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.company_id) and a wallet provider stores (wallet_providers.company_id). |
| `row.name` | string | Canonical name, stored UPPERCASE as the Airtable MID sheet spells the legal entity ("STELLAR TIDE LLC", "GAPO ECOM SCALE LLC", "JM GRATEFUL LLC"). Unique case-insensitively (unique index on lower(name)). |
| `row.aliases` | string[] | Alternate tokens the name is known by - the "LLC"-less spelling the wallet-provider names carry in parentheses ("GAPO", "HEUR DIGIMEDIA", "BRYBAA AD"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `row.active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `row.source` | string | `airtable` (migration 147: the 11 companies of the Airtable MID sheet's Company column) or `manual` (created through POST - Add unlisted). `seed` is the column default and unused for companies. |
| `row.gateway_count` | integer | Number of nmi_accounts rows referencing this entry - every account's, not just the caller's (the list is global). A JSON number (cast ::int). |
| `row.wallet_count` | integer | Number of wallet_providers rows referencing this entry, platform-wide. A JSON number. |
| `existing` | boolean | false = created now (status 201). true = the name already was a name or an alias, this is that row (status 200) and nothing was written. |

**Errors**

- `400` Zod validation failed: `name` missing, not a string, blank once trimmed, or longer than 64 characters; `aliases` not an array of strings, more than 50 of them, or one longer than 64. Body is `{ "error": "Invalid", "details": <zod flatten()> }`.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"} when the key's scopes lack routing.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (gate, then the handler's own check).
- `409` Two cases. (a) One of the `aliases` already belongs to another row (as its name or one of its aliases): `{ "error": "\"GAPO\" is already used by GAPO ECOM SCALE LLC" }`. (b) The name resolves to a DEACTIVATED row (active=false): `{ "error": "\"FELHAM MARKETING LLC\" is deactivated" }` - deactivation is a super_admin control, so "Add unlisted" never hands the row back; a super_admin restores it with PATCH { "active": true } first. An ACTIVE taken name never 409s - it returns that row with 200. A unique-index race (23505, two callers adding the same name at once) is resolved the same way: the winner comes back as `existing: true`.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Two success codes: 201 when created, 200 when deduped. Read `existing` rather than the status if you need to know which - both carry the full row.
- GLOBAL side effect: a row added here is visible to every account on the platform (the list is not per tenant). This is why a member with role user cannot grow the list, and why rename, deactivate and delete are kept for the platform operator.
- Dedupe matches aliases too: POST { "name": "gapo" } returns GAPO ECOM SCALE LLC (existing: true) because the token is one of its aliases. Send the canonical name or any alias - you get the same id.
- The stored name is the NORMALISED value (trim, single spaces, UPPERCASE), so `row.name` may differ from what you sent. Do not compare it to your input; use `row.id`.
- An API key can add entries (it acts as role admin of its account); a key without routing.write cannot.
- Every successful call is written to the admin action log (objectType `company`, page Gateways, objectName = the body `name`), including the 200 dedupe answers - the hook logs any 2xx mutation.
- Not idempotent in the REST sense but safe to retry: a repeated POST of the same name is a 200 dedupe, never a duplicate.

##### `POST /v1/convesio/s2s-test`

**Scope** `charges.write` - **Test a ConvesioPay S2S charge**

Test harness: fire ONE real server-to-server card charge at ConvesioPay with the integration id and secret given in the body, and return the normalised verdict plus the redacted request sent and the provider response. Nothing is persisted (no order, transaction, attempt or re-check).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `integration` | string (min 1) | **yes** | ConvesioPay integration id. |
| `secret` | string (min 1) | **yes** | ConvesioPay S2S secret key; sent to the provider, never echoed. |
| `amount` | number (> 0, major units) | **yes** | Amount in MAJOR units (9.99); a numeric string is accepted. Below 0.50 the adapter declines locally without calling the provider. |
| `currency` | string (3..8); default `USD` | no | Currency code, forwarded as is. |
| `orderId` | string (1..128); default `s2s-test-<epoch ms>` | no | Sent as the provider orderNumber. Not an idempotency key. |
| `bankPage` | string (max 256) | no | MID storefront metadata; does not change the return URL. |
| `ccnumber` | string (12..25) | **yes** | Card number (no Luhn check). Masked in requestSent. |
| `ccexp` | string (exactly 4, MMYY) | **yes** | Expiry MMYY. Non-digits are stripped before splitting, so a separator yields a wrong expiry. |
| `cvv` | string (3..4) | no | Security code; [REDACTED] in requestSent. |
| `firstName` | string (max 128) | no | With lastName forms holderName and name; both absent sends "Cardholder". |
| `lastName` | string (max 128) | no | See firstName. |
| `email` | string (max 256) | no | Forwarded as is (no format check). |
| `address1` | string (max 256) | no | Billing line, split into house number and street. The address block (billing = shipping) is sent only when address1, city or zip is present. |
| `city` | string (max 128) | no | Billing city. |
| `state` | string (max 64) | no | Billing state; dropped when address1, city and zip are all empty. |
| `zip` | string (max 32) | no | Billing postal code. |
| `country` | string (max 8) | no | Billing country; US when omitted in the address block. |
| `ipaddress` | string (max 64) | no | Customer IP, sent when present. |
| `phone` | string (max 40) | no | Digits only are kept; always sent with country code +1. |
| `useragent` | string (max 1024) | no | Sent as browserInfo.userAgent when present. |

**Request body**

```json
{
  "integration": "int_test_example",
  "secret": "sk_test_example",
  "amount": 9.99,
  "currency": "USD",
  "orderId": "qa-check-001",
  "ccnumber": "4111111111111111",
  "ccexp": "1230",
  "cvv": "123",
  "firstName": "Jane",
  "lastName": "Doe",
  "email": "jane.doe@example.com",
  "address1": "123 Main St",
  "city": "Austin",
  "state": "TX",
  "zip": "78701",
  "country": "US"
}
```

**Response**

```json
{
  "outcome": "approved",
  "approved": true,
  "cascade": false,
  "responseCode": "succeeded",
  "responseText": "succeeded",
  "transactionIdSupplier": "pay_example_01",
  "declineReason": null,
  "requestSent": {
    "endpoint": "https://s2s.example.com/v1/payments/direct",
    "integration": "int_test_example",
    "paymentMethod": {
      "number": "411111******1111",
      "cvc": "[REDACTED]",
      "holderName": "Jane Doe",
      "expiryMonth": "12",
      "expiryYear": "30"
    },
    "orderNumber": "qa-check-001",
    "amount": 999,
    "currency": "USD"
  },
  "responseRaw": {
    "http_status": "200",
    "id": "pay_example_01",
    "status": "Succeeded",
    "currency": "USD"
  }
}
```

| response field | type | description |
|---|---|---|
| `outcome` | string (approved\|declined\|timeout) | approved only for a captured status (succeeded, captured, settled) with a payment id; declined for a refusal (or the local under-0.50 guard); timeout for a network failure, a timeout, a non-2xx answer, a pending status or a customer action required (outcome unconfirmed). |
| `approved` | boolean | outcome is approved. HTTP is 200 for every outcome. |
| `cascade` | boolean | Whether production routing would try another MID (informational). |
| `responseCode / responseText / declineReason` | string \| null | Provider status or HTTP code, text, and refusal reason. |
| `transactionIdSupplier` | string \| null | ConvesioPay payment id. |
| `requestSent` | object | The body posted (card masked, cvc and 3DS values removed) plus endpoint, _basket and a credential fingerprint. Amounts here are minor units. |
| `responseRaw` | object \| null | Flattened string values of the provider answer (http_status, id, status, reason, refusal fields, currency, card brand and last four, action fields) or a body_format note. |

**Errors**

- `400` Invalid request (details: zod flatten).
- `401` Missing API key; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the key owner account has no paid or granted platform subscription.
- `403` Banned (the key owner is banned); or API key scope denied (code insufficient_scope).
- `500` Internal Server Error with requestId: an unexpected adapter failure; the charge may or may not have reached the provider.
- `503` Service temporarily unavailable (the key lookup failed; nothing was charged).

**Gotchas**

- A REAL charge on the provider endpoint: use sandbox credentials and test cards. An approved test charge is never reconciled or refunded automatically.
- No idempotency: the same body sent twice charges twice.
- amount is major units in the request, minor units in requestSent.
- A timeout outcome is ambiguous: the payment may exist at the provider. Do not retry blindly.

##### `GET /v1/processors`

**Scope** `routing.read` - **List processors**

Returns the GLOBAL reference list of processors - the PROCESSOR (the ISO / PSP that boards the MID) - that every gateway's "Processor" select field draws from (v3.9 §0, migration 138). Ordered by name, active rows only unless ?includeInactive=1, each with how many gateways (nmi_accounts) and wallet providers point at it. Read-only; nothing changes.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `includeInactive` | string | no | `1` or `true` also returns rows a super_admin deactivated (active = false). Anything else, or absent, = active rows only. |

**Response**

```json
{
  "rows": [
    {
      "id": "2b1f7e0c-6d3a-4c9e-9a41-8f0d5c7e2a10",
      "name": "CONVESIO PAY",
      "aliases": [
        "CONVESIO",
        "CONVESIOPAY"
      ],
      "active": true,
      "source": "seed",
      "gateway_count": 12,
      "wallet_count": 21,
      "in_use": true
    },
    {
      "id": "7c4a2d91-1e5b-4f08-b6c3-2d9e8a4f1b55",
      "name": "PRIORITY",
      "aliases": [
        "PRIORITY PAYMENTS"
      ],
      "active": true,
      "source": "seed",
      "gateway_count": 14,
      "wallet_count": 0,
      "in_use": true
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Every processor the filter admits, ordered by name. Never null; an empty array only before migration 138 seeded the list. |
| `rows[].id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.processor_id / acquiring_bank_id) and a wallet provider stores (wallet_providers, same two columns). |
| `rows[].name` | string | Canonical name, stored UPPERCASE as the operator's list spells it ("PRIORITY", "COASTAL PAY", "FFB BANK"). Unique case-insensitively (unique index on lower(name)). |
| `rows[].aliases` | string[] | Alternate tokens the name is known by ("CONVESIOPAY", "MV", "FFB"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `rows[].active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `rows[].source` | string | `seed` (migration 138, the operator's list), `airtable` (an acquirer only the Airtable MID sheet named) or `manual` (created through POST - Add unlisted). |
| `rows[].gateway_count` | number | v3.9.9 - the caller's ACCOUNT's MIDs referencing the row (the table is global). |
| `rows[].wallet_count` | number | v3.9.9 - the caller's account's wallet providers referencing the row. |
| `rows[].in_use` | boolean | v3.9.9 - whether ANY gateway / wallet provider (any account) references the row: the delete guard's question (DELETE answers in_use). |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund, {"error":"No access - ask an admin to grant you a role"} for a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- The list is global, not per account: every account sees the same processor rows. gateway_count and wallet_count count only the caller's account's gateways and wallet providers; in_use says whether any account references the row (what DELETE checks).
- Names and aliases are UPPERCASE by construction; match them case-insensitively anyway when you resolve a token (the API does: name OR alias, lower() on both sides).
- This is the ONLY way to obtain the id a gateway field takes - POST/PATCH /v1/accounts and the wallet-provider routes take it as `processorId` (uuid, camelCase - the body key, not the processor_id column) from this list, never a free-text name. Their schemas strip unknown keys, so a snake_case `processor_id` is silently ignored and the field stays null.
- No pagination, search or sort parameters: the whole list (a few dozen rows) comes back on every call. Filter client-side.
- A deactivated row stays referenced by the gateways that already chose it - deactivation hides it from pickers, it does not detach anything. Use DELETE (only when nothing references it) to remove one.
- Ordering is `order by r.name asc` under the database collation; with all-uppercase names that is plain alphabetical.

##### `POST /v1/processors`

**Scope** `routing.write` - **Add an unlisted processor**

"Add unlisted" from the Processor picker: creates a processor that is not in the list yet, stamped source `manual` and created_by = the caller. DEDUPES instead of refusing: when the name (trimmed, uppercased) already is the name OR an alias of an existing row, case-insensitively, that row comes back with 200 and `existing: true` - no duplicate, no 409. A brand-new row answers 201 with `existing: false`.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | The name as the operator types it. Trimmed BEFORE validation (1 to 64 characters after the trim); then inner whitespace is collapsed to single spaces and the result UPPERCASED for storage - "convesio pay" is stored as CONVESIO PAY and is the same row as "Convesio Pay". The length check runs on the trimmed value only, so a 66-character name padded with double spaces is a 400 even though it would collapse under 64. |
| `aliases` | string[]; default `[]` | no | Optional alternate tokens (up to 50, each up to 64 chars). Normalised like the name; empties, duplicates and the name itself are dropped. Ignored when the name resolves to an existing row (its aliases are NOT extended). An alias another row already answers to is refused with 409. |

**Request body**

```json
{
  "name": "new processor",
  "aliases": [
    "newproc"
  ]
}
```

**Response**

```json
{
  "row": {
    "id": "e9d3b6a2-5f71-4c28-8b0e-3a6d9c1f7e44",
    "name": "NEW PROCESSOR",
    "aliases": [
      "NEWPROC"
    ],
    "active": true,
    "source": "manual",
    "gateway_count": 0,
    "wallet_count": 0
  },
  "existing": false
}
```

| response field | type | description |
|---|---|---|
| `row` | object | The processor - the new row (201) or the existing one the name resolved to (200). |
| `row.id` | uuid | Primary key. This is the value a gateway stores (nmi_accounts.processor_id / acquiring_bank_id) and a wallet provider stores (wallet_providers, same two columns). |
| `row.name` | string | Canonical name, stored UPPERCASE as the operator's list spells it ("PRIORITY", "COASTAL PAY", "FFB BANK"). Unique case-insensitively (unique index on lower(name)). |
| `row.aliases` | string[] | Alternate tokens the name is known by ("CONVESIOPAY", "MV", "FFB"), UPPERCASE. Lookups (Add unlisted dedupe, rename collisions) match name OR alias case-insensitively. Empty array when none. |
| `row.active` | boolean | false = deactivated by the platform operator: hidden from the pickers and from the default list, but gateways already pointing at it keep their reference. |
| `row.source` | string | `seed` (migration 138, the operator's list), `airtable` (an acquirer only the Airtable MID sheet named) or `manual` (created through POST - Add unlisted). |
| `row.gateway_count` | integer | Number of nmi_accounts rows referencing this entry - every account's, not just the caller's (the list is global). A JSON number (cast ::int). |
| `row.wallet_count` | integer | Number of wallet_providers rows referencing this entry, platform-wide. A JSON number. |
| `existing` | boolean | false = created now (status 201). true = the name already was a name or an alias, this is that row (status 200) and nothing was written. |

**Errors**

- `400` Zod validation failed: `name` missing, not a string, blank once trimmed, or longer than 64 characters; `aliases` not an array of strings, more than 50 of them, or one longer than 64. Body is `{ "error": "Invalid", "details": <zod flatten()> }`.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"} when the key's scopes lack routing.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin (gate, then the handler's own check).
- `409` Two cases. (a) One of the `aliases` already belongs to another row (as its name or one of its aliases): `{ "error": "\"PPS\" is already used by PPS" }`. (b) The name resolves to a DEACTIVATED row (active=false): `{ "error": "\"NUVEI\" is deactivated" }` - deactivation is a super_admin control, so "Add unlisted" never hands the row back; a super_admin restores it with PATCH { "active": true } first. An ACTIVE taken name never 409s - it returns that row with 200. A unique-index race (23505, two callers adding the same name at once) is resolved the same way: the winner comes back as `existing: true`.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database/connection failure. Logged to the error log with the request id.
- `504` Postgres statement timeout (SQLSTATE 57014) mapped by the global error handler.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Two success codes: 201 when created, 200 when deduped. Read `existing` rather than the status if you need to know which - both carry the full row.
- GLOBAL side effect: a row added here is visible to every account on the platform (the list is not per tenant). This is why a member with role user cannot grow the list, and why rename, deactivate and delete are kept for the platform operator.
- Dedupe matches aliases too: POST { "name": "convesiopay" } returns CONVESIO PAY (existing: true) because the token is one of its aliases. Send the canonical name or any alias - you get the same id.
- The stored name is the NORMALISED value (trim, single spaces, UPPERCASE), so `row.name` may differ from what you sent. Do not compare it to your input; use `row.id`.
- An API key can add entries (it acts as role admin of its account); a key without routing.write cannot.
- Every successful call is written to the admin action log (objectType `processor`, page Gateways, objectName = the body `name`), including the 200 dedupe answers - the hook logs any 2xx mutation.
- Not idempotent in the REST sense but safe to retry: a repeated POST of the same name is a 200 dedupe, never a duplicate.

##### `GET /v1/stripe/options`

**Scope** `charges.read` - **List available Stripe checkout modes**

For one store (and optionally one cart), which Stripe presentations (s2s, embedded, hosted) its card route offers and whether a native card form can be shown. Used by a checkout before rendering card entry. Returns no keys.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store (checkout shop) id. |
| `cartToken` | string (max 4096) | no | Cart routing token, when routing depends on the cart. |

**Response**

```json
{
  "modes": [
    "s2s",
    "hosted"
  ],
  "cardAvailable": true
}
```

| response field | type | description |
|---|---|---|
| `modes` | string[] | Stripe presentations of the active Stripe gateways in the resolved ATRI: s2s, embedded, hosted. |
| `cardAvailable` | boolean | A native card form can be used (an NMI or Convesio gateway, or Stripe s2s, is active in the resolved ATRI). |

**Errors**

- `400` Invalid checkout (shopId not a uuid, or cartToken longer than 4096).
- `401` Invalid API key (missing or unknown key).
- `402` A paid platform subscription is required (code subscription_required): the key owner account has no paid or granted platform subscription.
- `403` Access denied (key owner banned, or the key lacks the charges read scope).
- `429` Too Many Requests (120 per minute per IP).

**Gotchas**

- An inactive or foreign store, or a store whose card method is disabled, answers {"modes":[],"cardAvailable":false} with 200.
- Never cached (Cache-Control: no-store).

##### `GET /v1/v5/flow-payment-capabilities`

**Scope** `routing.read` - **List post-purchase payment readiness**

Lists the account's MIDs with their support for original-card customer-initiated post-sell payments and fresh buyer authentication. It does not check a particular card, the provider configuration or a live bank approval.

*No parameters.*

**Response** `200`

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "label": "Main MID",
      "provider": "nmi",
      "activated": true,
      "enabled": false,
      "confirmedAt": null,
      "supported": true,
      "readiness": "configured",
      "method": "cit",
      "challengeSupported": true
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].id / label / provider` | string | MID UUID, its name and its gateway type (nmi when unset). |
| `rows[].activated` | boolean | The MID's own activation flag. |
| `rows[].supported` | boolean | True for providers with a registered card adapter (nmi, convesio, stripe). |
| `rows[].readiness` | string | configured, inactive_mid or unsupported_provider. configured describes the available implementation, not a guaranteed approval. |
| `rows[].method` | string \| null | cit (new customer-initiated sale) for supported providers, null otherwise. |
| `rows[].challengeSupported` | boolean | True when the adapter supports fresh buyer authentication for post-sells. |
| `rows[].enabled / confirmedAt` | boolean / string \| null | Historical Customer Vault opt-in fields: enabled is always false; confirmedAt is when the flag was last revoked, or null. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Post-sell pages follow the confirmed initial payment whatever the method (card, wallet or wire). This endpoint reports card adapter readiness per MID, not page eligibility. Payment admission still checks the exact captured source, owner, session and original MID; it never selects another ATRI or MID.
- New original-card upsells use a customer-initiated sale on the exact original stored card and MID (for NMI: type=sale, initiated_by=customer). No Customer Vault, reference sale, initial_transaction_id chain, old 3DS proof or original checkout CVV is replayed.
- Card offers authorized at the post-sell need price-bound buyer acceptance and a fresh security code entered by the buyer for that basket, held in request memory only. Wallet and wire use their own native confirmation.
- Readiness and fixtures do not certify a live processor or guarantee bank approval.

##### `PUT /v1/v5/flow-payment-capabilities/:midId`

**Scope** `routing.write` - **Revoke a historical Vault opt-in**

Compatibility endpoint that clears the historical Customer Vault flag of one MID. Enabling it is refused (409): new post-sell payments use a customer-initiated sale and never depend on this flag.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `midId` | uuid | **yes** | UUID of a MID of this account (rows[].id of GET /v1/v5/flow-payment-capabilities). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | **yes** | Must be false; true answers 409. |
| `confirmed` | boolean | no | Accepted and ignored. |

**Request body**

```json
{
  "enabled": false
}
```

**Response** `200`

```json
{
  "midId": "00000000-0000-4000-8000-000000000001",
  "enabled": false,
  "provider": "nmi"
}
```

| response field | type | description |
|---|---|---|
| `midId` | uuid | The MID updated. |
| `enabled` | boolean | Always false. |
| `provider` | string | Gateway type of the MID (nmi when unset). |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: midId is not a UUID, enabled is missing, or an unknown key was sent.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `404` {"error":"MID not found."}: the MID is unknown or belongs to another account.
- `409` {"error":"Post-purchase payments use a new customer-initiated sale. Customer Vault is not used."}: enabled was true.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Disabling the historical flag does not change original-card post-sell readiness, which never used it.
- Already dispatched historical payments stay reconcilable read-only; nothing is retried.

#### Wallet providers

The Apple Pay and Google Pay gateways (wallet MIDs): create, provision, verify domains and run the background setup.

- Totals of the list, computed in the browser from `GET /v1/wallet-providers`: charges over 30 days = sum of the rows; pooled approval rate = sum(approved) / sum(completed); Apple Pay approval rate the same on the Apple Pay counts.
- Exports are built in the browser from the list.

##### `GET /v1/wallet-providers`

**Scope** `routing.read` - **List wallet gateways (Apple Pay / Google Pay MIDs)**

Lists the account's wallet gateways (Apple Pay / Google Pay MIDs); card gateways are listed by GET /v1/accounts. Returns every wallet (Apple Pay / Google Pay) provider MID owned by the caller's account, each with its full config row plus a 30-day performance rollup. Encrypted credentials are replaced by has_secret / has_webhook_secret booleans.

*No parameters.*

**Response**

```json
{
  "providers": [
    {
      "id": "9f1c2e88-4b3a-4d21-9c7e-1a2b3c4d5e6f",
      "name": "Wallet - shop.example.com",
      "environment": "production",
      "integration_id": "fbm-wallet-example-com-production",
      "api_key": "pk_live_EXAMPLE",
      "client_key": "ck_live_EXAMPLE",
      "registered_domain": "wallet.example.com",
      "apple_cert": "7B227073705F6964223A2231...",
      "google_pay_merchant_id": null,
      "apple_pay_enabled": true,
      "google_pay_enabled": false,
      "is_active": true,
      "sort_order": 0,
      "debug_log_enabled": false,
      "render_domain_id": "cdm-d1abc2de3fg4h5i6j7k0",
      "dns_record_type": "CNAME",
      "dns_record_target": "cocoapi.onrender.com",
      "domain_verification_status": "verified",
      "domain_verified_at": "2026-08-12T09:41:22.104Z",
      "legacy_provider_id": null,
      "created_at": "2026-07-30T14:02:11.880Z",
      "updated_at": "2026-08-12T09:41:22.104Z",
      "discount_fee_bps": 295,
      "transaction_fee_cents": 30,
      "reserve_rate_bps": 1000,
      "mc_refund_fee_cents": 50,
      "visa_refund_fee_cents": 50,
      "processor_id": "a0f1e2d3-c4b5-4a69-8778-695a4b3c2d1e",
      "processor_name": "CONVESIO PAY",
      "acquiring_bank_id": "e1d2c3b4-a596-4877-8a9b-0c1d2e3f4a5b",
      "acquiring_bank_name": "ADYEN",
      "company_id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
      "company_name": "STELLAR TIDE LLC",
      "has_secret": true,
      "has_webhook_secret": false,
      "attempts_30d": 1842,
      "approved_30d": 1391,
      "apple_attempts_30d": 1102,
      "apple_approved_30d": 868,
      "perf": {
        "attempts_30d": 1842,
        "approved_30d": 1391,
        "apple_attempts_30d": 1102,
        "apple_approved_30d": 868
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `providers` | object[] | All MIDs owned by the caller's account, ordered by sort_order asc then name asc. No pagination, no filters - you always get the whole set. |
| `providers[].id` | uuid | MID id, used as :id on every other route in this file. |
| `providers[].integration_id` | string | The ConvesioPay integration name (e.g. fbm-wallet-example-com-production). This is what legacy /v1/convesio charges are attributed by. |
| `providers[].api_key` | string\|null | ConvesioPay publishable API key, stored UNENCRYPTED and returned here in plaintext. Despite the file's 'secrets never leave' comment, api_key and client_key ARE in the response - only secret_key and webhook_secret are withheld. |
| `providers[].client_key` | string\|null | ConvesioPay client key, also returned in plaintext. |
| `providers[].has_secret` | boolean | true when secret_key_enc is non-null. The secret itself is not in the list - GET /v1/wallet-providers/:id/credentials (v3.9.8 item 7). |
| `providers[].has_webhook_secret` | boolean | true when webhook_secret_enc is non-null. |
| `providers[].apple_cert` | string\|null | Raw body served at /.well-known/apple-developer-merchantid-domain-association on the registered wallet host. Returned in full (can be ~20 KB). |
| `providers[].discount_fee_bps` | integer | Discount rate in BASIS POINTS (0..10000), not a 0..1 ratio. 295 = 2.95%. |
| `providers[].reserve_rate_bps` | integer | Reserve rate in BASIS POINTS (0..10000), not a 0..1 ratio. 1000 = 10%. |
| `providers[].transaction_fee_cents` | integer | Flat per-transaction fee in integer CENTS. |
| `providers[].mc_refund_fee_cents` | integer | Mastercard refund fee in integer CENTS. |
| `providers[].visa_refund_fee_cents` | integer | Visa refund fee in integer CENTS. |
| `providers[].processor_id` | string (uuid) \| null | v3.9 section 0 - the PROCESSOR behind the wallet MID (processors.id). null when unset. |
| `providers[].processor_name` | string \| null | Display name of that processor ("CONVESIO PAY"); null when processor_id is null. Resolved by a scalar sub-select, so a wallet with none set still lists. |
| `providers[].acquiring_bank_id` | string (uuid) \| null | v3.9 section 0 - the ACQUIRING BANK / service behind the wallet MID (acquiring_banks.id). null when unset. |
| `providers[].acquiring_bank_name` | string \| null | Display name of that acquiring bank ("ADYEN", "STRIPE"); null when acquiring_bank_id is null. |
| `providers[].company_id` | string (uuid) \| null | v3.9.2 section 0 - the COMPANY behind the wallet MID (companies.id): the legal entity it is boarded under. null when unset. |
| `providers[].company_name` | string \| null | Display name of that company ("MASTU DIGITAL LLC", "GAPO ECOM SCALE LLC"); null when company_id is null. Resolved by a scalar sub-select, so a wallet with none set still lists. |
| `providers[].domain_verification_status` | string\|null | Render custom-domain state, passed through verbatim: 'unverified' \| 'verified' \| 'render_error' (the last is set locally by this API when the Render call throws, it is NOT a Render value). |
| `providers[].perf` | object | 30-day counters: attempts_30d / approved_30d / apple_attempts_30d / apple_approved_30d. v3.9 section 1: attempts count the LIVE transactions (no test card, no CSV import, no 3DS park) whose status is approved, declined, error or unknown in the last 30 days - the approval rate's base, so approved_30d / attempts_30d is THE rate. |
| `providers[].attempts_30d` | integer | Same value as perf.attempts_30d - the four counters are duplicated at the top level AND inside perf. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Unhandled DB error (the route has no try/catch).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The owner_email comparison here is an exact, case-SENSITIVE match ('where p.owner_email = $1'), while ownedWalletProviderIds() lowercases. A MID stored with mixed-case owner_email can be invisible to its own owner on this route.
- owner_email itself is NOT in the response - you cannot tell from the payload who owns a MID.
- Inactive MIDs (is_active=false) are included; there is no filter parameter of any kind.
- The four *_30d counters appear twice: once flat on the row and once under perf. They are the same numbers, not two different windows.

##### `POST /v1/wallet-providers`

**Scope** `routing.write` - **Create wallet MID**

Creates a wallet provider MID from operator-supplied ConvesioPay credentials, optionally replaces its shop links, and - when registeredDomain is set and Render is configured - best-effort creates the Render custom domain and stores the DNS record the operator must add.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Display name, 1..256 chars. |
| `integrationId` | string | **yes** | ConvesioPay integration name, 1..512 chars. Stored in integration_id and used to attribute legacy /v1/convesio charges. |
| `environment` | enum: sandbox\|production; default `production` | no | Default applied in the DB layer, not by zod - omit and you get 'production'. |
| `apiKey` | string\|null; default `null` | no | ConvesioPay publishable key, max 256. Stored UNENCRYPTED and echoed back by the GET routes. |
| `clientKey` | string\|null; default `null` | no | ConvesioPay client key, max 256. Stored UNENCRYPTED. |
| `secretKey` | string\|null; default `null` | no | ConvesioPay secret key, max 512. Encrypted at rest; the reads carry has_secret, GET /v1/wallet-providers/:id/credentials the value (v3.9.8 item 7). |
| `webhookSecret` | string\|null; default `null` | no | Max 512. Encrypted at rest; the reads carry has_webhook_secret, GET /v1/wallet-providers/:id/credentials the value (v3.9.8 item 7). |
| `registeredDomain` | string\|null; default `null` | no | The wallet host, max 256. Stored VERBATIM in the DB (scheme/path NOT stripped), but the Render provisioning path strips https:// and any /path before creating the domain. |
| `appleCert` | string\|null; default `null` | no | Body served at /.well-known/apple-developer-merchantid-domain-association. Max 20000 chars. |
| `googlePayMerchantId` | string\|null; default `null` | no | Max 128. |
| `applePayEnabled` | boolean; default `false` | no | Capability flag read by the charge-time picker. |
| `googlePayEnabled` | boolean; default `false` | no | Capability flag read by the charge-time picker. |
| `isActive` | boolean; default `true` | no | Inactive MIDs are never picked for a charge but still serve their .well-known cert. |
| `sortOrder` | integer; default `0` | no | z.coerce.number().int() - a numeric STRING like "3" is accepted and coerced. Controls list ordering only. |
| `debugLogEnabled` | boolean; default `false` | no | Verbose charge logging for this MID. |
| `ownerEmail` | string\|null; default `null` | no | ACCEPTED BY THE SCHEMA BUT IGNORED on create - the route overwrites it with the caller's own account email before insert. You cannot create a MID for another account. |
| `discountFeeBps` | integer | no | 0..10000 basis points. ACCEPTED BY THE SCHEMA BUT NEVER PERSISTED on create - createWalletProvider's INSERT does not include the fee columns. Set fees with a follow-up PATCH. |
| `transactionFeeCents` | integer | no | Integer cents, >= 0. Same trap: accepted on create, silently dropped. Use PATCH. |
| `reserveRateBps` | integer | no | 0..10000 basis points. Accepted on create, silently dropped. Use PATCH. |
| `mcRefundFeeCents` | integer | no | Integer cents, >= 0. Accepted on create, silently dropped. Use PATCH. |
| `visaRefundFeeCents` | integer | no | Integer cents, >= 0. Accepted on create, silently dropped. Use PATCH. |
| `processorId` | string (uuid) \| null; default `null` | no | v3.9 section 0 - id of the PROCESSOR behind the wallet MID (a `processors` row - the same reference table gateways use, so no breakdown special-cases a wallet). Never free text: an unknown id is 400 `{"error":"Unknown processor"}`. Applied on create (unlike the fee fields). Omitted = null. -> column wallet_providers.processor_id. |
| `acquiringBankId` | string (uuid) \| null; default `null` | no | v3.9 section 0 - id of the ACQUIRING BANK / service behind the wallet MID (an `acquiring_banks` row). Unknown id -> 400 `{"error":"Unknown acquiring bank"}`. Applied on create (unlike the fee fields). Omitted = null. -> column wallet_providers.acquiring_bank_id. |
| `companyId` | string (uuid) \| null; default `null` | no | v3.9.2 section 0 - id of the COMPANY behind the wallet MID (a `companies` row - the same reference table gateways use, so no breakdown special-cases a wallet). Never free text: an unknown id is 400 `{"error":"Unknown company"}`. Applied on create (unlike the fee fields). Omitted = null. -> column wallet_providers.company_id. |
| `shops` | object[] | no | Array of {shop_id (uuid, required), shop_name (string<=256, nullable), shop_domain (string<=256, nullable)}. Written wholesale via setProviderShops. |

**Request body**

```json
{
  "name": "Wallet - shop.example.com",
  "environment": "production",
  "integrationId": "fbm-wallet-example-com-production",
  "apiKey": "pk_live_EXAMPLE",
  "clientKey": "ck_live_EXAMPLE",
  "secretKey": "sk_live_EXAMPLE",
  "webhookSecret": "whsec_Q1w2E3r4T5y6",
  "registeredDomain": "wallet.example.com",
  "appleCert": "7B227073705F6964223A2231...",
  "applePayEnabled": true,
  "googlePayEnabled": false,
  "isActive": true,
  "sortOrder": 0,
  "shops": [
    {
      "shop_id": "1b6d0a44-2f7c-4c19-8a55-9e0d7c3b1f22",
      "shop_name": "Example Store",
      "shop_domain": "shop.example.com"
    }
  ]
}
```

**Response**

```json
{
  "id": "9f1c2e88-4b3a-4d21-9c7e-1a2b3c4d5e6f",
  "dns": {
    "type": "CNAME",
    "name": "wallet.example.com",
    "target": "cocoapi.onrender.com"
  },
  "renderError": null
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | The new MID id. HTTP 201. |
| `dns` | object\|null | The DNS record the operator must add at the registrar. null when registeredDomain was omitted OR RENDER_API_KEY/RENDER_SERVICE_ID are unset - in that case no Render domain was attempted at all. |
| `dns.type` | enum: CNAME\|A | Computed locally, not returned by Render: >=3 labels (a subdomain) -> CNAME to RENDER_SERVICE_HOSTNAME; 2 labels (apex) -> A to RENDER_APEX_IP (default 216.24.57.1). |
| `dns.name` | string | The normalised host (scheme and path stripped). |
| `dns.target` | string | CNAME target hostname or apex IP. |
| `renderError` | string\|null | Non-null when the Render custom-domain call failed. The MID was STILL created and the response is STILL 201. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} - schema validation failed (missing name/integrationId, string too long, bad email, non-uuid shop_id, out-of-range bps, etc.). {"error":"Unknown processor"} / {"error":"Unknown acquiring bank"} / {"error":"Unknown company"} - processorId / acquiringBankId / companyId is a well-formed uuid but not a row of the reference table (FK wallet_providers_processor_id_fkey / wallet_providers_acquiring_bank_id_fkey / wallet_providers_company_id_fkey). v3.9 section 0.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` DB insert failed (e.g. a unique-index violation) or setProviderShops threw.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The five fee fields (discountFeeBps, transactionFeeCents, reserveRateBps, mcRefundFeeCents, visaRefundFeeCents) pass validation and are then THROWN AWAY - createWalletProvider's INSERT column list omits them. A MID created here always starts at the DB defaults. You must PATCH immediately after to set fees, or every wallet sale books at the wrong margin.
- ownerEmail in the body is overwritten with the caller's account email. There is no way to create a MID for someone else.
- A Render failure does NOT fail the request: you get 201 with renderError set and the MID is left with domain_verification_status='render_error'. Always check renderError, not just the status code.
- If registeredDomain is omitted, or Render is not configured, dns is null and NO domain is provisioned - the MID can never verify until you call POST /v1/wallet-providers/:id/create-domain.
- registeredDomain is stored EXACTLY as sent (https:// and trailing paths are NOT stripped in the DB), but the Render/DNS path normalises it. Send a bare host or the stored value and the provisioned domain will disagree, and the wallet-host lookup (exact match on registered_domain) will miss.
- shops replaces the link set wholesale: setProviderShops DELETEs all rows for the provider first. Sending "shops": [] is truthy in JS and therefore wipes every link.
- Shop links are decorative for routing - pickWalletProvider ignores them entirely and picks a random active, capability-enabled, domain-having MID.
- secretKey/webhookSecret cannot be cleared through the API once set; v3.9.8 item 7 - they are read back in clear through GET /v1/wallet-providers/:id/credentials by a caller that may edit the provider (audited).

##### `GET /v1/wallet-providers/:id`

**Scope** `routing.read` - **Get wallet MID**

Returns one wallet MID (same shape as a list row, minus the 30-day perf rollup) plus its linked shops. Only resolves if the MID is owned by the caller's account.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id. NOT validated by the route - it is passed straight into a uuid-typed SQL comparison. |

**Response**

```json
{
  "provider": {
    "id": "9f1c2e88-4b3a-4d21-9c7e-1a2b3c4d5e6f",
    "name": "Wallet - shop.example.com",
    "environment": "production",
    "integration_id": "fbm-wallet-example-com-production",
    "api_key": "pk_live_EXAMPLE",
    "client_key": "ck_live_EXAMPLE",
    "registered_domain": "wallet.example.com",
    "apple_cert": "7B227073705F6964223A2231...",
    "google_pay_merchant_id": null,
    "apple_pay_enabled": true,
    "google_pay_enabled": false,
    "is_active": true,
    "sort_order": 0,
    "debug_log_enabled": false,
    "render_domain_id": "cdm-d1abc2de3fg4h5i6j7k0",
    "dns_record_type": "CNAME",
    "dns_record_target": "cocoapi.onrender.com",
    "domain_verification_status": "verified",
    "domain_verified_at": "2026-08-12T09:41:22.104Z",
    "legacy_provider_id": null,
    "created_at": "2026-07-30T14:02:11.880Z",
    "updated_at": "2026-08-12T09:41:22.104Z",
    "discount_fee_bps": 295,
    "transaction_fee_cents": 30,
    "reserve_rate_bps": 1000,
    "mc_refund_fee_cents": 50,
    "visa_refund_fee_cents": 50,
    "processor_id": "a0f1e2d3-c4b5-4a69-8778-695a4b3c2d1e",
    "processor_name": "CONVESIO PAY",
    "acquiring_bank_id": "e1d2c3b4-a596-4877-8a9b-0c1d2e3f4a5b",
    "acquiring_bank_name": "ADYEN",
    "company_id": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
    "company_name": "STELLAR TIDE LLC",
    "has_secret": true,
    "has_webhook_secret": false
  },
  "shops": [
    {
      "shop_id": "1b6d0a44-2f7c-4c19-8a55-9e0d7c3b1f22",
      "shop_name": "Example Store",
      "shop_domain": "shop.example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `provider` | object | Same column set as a list row but WITHOUT attempts_30d/approved_30d/apple_* and without perf. |
| `provider.discount_fee_bps` | integer | Basis points (0..10000), not a 0..1 ratio. |
| `provider.reserve_rate_bps` | integer | Basis points (0..10000), not a 0..1 ratio. |
| `provider.transaction_fee_cents` | integer | Integer cents. |
| `provider.mc_refund_fee_cents` | integer | Integer cents. |
| `provider.visa_refund_fee_cents` | integer | Integer cents. |
| `provider.processor_id` | string (uuid) \| null | v3.9 section 0 - the PROCESSOR behind the wallet MID (processors.id). null when unset. |
| `provider.processor_name` | string \| null | Display name of that processor ("CONVESIO PAY"); null when processor_id is null. Resolved by a scalar sub-select, so a wallet with none set still lists. |
| `provider.acquiring_bank_id` | string (uuid) \| null | v3.9 section 0 - the ACQUIRING BANK / service behind the wallet MID (acquiring_banks.id). null when unset. |
| `provider.acquiring_bank_name` | string \| null | Display name of that acquiring bank ("ADYEN", "STRIPE"); null when acquiring_bank_id is null. |
| `provider.company_id` | string (uuid) \| null | v3.9.2 section 0 - the COMPANY behind the wallet MID (companies.id): the legal entity it is boarded under. null when unset. |
| `provider.company_name` | string \| null | Display name of that company ("MASTU DIGITAL LLC", "GAPO ECOM SCALE LLC"); null when company_id is null. Resolved by a scalar sub-select, so a wallet with none set still lists. |
| `shops` | object[] | Rows from wallet_provider_shops for this MID, ordered by shop_name. Empty array when none are linked. |
| `shops[].shop_id` | uuid | External shop identifier. |
| `shops[].shop_name` | string\|null | Free-text label. |
| `shops[].shop_domain` | string\|null | Free-text domain. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - the MID does not exist OR it exists but is owned by another account. The two are indistinguishable, by design.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- A malformed :id returns 400 "A value has an invalid format.", not 404 - the route never validates the uuid before hitting Postgres.
- The shops list is fetched WITHOUT an ownership filter, but the provider ownership check already gated it, so this is not a leak - it just means shops are always for the requested id.
- api_key and client_key come back in plaintext here too.
- v3.9.8 item 7 - has_secret / has_webhook_secret only; GET /v1/wallet-providers/:id/credentials returns the two secrets in clear to a caller that may edit the provider (audited).

##### `PATCH /v1/wallet-providers/:id`

**Scope** `routing.write` - **Update wallet MID**

Partially updates a wallet MID owned by the caller's account and/or replaces its shop links. This is the ONLY route that can write the fee schedule.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | 1..256 chars. Optional here (required on create) because the update schema is .partial(). |
| `environment` | enum: sandbox\|production | no | Column is only touched when the key is present. |
| `integrationId` | string | no | 1..512 chars. |
| `apiKey` | string\|null | no | Max 256. Explicit null CLEARS the column (unlike secretKey). |
| `clientKey` | string\|null | no | Max 256. Explicit null CLEARS the column. |
| `secretKey` | string\|null | no | Max 512. Written only when TRUTHY - null, omitted, or "" all mean 'keep the existing encrypted secret'. There is no way to clear it via this API. |
| `webhookSecret` | string\|null | no | Max 512. Same truthy-only rule as secretKey; cannot be cleared. |
| `registeredDomain` | string\|null | no | Max 256. Changing it does NOT re-provision the Render domain - call create-domain afterwards. |
| `appleCert` | string\|null | no | Max 20000. Explicit null clears it. |
| `googlePayMerchantId` | string\|null | no | Max 128. |
| `applePayEnabled` | boolean | no | Capability flag used by the charge-time picker. |
| `googlePayEnabled` | boolean | no | Local flag only - it does NOT push anything to ConvesioPay. |
| `isActive` | boolean | no | false removes the MID from charge selection but it still serves its .well-known cert. |
| `sortOrder` | integer | no | z.coerce.number().int() - numeric strings accepted. The dashboard form has no field for it: this route is the only way to change it. |
| `debugLogEnabled` | boolean | no | Verbose charge logging. |
| `ownerEmail` | string\|null | no | Accepted by the schema (a valid e-mail, max 200, or null) but IGNORED: ownership is never editable through this route; the provider stays with the account that created it. |
| `discountFeeBps` | integer | no | 0..10000 BASIS POINTS. Applied here (unlike on create). |
| `transactionFeeCents` | integer | no | Integer cents, >= 0. Applied here. |
| `reserveRateBps` | integer | no | 0..10000 BASIS POINTS. Applied here. |
| `mcRefundFeeCents` | integer | no | Integer cents, >= 0. Applied here. |
| `visaRefundFeeCents` | integer | no | Integer cents, >= 0. Applied here. |
| `processorId` | string (uuid) \| null | no | v3.9 section 0 - id of the PROCESSOR behind the wallet MID (a `processors` row - the same reference table gateways use, so no breakdown special-cases a wallet). Never free text: an unknown id is 400 `{"error":"Unknown processor"}`. Explicit null CLEARS the field; omitted leaves it unchanged. -> column wallet_providers.processor_id. |
| `acquiringBankId` | string (uuid) \| null | no | v3.9 section 0 - id of the ACQUIRING BANK / service behind the wallet MID (an `acquiring_banks` row). Unknown id -> 400 `{"error":"Unknown acquiring bank"}`. Explicit null CLEARS the field; omitted leaves it unchanged. -> column wallet_providers.acquiring_bank_id. |
| `companyId` | string (uuid) \| null | no | v3.9.2 section 0 - id of the COMPANY behind the wallet MID (a `companies` row - the same reference table gateways use, so no breakdown special-cases a wallet). Never free text: an unknown id is 400 `{"error":"Unknown company"}`. Explicit null CLEARS the field; omitted leaves it unchanged. -> column wallet_providers.company_id. |
| `shops` | object[] | no | Array of {shop_id (uuid, required), shop_name, shop_domain}. Replaces the entire link set. |

**Request body**

```json
{
  "discountFeeBps": 295,
  "transactionFeeCents": 30,
  "reserveRateBps": 1000,
  "mcRefundFeeCents": 50,
  "visaRefundFeeCents": 50,
  "applePayEnabled": true,
  "isActive": true
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. It does NOT tell you which columns changed, and it is returned even if the only thing that happened was replacing the shop links. |

**Errors**

- `400` Either {"error":"Invalid","details":<zod flatten()>} for a schema failure, OR {"error":"No fields to update"} when the body produced zero writable columns and no shops array. {"error":"Unknown processor"} / {"error":"Unknown acquiring bank"} / {"error":"Unknown company"} - processorId / acquiringBankId / companyId is a well-formed uuid but not a row of the reference table (FK wallet_providers_processor_id_fkey / wallet_providers_acquiring_bank_id_fkey / wallet_providers_company_id_fkey). v3.9 section 0. {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - the MID does not exist or is not owned by the caller's account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- PATCH is the ONLY place fees can be written. If you created the MID via POST or /bootstrap with fee fields in the body, they were dropped - you must PATCH them or the MID silently bills at the DB defaults.
- Sending {} passes validation (every field is optional) and then returns 400 'No fields to update'. Same for a body whose only field is an empty-string secretKey.
- secretKey / webhookSecret are written only when truthy. Sending null or "" is a deliberate 'keep existing' - it is NOT a clear, and no error is raised.
- ownerEmail is honoured here: a single PATCH can hand the MID to another account, after which the same caller gets 404 on it. There is no undo through this API.
- If shops is present the shop links are replaced even when the column update returns false, and the response is still {"ok":true} instead of the 400.
- Changing registeredDomain does not touch render_domain_id, dns_record_* or domain_verification_status - those keep pointing at the OLD host until you call create-domain.
- googlePayEnabled here only flips a local column. The Convesio side is only changed by POST /:id/enable-methods, which hardcodes googlePay:false.

##### `DELETE /v1/wallet-providers/:id`

**Scope** `routing.write` - **Delete wallet MID**

Permanently deletes a wallet MID owned by the caller's account, best-effort detaching its Render custom domain first so it is not left orphaned on the service.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Response** `204`

```json
HTTP 204 No Content (empty response body)
```

| response field | type | description |
|---|---|---|
| `(none)` | empty | 204 No Content with an empty body on success. Do not try to parse JSON. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - the MID does not exist or is not owned by the caller's account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- A MID with even one attributed transaction will fail with a 500 FK violation, not a clean 409. Deactivate with PATCH {"isActive": false} instead - that is the real 'retire a MID' operation.
- The Render domain is deleted FIRST and the error is swallowed (.catch(() => {})). If the FK violation then aborts the DB delete, you are left with a live MID row whose Render custom domain has already been removed - the wallet host stops serving TLS while the MID still looks healthy in the API.
- Deletion is hard, not soft. Linked wallet_provider_shops rows cascade away with it.
- Success is 204 with an EMPTY body - clients that assume JSON on 2xx will throw.
- Successful deletion returns HTTP 204 with no JSON body; do not call response.json() on that success response.

##### `GET /v1/wallet-providers/:id/cert-probe`

**Scope** `routing.read` - **Probe Apple cert**

Self-check before submitting a domain to Apple: fetches https://<registered_domain>/.well-known/apple-developer-merchantid-domain-association from the public internet and reports the upstream status, content type, a body preview and whether the served body matches the apple_cert stored on the MID.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Response**

```json
{
  "url": "https://wallet.example.com/.well-known/apple-developer-merchantid-domain-association",
  "status": 200,
  "contentType": "text/plain; charset=utf-8",
  "bodyPreview": "7B227073705F6964223A22364138453838323439393442222C2276657273696F6E223A312C22637265617465",
  "matchesStored": true
}
```

| response field | type | description |
|---|---|---|
| `url` | string | The exact URL that was fetched, built as https://<registered_domain>/.well-known/apple-developer-merchantid-domain-association. |
| `status` | integer | The UPSTREAM HTTP status code from that fetch (200, 404, 502, ...). This is the field that tells you whether the probe succeeded - NOT the status of this API call. |
| `contentType` | string\|string[]\|null | The upstream content-type header, forwarded raw from undici. Can be an array if the origin sent the header more than once. |
| `bodyPreview` | string | The first 120 characters of the upstream body only - truncated, so it is never enough to reconstruct the cert. |
| `matchesStored` | boolean | true when the trimmed upstream body equals the trimmed apple_cert column. This is the real pass/fail signal. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"No registered domain"} - returned BOTH when registered_domain is null AND when the id does not exist or is not yours (`!provider?.registered_domain` collapses the two).
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `502` {"url":"...","error":"<message>"} - the outbound fetch itself threw: DNS failure, TLS error, connection refused or timeout. An upstream 404/500 does NOT land here.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- This returns HTTP 200 even when the probe found nothing: an upstream 404 comes back as {"status":404,"matchesStored":false} with a 200 envelope. Never branch on the HTTP status - read `status` and `matchesStored`.
- matchesStored is false whenever apple_cert is null, because the comparison is against ('' ).trim() - an empty served body would then compare equal to an empty stored cert and report true, which is a false pass. Check `status` and a non-empty bodyPreview too.
- The 404 here means 'no domain OR no such MID', not 'the cert file is missing'. The cert file being missing shows up as a 200 with status:404 inside.
- bodyPreview is capped at 120 chars while the comparison uses the FULL body - a preview that looks right tells you nothing about matchesStored.
- Only https:// is attempted, with no redirect handling configured and no timeout override - a slow or hanging wallet host will occupy the request until undici's default timeout.
- This is a GET that makes an outbound request to an operator-controlled hostname stored in the DB. It is scoped to MIDs the caller owns, but it is still a server-side fetch driven by user-supplied data.
- If registered_domain was stored with an https:// prefix or a path, the URL becomes https://https://... and you get a 502 rather than a useful error.

##### `POST /v1/wallet-providers/:id/create-domain`

**Scope** `routing.write` - **Provision Render domain**

Creates (or re-creates) the Render custom domain for a MID's registered_domain and stores the resulting domain id plus the DNS record the operator must add. Used when the MID predates Render being configured, or to retry after a render_error.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Request body**

```json
{}
```

**Response**

```json
{
  "dns": {
    "type": "CNAME",
    "name": "wallet.example.com",
    "target": "cocoapi.onrender.com"
  }
}
```

| response field | type | description |
|---|---|---|
| `dns.type` | enum: CNAME\|A | Computed locally from the label count: >=3 labels -> CNAME to RENDER_SERVICE_HOSTNAME, 2 labels (apex) -> A to RENDER_APEX_IP. |
| `dns.name` | string | The normalised host the record must be created for (scheme/path stripped from registered_domain). |
| `dns.target` | string | CNAME target hostname or apex IP address the record must point at. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `409` {"error":"<host> is already a custom domain on the Render service \"<name>\"...","conflict":{"serviceId","serviceName","domainId","verificationStatus"}|null,"dns":{...}} - Render refused because the host belongs to another of our services. `conflict` names it, found by scanning every service's custom domains; null when that scan failed or Render is unkeyed.
- `422` {"error":"MID has no registered domain"} - returned for a MID with a null registered_domain AND for an id that does not exist or is not yours. This route has NO 404: `!provider?.registered_domain` collapses both cases.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `502` {"error":"<render message>","dns":{...}} - Render rejected the create for a reason other than a domain conflict. The MID is left with domain_verification_status='render_error' and the dns_record_* columns updated.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Render not configured"} - RENDER_API_KEY or RENDER_SERVICE_ID is unset on the server.

**Gotchas**

- A wrong or foreign :id returns 422 'MID has no registered domain', which reads like a data problem but is actually a not-found/not-owned. Do not treat 422 as 'fix the domain field'.
- 'Re-create' means a NEW Render custom domain is created - the previous render_domain_id is NOT deleted at Render first. Repeated calls orphan domains on the service and usually 502 with 'already exists'.
- Even on failure the route WRITES to the MID: dns_record_type, dns_record_target and domain_verification_status='render_error' are persisted, and because updateProviderDomain uses coalesce(), the OLD render_domain_id is preserved. A 502 leaves the row in a half-updated state.
- The dns record is computed by this API, not returned by Render. If RENDER_SERVICE_HOSTNAME is unset, dns.target for a CNAME is the empty string and the record you publish will be wrong.
- This only creates the domain on Render. DNS at the registrar and verification are separate manual steps - follow with POST /:id/verify-domain.
- Nothing here validates that registered_domain is a bare host. If it was stored with an https:// prefix via POST/PATCH, the Render domain is created for the stripped host while the DB keeps the unstripped value, and the wallet-host lookup (exact match) will never hit.

##### `GET /v1/wallet-providers/:id/credentials`

**Scope** `routing.write` - **Read a wallet MID's stored secrets (in clear)**

Returns one wallet provider's stored secret key and webhook secret in clear ('' when unset), to a caller that may edit the provider; no-store, one audit row per reveal naming the fields (never a value).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string | **yes** | Wallet provider id of the caller's account; another account's -> 404. |

**Response**

```json
{
  "secretKey": "sk_live_...",
  "webhookSecret": "whsec_..."
}
```

| response field | type | description |
|---|---|---|
| `secretKey` | string | Decrypted secret_key_enc, "" when unset. |
| `webhookSecret` | string | Decrypted webhook_secret_enc, "" when unset. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"}: the key lacks routing.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Not found"} - unknown id or another account's provider.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Internal Server Error with a requestId.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- v3.9.8 item 7 - the answer carries LIVE secrets in clear: it is `Cache-Control: no-store` (+ `Pragma: no-cache`); never log it, never cache it, never echo it into a transcript.
- Each call that returns at least one value writes ONE audit row: action view_secret, the caller (an API key is recorded as apikey:<id>), object type and id, and the object name followed by the NAMES of the fields shown, never a value. A provider with nothing stored returns empty values and writes no row.
- The lists and general reads never carry these values (only *_set booleans): this route is the only way to read them, and the dashboard calls it when the form opens.
- PATCH /v1/wallet-providers/:id replaces a secret (a truthy string) and never empties one.

##### `POST /v1/wallet-providers/:id/enable-methods`

**Scope** `routing.write` - **Enable wallet methods**

Calls ConvesioPay PATCH /v1/payment-methods with the MID's stored secret key to turn on card and Apple Pay for that integration. Run after pasting a freshly-created integration's secret, since Convesio's connect leaves wallet methods disabled.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Request body**

```json
{}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true means ConvesioPay returned a 2xx for the payment-methods PATCH, and wallet_providers.wallet_methods_enabled_at was stamped with now(). |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - the MID does not exist or is not owned by the caller's account.
- `422` {"error":"MID has no secret on file"} - secret_key_enc is null (or decryption returned null). PATCH the MID with a secretKey first.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `502` {"error":"Convesio enable methods <status>: <message>"} - ConvesioPay rejected the call, usually a bad/revoked secret key.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The method set is HARDCODED to {card:true, applePay:true, googlePay:false}. Calling this on a MID you had configured for Google Pay will DISABLE Google Pay at Convesio, silently, with no parameter to prevent it.
- On success it stamps wallet_methods_enabled_at (migration 138) - our own record that the switch was thrown, since Convesio offers no read-back. It still does NOT touch apple_pay_enabled / google_pay_enabled, so the local routing flags and the Convesio state can still disagree.
- Auth to Convesio is the RAW secret key in the Authorization header with no 'Bearer' prefix - that is the /v1 API's convention, not a bug, but it means the stored secret must be the /v1 secret, not an api key.
- Idempotent at Convesio (it is a PATCH of a state), so retrying is safe, but there is no way to read back what the methods currently are.
- The MID's own is_active / apple_pay_enabled state is not checked - you can enable methods at Convesio on a MID that is switched off locally.

##### `GET /v1/wallet-providers/:id/status`

**Scope** `routing.read` - **Apple Pay readiness**

Every condition that must hold before this wallet MID can take an Apple Pay payment, checked LIVE rather than read from our own columns: public DNS is resolved, Render is asked for the real custom-domain verification state, and the Apple domain-association file is fetched off the wallet host and compared byte for byte with the stored one. Backs the Status tab on the wallet provider screen, which renders one green/red line per step with either a Fix now button or the manual steps.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. A non-uuid answers 400 {"error":"Invalid wallet provider ID"} before any database read. |

**Response**

```json
{
  "id": "3f2b\u2026",
  "name": "HOOMA CONVESIOPAY",
  "environment": "production",
  "ready": false,
  "failed": 2,
  "steps": [
    {
      "key": "integration",
      "label": "Convesio integration",
      "state": "ok",
      "detail": "fbm-wallet-hooma-production-wallet.hoomagoods.com",
      "blocking": true
    },
    {
      "key": "dns",
      "label": "DNS",
      "state": "fail",
      "detail": "wallet.hoomagoods.com does not resolve at all.",
      "blocking": true,
      "manual": [
        "Add a CNAME record for wallet.hoomagoods.com pointing to coco-wallet.onrender.com.",
        "Keep it DNS-only. Proxied (Cloudflare\u2019s orange cloud) stops Render verifying the domain and issuing its certificate."
      ]
    },
    {
      "key": "render-verify",
      "label": "Render domain verified",
      "state": "fail",
      "detail": "Render reports \"unverified\". Until it verifies there is no TLS certificate, and Apple refuses a host it cannot reach over HTTPS.",
      "blocking": true,
      "fix": {
        "label": "Verify now",
        "path": "verify-domain"
      },
      "manual": [
        "Add the CNAME record below first, DNS-only, then press Verify now."
      ]
    }
  ],
  "test": {
    "possible": false,
    "reason": "Blocked by: DNS, Render domain verified.",
    "simulated": false
  }
}
```

| response field | type | description |
|---|---|---|
| `ready` | boolean | true when no BLOCKING step is red. The single pass/fail signal; `warn` and non-blocking steps never make it false. |
| `failed` | integer | How many blocking steps are in state 'fail'. |
| `steps[].key` | string | Stable identifier for the step: integration, api-key, secret, domain, render, render-verify, dns, cert-stored, cert-served, methods, flag, account-flag, active, shops, env. |
| `steps[].state` | string | 'ok' \| 'fail' \| 'warn' \| 'skip'. 'skip' means the step could not be evaluated because an earlier one is missing (no domain -> no DNS check), NOT that it passed. |
| `steps[].blocking` | boolean | Whether a red state on this step stops a payment. Store links and a sandbox environment are reported but non-blocking. |
| `steps[].detail` | string | What is true right now, in one line - the resolved DNS target, Render's own wording, the upstream HTTP status. |
| `steps[].fix` | object\|undefined | {label, path} when the step can be fixed by calling POST /v1/wallet-providers/:id/<path> (create-domain, verify-domain, enable-methods). Absent when only a human can fix it. |
| `steps[].link` | object\|undefined | {label, url} when there is something the operator should open and judge themselves - the wallet host, and the exact .well-known URL Apple fetches. |
| `steps[].manual` | string[]\|undefined | Ordered instructions for a human, used when there is no automatic fix or when the automatic one needs a prerequisite. |
| `test.possible` | boolean | Whether POST /v1/wallet-providers/:id/test-session would produce a usable sheet. False while any blocking step other than 'methods' is not ok. |
| `test.simulated` | boolean | WALLET_TEST_MODE. true -> the hosted page offers Simulate approved / declined and no money moves; false -> completing the sheet is a real charge. |

**Errors**

- `400` {"error":"Invalid wallet provider ID"} when :id is not a uuid (checked by the route before any database read).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - no such MID, or it belongs to another account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The response is always 200 when the MID exists, whatever the checks found. Read `ready` and the per-step `state`; never branch on the HTTP status.
- The call makes three outbound requests (DNS resolution, the Render API, an HTTPS fetch of the wallet host) so it is slow by design - budget a few seconds and do not put it on a polling loop.
- The 'Render custom domain' step scans every Render service when the host is not on ours, so a red line there names the service that holds it (the legacy checkout holds nine wallet hosts). That scan adds a second or two to the call.
- 'Apple Pay enabled at Convesio' goes green only on OUR record (wallet_methods_enabled_at), never on Convesio's actual state - they expose no read. Green there means 'we threw the switch on this date', and the step keeps a Run again action.
- A 'skip' state is not a pass. With no registered domain, five steps come back 'skip' and `ready` is still false because the domain step itself is red.
- The DNS check accepts any resolution when the MID has no stored Render target, so a green DNS line on a MID that was never provisioned on Render only means the host resolves somewhere.
- Apple Pay has TWO switches - the MID's apple_pay_enabled and the account-wide one. The hosted page honours both, so the checklist reports both; turning the MID's on while the account's is off changes nothing.

##### `POST /v1/wallet-providers/:id/test-session`

**Scope** `routing.write` - **Open a test Apple Pay sheet**

Creates a $1.00 Apple Pay wallet session PINNED to this MID and returns the hosted-page URL for it, so an operator tests the MID in front of them instead of whichever one the router would have picked. The row is an ordinary wallet_sessions row with order_id 'wallet-test-<8 hex>' and a 30-minute expiry; opening the URL renders the real Convesio Apple Pay sheet on the wallet host.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. A non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Request body**

```json
{}
```

**Response**

```json
{
  "url": "https://wallet.hoomagoods.com/s/6f1c2b90-1f4e-4a0e-9a1f-2d9a7c3e5b11",
  "simulated": false,
  "amountCents": 100
}
```

| response field | type | description |
|---|---|---|
| `url` | string | The hosted wallet page for the new session, https://<registered_domain>/s/<session id>. Open it on a device with Apple Pay. |
| `simulated` | boolean | WALLET_TEST_MODE. true -> the page shows Simulate approved / declined and nothing is sent to Convesio; false -> completing the sheet charges $1.00 for real. |
| `amountCents` | integer | Always 100. The session amount, in cents. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - no such MID, or it belongs to another account.
- `422` {"error":"MID has no registered domain"} or {"error":"MID has no api_key - the sheet cannot mount"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The session is created with no idempotency key, so every call makes a new pending row. Sessions expire after 30 minutes and stay 'pending' in wallet_sessions if never completed.
- shop_id is the MID's first linked store, or the all-zero uuid when none is attached - so a test session on an unattached MID is not tied to any store in the wallet log.
- return_url points back at the session page itself, so closing the sheet lands on the session's own status rather than on a storefront.
- A 422 about the api_key means the PUBLIC Convesio key, not the secret. Without it the page renders a notice instead of the Apple Pay button.

##### `POST /v1/wallet-providers/:id/verify-domain`

**Scope** `routing.write` - **Verify Render domain**

Forces Render to re-check the MID's custom domain after DNS has been added, then re-reads the domain and persists the resulting verification status on the MID.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Wallet provider id, owned by the caller's account. Not validated - a non-uuid reaches the database and answers 400 "A value has an invalid format.". |

**Request body**

```json
{}
```

**Response**

```json
{
  "verificationStatus": "verified"
}
```

| response field | type | description |
|---|---|---|
| `verificationStatus` | string | Render's status for the custom domain, passed through verbatim; 'unverified' is substituted when Render returns no status. Typical values: 'verified', 'unverified'. This is also written to domain_verification_status, and domain_verified_at is stamped ONLY when the value is exactly 'verified'. |

**Errors**

- `400` {"error":"A value has an invalid format."} when :id is not a valid uuid (the database rejects it).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `404` {"error":"Not found"} - the MID does not exist or is not owned by the caller's account.
- `422` {"error":"No Render domain on this MID"} - render_domain_id is null. Call POST /:id/create-domain first.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database failure.
- `502` {"error":"Render getCustomDomain <status>: ..."} - the follow-up read of the domain failed (e.g. the domain was deleted at Render, or the API key is bad).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- A 200 does NOT mean the domain is verified. Verification is asynchronous at Render - the overwhelmingly common success response is {"verificationStatus":"unverified"}, meaning 'checked, still not verified'. Poll it.
- verifyCustomDomain's return value is DISCARDED: if Render's POST /verify returns a non-2xx it does not throw and does not surface anywhere. Only a failure of the subsequent GET produces a 502, so a rejected verify request looks like a normal 'still unverified' result.
- domain_verified_at is only set when the status string is exactly 'verified'; any other Render wording leaves it null forever.
- updateProviderDomain uses coalesce(), so a null/absent status silently keeps the previous value rather than clearing it.
- This route never re-checks whether the DNS record actually matches dns_record_target - it only asks Render.

##### `POST /v1/wallet-providers/bootstrap`

**Scope** `routing.write` - **Bootstrap MID via Convesio**

One-shot onboarding of a ConvesioPay wallet provider: logs into ConvesioPay with the merchant's ConvesioPay dashboard credentials to provision a new integration's keys, enables card and Apple Pay on it, creates the local provider with those keys, then creates the wallet custom domain. Runs as a durable job (run inline, up to five steps) when the job storage is available: 201 with the result on success, else 502 with the job id to follow. Without the job storage it runs the legacy inline path.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `convesioEmail` | string | **yes** | The operator's ConvesioPay account login email. Sent as HTTP Basic to POST https://api.convesiopay.com/v1/integrations/connect. |
| `convesioPassword` | string | **yes** | The dashboard password, min 1 char. Travels in the JSON request body in PLAINTEXT and is never stored. |
| `name` | string | **yes** | Display name for the new local MID, 1..256 chars. |
| `registeredDomain` | string | **yes** | The wallet host, 3..256 chars. https:// and any /path are stripped before use, and the STRIPPED value is what gets stored (unlike plain POST /wallet-providers). |
| `environment` | enum: sandbox\|production; default `production` | no | zod .default('production'). Feeds the derived integration name slug; the Convesio host is hardcoded to production either way (api-qa is retired). |
| `appleCert` | string\|null; default `null` | no | Optional pre-issued Apple domain-association file body, max 20000 chars. |
| `processorId` | string (uuid) \| null; default `the CONVESIO PAY row` | no | v3.9 section 0 - id of the PROCESSOR behind the wallet MID (a `processors` row, GET /v1/processors). Never free text: an unknown id is 400 `{"error":"Unknown processor"}`. Omitted (or null) -> the CONVESIO PAY reference row, resolved by name or alias (CONVESIO PAY / CONVESIOPAY), because this route IS a ConvesioPay connect - the same rule migration 138 backfilled; null only if that row does not exist. -> column wallet_providers.processor_id. |
| `acquiringBankId` | string (uuid) \| null; default `null` | no | v3.9 section 0 - id of the ACQUIRING BANK / service behind the wallet MID (an `acquiring_banks` row, GET /v1/acquiring-banks). Unknown id -> 400 `{"error":"Unknown acquiring bank"}`. No default: omitted stores null, and the wallet then lands in the '(unset)' bucket of the per-wallet breakdowns - the dashboard form requires it. -> column wallet_providers.acquiring_bank_id. |
| `companyId` | string (uuid) \| null; default `null` | no | v3.9.2 section 0 - id of the COMPANY behind the wallet MID (a `companies` row, GET /v1/companies): the legal entity it is boarded under. Unknown id -> 400 `{"error":"Unknown company"}`. No default (a Convesio connect names no legal entity): omitted stores null and the wallet lands in the '(unset)' bucket of the Company breakdowns until you PATCH it. -> column wallet_providers.company_id. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `X-Request-Id` | string (uuid); default `a new uuid` | no | Idempotency key of the onboarding job. Resending the same id with the same body returns the same job instead of provisioning again; the same id with another body answers 409. Without it every call is a new job. |

**Request body**

```json
{
  "convesioEmail": "merchant@example.com",
  "convesioPassword": "<dashboard password>",
  "name": "Wallet - shop.example.com",
  "registeredDomain": "wallet.example.com",
  "environment": "production",
  "acquiringBankId": "c1e6f4b9-3a7d-4e25-9c08-6b2d1f8a3e07",
  "companyId": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35"
}
```

**Response**

```json
{
  "id": "9f1c2e88-4b3a-4d21-9c7e-1a2b3c4d5e6f",
  "integration_id": "fbm-wallet-example-com-production-wallet.example.com",
  "client_key_returned": true,
  "dns": {
    "type": "CNAME",
    "name": "wallet.example.com",
    "target": "cocoapi.onrender.com"
  },
  "renderError": null
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | The new local MID id. HTTP 201. |
| `integration_id` | string | The integration name CONVESIO RETURNED, not the one this API derived - Convesio appends the domain. Snake_case here even though the create route has no such field. |
| `client_key_returned` | boolean | false means Convesio's connect response omitted clientKey, so client_key is null on the MID and the checkout sheet will need it filled in manually via PATCH. |
| `dns` | object\|null | {type, name, target} DNS record to add at the registrar. null when RENDER_API_KEY/RENDER_SERVICE_ID are unset. |
| `renderError` | string\|null | Non-null when the Render domain creation failed. The MID still exists and the status is still 201. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} - bad email, empty password, domain shorter than 3 chars, a processorId / acquiringBankId / companyId that is not a uuid, etc. {"error":"Unknown processor"}, {"error":"Unknown acquiring bank"} or {"error":"Unknown company"} - a well-formed processorId / acquiringBankId / companyId that is not in its reference table (the FK failed). Both Convesio calls already succeeded: the remote integration exists with no local record (same as the 500 case). {"error":"Unknown provider reference"} (durable path) when processorId, acquiringBankId or companyId is not a known reference.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Wallet administration access is required"}; {"error":"Wallet account access changed"}.
- `409` {"error":"Request identity belongs to another request or principal"} when X-Request-Id was used with another body or by another caller; a conflict when the host already has a domain operation in progress.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance). {"error":"Five wallet operations already need attention"}.
- `500` The local insert failed after both Convesio calls succeeded - the remote integration exists with no local record.
- `502` {"error":"Convesio connect failed: ..."} - the ConvesioPay account login/provisioning call failed (wrong credentials, duplicate integration name, or a response missing apiKey/secretKey). Nothing was created locally. {"error":"Convesio enable-methods failed: ..."} - keys WERE provisioned at Convesio but PATCH /v1/payment-methods failed. No local MID is created; the remote integration is orphaned. {"error":"<reason, or Wallet setup needs review. Open saved progress.>","jobId":"<uuid>","providerId":"<uuid> | null"} (durable path) when the job did not finish successfully within the inline steps.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Wallet operation controls are busy. Check saved progress before retrying.","requestId":"<id>"} on the durable path when more than 32 wallet control operations run at once on the instance.

**Gotchas**

- Send X-Request-Id: with it a retry after a timeout or a 502 returns the saved job instead of provisioning a second ConvesioPay integration. Follow an unfinished job with the wallet bootstrap job routes (GET /v1/wallet-providers/bootstrap-jobs).
- The wallet method set is HARDCODED: card:true, applePay:true, googlePay:FALSE. There is no parameter to enable Google Pay, and the created MID has google_pay_enabled unset (false).
- None of the five fee fields can be supplied here and the create path drops them anyway. A bootstrapped MID starts on DB-default fees; PATCH it before sending traffic or the margin is wrong.
- v3.9 section 0 - the processor defaults to CONVESIO PAY (looked up by name / alias, so a rename keeps working), the acquiring bank does NOT: send acquiringBankId (ADYEN or STRIPE, whichever backs the integration) or the wallet reports as '(unset)' in every per-wallet breakdown and filter until you PATCH it. The company (v3.9.2 section 0) has no default either: send companyId (the boarding LLC) or set it later from the wallet provider page.
- integration_id in the response is Convesio's name (domain appended), which differs from the fbm-<slug>-<env> name this API derived. Store what the response says, not what you predicted.
- environment is only a naming/slug input - CONVESIO_BASE_URL is hardcoded to https://api.convesiopay.com, so 'sandbox' still hits production.
- convesioPassword is sent as a plaintext JSON field over this admin API. It is used once for Basic auth and discarded, but it will appear in any request-body logging or proxy capture.
- renderError non-null still returns 201 - check the field, not the status.
- At most five onboarding or domain operations of the account may be queued, running or uncertain at once (429 beyond).

##### `GET /v1/wallet-providers/bootstrap-capabilities`

**Scope** `routing.read` - **Read wallet setup availability**

Says whether the background wallet setup can run for the caller: background workers on and wallet job storage present. Checks the caller's access first.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | Wallet setup available. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Required storage for wallet setup is unavailable. Complete the current database migrations."}: workers are on but the storage is missing.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- enabled false (workers off) means POST /v1/wallet-providers/bootstrap-jobs answers 503.
- Answers carry cache-control: no-store.

##### `GET /v1/wallet-providers/bootstrap-jobs`

**Scope** `routing.read` - **List wallet setups**

Lists the last 20 wallet setup jobs started by the same principal and scope as the caller, jobs that still need attention first, then newest first. With requestId, returns only the job of that request id (or none).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | no | The requestId of a POST: returns {"jobs": [job]} or {"jobs": []}. Lets a caller find a job after an uncertain POST. |

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000701",
      "requestId": "00000000-0000-4000-8000-000000000702",
      "name": "Demo wallet",
      "hostname": "wallet.example.com",
      "status": "success",
      "phase": "finish",
      "effects": 4,
      "attempts": 0,
      "nextAttemptAt": "2026-11-24T10:00:00.000Z",
      "cancelRequested": false,
      "providerId": "00000000-0000-4000-8000-000000000703",
      "result": {
        "id": "00000000-0000-4000-8000-000000000703",
        "integration_id": "demo-wallet-integration",
        "client_key_returned": true,
        "inactive": false,
        "dns": {
          "type": "CNAME",
          "target": "demo-service.example.com",
          "name": "wallet.example.com"
        },
        "renderError": null
      },
      "error": null,
      "createdAt": "2026-11-24T10:00:00.000Z",
      "updatedAt": "2026-11-24T10:02:00.000Z",
      "finishedAt": "2026-11-24T10:02:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | Jobs in the shape of job (see GET /v1/wallet-providers/bootstrap-jobs/:id). |

**Errors**

- `400` {"error":"Invalid wallet operation identifier"}: requestId is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Wallet history unavailable"}: storage missing.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- A setup signs in to the wallet payment account with the given e-mail and password, enables its wallet payment methods, saves a wallet provider with Apple Pay on (GET /v1/wallet-providers) and registers its hostname on the hosting service. A step whose outcome is unknown ends as uncertain and is never replayed automatically; cancelling never undoes an external change.
- The password is kept encrypted for at most 30 minutes and wiped when the job ends; staged provider keys for 24 hours. Finished jobs are deleted after 7 days; uncertain jobs stay.
- Only transient database failures before any external call are retried, at most 3 attempts (2 s then 4 s).
- Answers carry cache-control: no-store.

##### `POST /v1/wallet-providers/bootstrap-jobs`

**Scope** `routing.write` - **Start a wallet setup**

Queues a durable wallet setup (sign in to the wallet payment account, enable its wallet methods, save the wallet provider, register its hostname on the hosting service) and answers 202 with the job. Follow it with GET /v1/wallet-providers/bootstrap-jobs/:id.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Your idempotency id. The same requestId with the same input and principal returns the saved job (202). |
| `input` | object | **yes** | Setup input. Strict: any other key is refused. |
| `input.convesioEmail` | string | **yes** | E-mail of the wallet payment account, at most 256 characters; trimmed and lowercased. |
| `input.convesioPassword` | string | **yes** | Password of that account, 1 to 4096 characters. Stored encrypted for at most 30 minutes, never returned. |
| `input.name` | string | **yes** | Name of the wallet provider to create, 1 to 256 characters. |
| `input.registeredDomain` | string | **yes** | 3 to 256 characters: the wallet hostname, bare (wallet.example.com) or as an http(s) URL. Normalized to the lowercase hostname; a port, credentials, a hostname without a dot or under .localhost answer 400. |
| `input.environment` | string; default `production` | no | sandbox or production. |
| `input.appleCert` | string \| null | no | Apple Pay domain association content, at most 20000 characters. |
| `input.processorId` | string (uuid) \| null | no | Processor reference (GET /v1/processors). Omitted: the wallet processor of the reference list, when one exists. |
| `input.acquiringBankId` | string (uuid) \| null | no | Acquiring bank reference (GET /v1/acquiring-banks). |
| `input.companyId` | string (uuid) \| null | no | Company reference (GET /v1/companies). |

**Request body**

```json
{
  "requestId": "00000000-0000-4000-8000-000000000702",
  "input": {
    "convesioEmail": "wallet-owner@example.com",
    "convesioPassword": "example-password",
    "name": "Demo wallet",
    "registeredDomain": "wallet.example.com",
    "environment": "production",
    "appleCert": null,
    "processorId": null,
    "acquiringBankId": null,
    "companyId": null
  }
}
```

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "requestId": "00000000-0000-4000-8000-000000000702",
    "name": "Demo wallet",
    "hostname": "wallet.example.com",
    "status": "queued",
    "phase": "connect",
    "effects": 0,
    "attempts": 0,
    "nextAttemptAt": "2026-11-24T10:00:00.000Z",
    "cancelRequested": false,
    "providerId": null,
    "result": null,
    "error": null,
    "createdAt": "2026-11-24T10:00:00.000Z",
    "updatedAt": "2026-11-24T10:00:00.000Z",
    "finishedAt": null
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, requestId, name, hostname, status (queued, running, success, partial, failed, cancelled, uncertain), phase (connect, enable, provider, render, finish), effects (confirmed external changes), attempts, nextAttemptAt, cancelRequested, providerId (the wallet provider id once saved), result, error, createdAt, updatedAt, finishedAt. Never a credential. |
| `job.result` | object \| null | Once the provider is saved: id, integration_id, client_key_returned, inactive, and after domain registration dns {type, target, name} and renderError. |

**Errors**

- `400` {"error":"Invalid wallet setup request"}: a missing or invalid field or an unknown key; {"error":"Invalid wallet hostname"}; {"error":"Unknown provider reference"}: processorId, acquiringBankId or companyId not found.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `409` {"error":"Request identity belongs to another request or principal"}: same requestId with other input or another principal; {"error":"A domain operation already holds this hostname"}; {"error":"A wallet operation already needs attention for this integration"}: an active job for the same account e-mail and hostname, or the same hostname.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `429` {"error":"Five wallet operations already need attention"}: the account has 5 queued, running or uncertain jobs.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Background wallet setup is unavailable"}: workers off; {"error":"Wallet background jobs are unavailable"}: storage missing.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- Body limit 65536 bytes.
- The new provider stays inactive until its hostname is confirmed.
- A setup signs in to the wallet payment account with the given e-mail and password, enables its wallet payment methods, saves a wallet provider with Apple Pay on (GET /v1/wallet-providers) and registers its hostname on the hosting service. A step whose outcome is unknown ends as uncertain and is never replayed automatically; cancelling never undoes an external change.
- The password is kept encrypted for at most 30 minutes and wiped when the job ends; staged provider keys for 24 hours. Finished jobs are deleted after 7 days; uncertain jobs stay.
- Only transient database failures before any external call are retried, at most 3 attempts (2 s then 4 s).
- Answers carry cache-control: no-store.

##### `GET /v1/wallet-providers/bootstrap-jobs/:id`

**Scope** `routing.read` - **Read a wallet setup**

Reads the progress of one wallet setup job.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Wallet setup job id. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "requestId": "00000000-0000-4000-8000-000000000702",
    "name": "Demo wallet",
    "hostname": "wallet.example.com",
    "status": "success",
    "phase": "finish",
    "effects": 4,
    "attempts": 0,
    "nextAttemptAt": "2026-11-24T10:00:00.000Z",
    "cancelRequested": false,
    "providerId": "00000000-0000-4000-8000-000000000703",
    "result": {
      "id": "00000000-0000-4000-8000-000000000703",
      "integration_id": "demo-wallet-integration",
      "client_key_returned": true,
      "inactive": false,
      "dns": {
        "type": "CNAME",
        "target": "demo-service.example.com",
        "name": "wallet.example.com"
      },
      "renderError": null
    },
    "error": null,
    "createdAt": "2026-11-24T10:00:00.000Z",
    "updatedAt": "2026-11-24T10:02:00.000Z",
    "finishedAt": "2026-11-24T10:02:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, requestId, name, hostname, status (queued, running, success, partial, failed, cancelled, uncertain), phase (connect, enable, provider, render, finish), effects (confirmed external changes), attempts, nextAttemptAt, cancelRequested, providerId (the wallet provider id once saved), result, error, createdAt, updatedAt, finishedAt. Never a credential. |
| `job.result` | object \| null | Once the provider is saved: id, integration_id, client_key_returned, inactive, and after domain registration dns {type, target, name} and renderError. |

**Errors**

- `400` {"error":"Invalid wallet operation identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `404` {"error":"Wallet operation not found or access changed"}: unknown id, or a job started by another principal or scope.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- A setup signs in to the wallet payment account with the given e-mail and password, enables its wallet payment methods, saves a wallet provider with Apple Pay on (GET /v1/wallet-providers) and registers its hostname on the hosting service. A step whose outcome is unknown ends as uncertain and is never replayed automatically; cancelling never undoes an external change.
- The password is kept encrypted for at most 30 minutes and wiped when the job ends; staged provider keys for 24 hours. Finished jobs are deleted after 7 days; uncertain jobs stay.
- Only transient database failures before any external call are retried, at most 3 attempts (2 s then 4 s).
- Answers carry cache-control: no-store.

##### `POST /v1/wallet-providers/bootstrap-jobs/:id/cancel`

**Scope** `routing.write` - **Cancel a wallet setup**

Stops a queued or running wallet setup before its next external step. With no external call in flight the job ends cancelled at once ("Stopped before the next effect. Confirmed changes remain."); with one in flight cancelRequested becomes true and the worker stops after it. A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Wallet setup job id. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "requestId": "00000000-0000-4000-8000-000000000702",
    "name": "Demo wallet",
    "hostname": "wallet.example.com",
    "status": "cancelled",
    "phase": "connect",
    "effects": 0,
    "attempts": 0,
    "nextAttemptAt": "2026-11-24T10:00:00.000Z",
    "cancelRequested": true,
    "providerId": null,
    "result": null,
    "error": "Stopped before the next effect. Confirmed changes remain.",
    "createdAt": "2026-11-24T10:00:00.000Z",
    "updatedAt": "2026-11-24T10:00:20.000Z",
    "finishedAt": "2026-11-24T10:00:20.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, requestId, name, hostname, status (queued, running, success, partial, failed, cancelled, uncertain), phase (connect, enable, provider, render, finish), effects (confirmed external changes), attempts, nextAttemptAt, cancelRequested, providerId (the wallet provider id once saved), result, error, createdAt, updatedAt, finishedAt. Never a credential. |
| `job.result` | object \| null | Once the provider is saved: id, integration_id, client_key_returned, inactive, and after domain registration dns {type, target, name} and renderError. |

**Errors**

- `400` {"error":"Invalid wallet operation identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `404` {"error":"Wallet operation not found or access changed"}: unknown id, or a job started by another principal or scope.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- No body is read. Cancelling never undoes a change already made at the wallet payment account or the hosting service.
- A setup signs in to the wallet payment account with the given e-mail and password, enables its wallet payment methods, saves a wallet provider with Apple Pay on (GET /v1/wallet-providers) and registers its hostname on the hosting service. A step whose outcome is unknown ends as uncertain and is never replayed automatically; cancelling never undoes an external change.
- The password is kept encrypted for at most 30 minutes and wiped when the job ends; staged provider keys for 24 hours. Finished jobs are deleted after 7 days; uncertain jobs stay.
- Only transient database failures before any external call are retried, at most 3 attempts (2 s then 4 s).
- Answers carry cache-control: no-store.

##### `POST /v1/wallet-providers/bootstrap-jobs/:id/reconcile`

**Scope** `routing.write` - **Confirm an uncertain hostname registration**

Checks with the hosting service whether the hostname registration of an uncertain job actually happened, without repeating it. A positive readback saves the domain details on the provider and ends the job as partial with the provider still inactive for review.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Wallet setup job id. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "requestId": "00000000-0000-4000-8000-000000000702",
    "name": "Demo wallet",
    "hostname": "wallet.example.com",
    "status": "partial",
    "phase": "finish",
    "effects": 4,
    "attempts": 0,
    "nextAttemptAt": "2026-11-24T10:00:00.000Z",
    "cancelRequested": false,
    "providerId": "00000000-0000-4000-8000-000000000703",
    "result": {
      "id": "00000000-0000-4000-8000-000000000703",
      "integration_id": "demo-wallet-integration",
      "client_key_returned": true,
      "inactive": true,
      "dns": {
        "type": "CNAME",
        "target": "demo-service.example.com",
        "name": "wallet.example.com"
      },
      "renderError": null
    },
    "error": "Render registration confirmed by readback. Provider remains inactive until reviewed.",
    "createdAt": "2026-11-24T10:00:00.000Z",
    "updatedAt": "2026-11-24T10:02:00.000Z",
    "finishedAt": "2026-11-24T10:02:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, requestId, name, hostname, status (queued, running, success, partial, failed, cancelled, uncertain), phase (connect, enable, provider, render, finish), effects (confirmed external changes), attempts, nextAttemptAt, cancelRequested, providerId (the wallet provider id once saved), result, error, createdAt, updatedAt, finishedAt. Never a credential. |
| `job.result` | object \| null | Once the provider is saved: id, integration_id, client_key_returned, inactive, and after domain registration dns {type, target, name} and renderError. |

**Errors**

- `400` {"error":"Invalid wallet operation identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Wallet administration access is required"}: the caller's role is not admin; {"error":"Import API key or account access changed"}: the key is inactive or its account changed; {"error":"Wallet account access changed"}: the account owner is banned; {"error":"Import permissions changed"} / {"error":"Import account or role changed"}: the caller's grants changed.
- `404` {"error":"Wallet operation not found or access changed"}: unknown id, or a job started by another principal or scope.
- `409` {"error":"Only an uncertain Render registration can be checked"}; {"error":"Render configuration changed. Review the original service manually."}; {"error":"The original Render service does not confirm this hostname. No provider change was repeated."}; {"error":"Wallet progress or configuration changed"}; {"error":"Wallet domain reservation changed"}; {"error":"Saved provider changed. Review its configuration manually."}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Wallet operation controls are busy. Check saved progress before retrying."}: too many concurrent controls or a lock wait; {"error":"The database is temporarily unavailable  -  please retry in a moment."} when connections are exhausted.
- `504` {"error":"The request took too long and was cancelled  -  narrow the range and retry."}: the control deadline ran out; read the job again before retrying.

**Gotchas**

- No body is read. The check has a budget of about 22 seconds.
- Activate the provider afterwards from the wallet provider routes once reviewed.
- A setup signs in to the wallet payment account with the given e-mail and password, enables its wallet payment methods, saves a wallet provider with Apple Pay on (GET /v1/wallet-providers) and registers its hostname on the hosting service. A step whose outcome is unknown ends as uncertain and is never replayed automatically; cancelling never undoes an external change.
- The password is kept encrypted for at most 30 minutes and wiped when the job ends; staged provider keys for 24 hours. Finished jobs are deleted after 7 days; uncertain jobs stay.
- Only transient database failures before any external call are retried, at most 3 attempts (2 s then 4 s).
- Answers carry cache-control: no-store.

#### Bank accounts

The bank accounts that receive wire payments.

##### `GET /v1/bank-accounts`

**Scope** `routing.read` - **List bank accounts**

Lists every receiving bank account of the account (active and deactivated), newest first. These are the wire transfer sources used by payment ATRIs and payment method routing.

*No parameters.*

**Response**

```json
{
  "items": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "owner_email": "owner@example.com",
      "name": "USD account",
      "is_active": true,
      "currency": "USD",
      "country": "US",
      "bank_name": "Example Bank",
      "account_holder": "Example Company LLC",
      "account_number": "0012345678",
      "routing_number": "021000021",
      "iban": "",
      "swift_bic": "",
      "bank_address": "1 Example Street, New York, NY",
      "beneficiary_address": "2 Example Avenue, Austin, TX",
      "transfer_instructions": "Put the order reference in the transfer memo.",
      "discount_fee_bps": 0,
      "transaction_fee_cents": 0,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:00.000Z"
    }
  ]
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- The response is the full stored row, including account_number and iban in clear and owner_email. It is sent with cache-control: no-store.
- Deactivated accounts (is_active false) stay in the list; filter on is_active yourself.

##### `POST /v1/bank-accounts`

**Scope** `routing.write` - **Add a bank account**

Adds receiving bank instructions for wire payments. Needs an account number or an IBAN, and a routing number or a SWIFT/BIC. Answers 201 with the stored row.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-500, trimmed) | **yes** | Display name of the bank account. |
| `is_active` | boolean; default `true` | no | Whether the account can be used as a wire payment source. DELETE sets it to false; PATCH true reactivates. |
| `currency` | string (ISO 4217, 3 letters) | **yes** | Transfer currency; trimmed and upper-cased, must match ^[A-Z]{3}$. |
| `country` | string (ISO 3166-1 alpha-2) | **yes** | Bank country; trimmed and upper-cased, must match ^[A-Z]{2}$. |
| `bank_name` | string (1-500, trimmed) | **yes** | Name of the receiving bank. |
| `account_holder` | string (1-500, trimmed) | **yes** | Beneficiary name shown to the buyer. |
| `account_number` | string (0-500, trimmed); default `""` | no | Account number, kept as text so leading zeros survive. Required when iban is empty. |
| `routing_number` | string (0-500, trimmed); default `""` | no | Routing number (ABA, sort code...). Required when swift_bic is empty. |
| `iban` | string (0-500); default `""` | no | IBAN; spaces removed and upper-cased before the format check. Required when account_number is empty. |
| `swift_bic` | string (0-500); default `""` | no | SWIFT/BIC, upper-cased before the format check (8 or 11 characters). Required when routing_number is empty. |
| `bank_address` | string (0-500, trimmed); default `""` | no | Address of the bank. |
| `beneficiary_address` | string (0-500, trimmed); default `""` | no | Address of the beneficiary. |
| `transfer_instructions` | string (0-2000, trimmed); default `""` | no | Free text instructions shown with the wire details. |
| `discount_fee_bps` | integer (0-10000); default `0` | no | Percentage fee in basis points (100 = 1%) charged on a successful wire, used by the fee and net reports. |
| `transaction_fee_cents` | integer (0-2147483647); default `0` | no | Flat fee per successful wire transaction in minor units (cents), used by the fee and net reports. |

**Request body**

```json
{
  "name": "USD account",
  "currency": "USD",
  "country": "US",
  "bank_name": "Example Bank",
  "account_holder": "Example Company LLC",
  "account_number": "0012345678",
  "routing_number": "021000021",
  "bank_address": "1 Example Street, New York, NY",
  "beneficiary_address": "2 Example Avenue, Austin, TX",
  "transfer_instructions": "Put the order reference in the transfer memo.",
  "discount_fee_bps": 0,
  "transaction_fee_cents": 0
}
```

**Response** `201`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000001",
    "owner_email": "owner@example.com",
    "name": "USD account",
    "is_active": true,
    "currency": "USD",
    "country": "US",
    "bank_name": "Example Bank",
    "account_holder": "Example Company LLC",
    "account_number": "0012345678",
    "routing_number": "021000021",
    "iban": "",
    "swift_bic": "",
    "bank_address": "1 Example Street, New York, NY",
    "beneficiary_address": "2 Example Avenue, Austin, TX",
    "transfer_instructions": "Put the order reference in the transfer memo.",
    "discount_fee_bps": 0,
    "transaction_fee_cents": 0,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `{"error":"Invalid bank account fields"}` when the id is not a UUID or the body fails the schema (wrong type, out of bounds, unknown field: the schema is strict).
- `400` `{"error":"Account number or IBAN is required"}`, `{"error":"Routing number or SWIFT/BIC is required"}`, `{"error":"Invalid IBAN"}` (after spaces are removed and letters upper-cased it must match 2 letters, 2 digits, 11 to 30 letters or digits) or `{"error":"Invalid SWIFT/BIC"}` (6 letters, 2 letters or digits, optional 3 more).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Unknown body fields are refused (strict schema) with the generic 400 `Invalid bank account fields`; the message does not name the field.
- Fees: discount_fee_bps is basis points, transaction_fee_cents is minor units. The currency field is the transfer currency shown to the buyer.

##### `GET /v1/bank-accounts/:id`

**Scope** `routing.read` - **Get a bank account**

Reads one receiving bank account of the account.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Bank account id (one of this account's, from GET /v1/bank-accounts). |

**Response**

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000001",
    "owner_email": "owner@example.com",
    "name": "USD account",
    "is_active": true,
    "currency": "USD",
    "country": "US",
    "bank_name": "Example Bank",
    "account_holder": "Example Company LLC",
    "account_number": "0012345678",
    "routing_number": "021000021",
    "iban": "",
    "swift_bic": "",
    "bank_address": "1 Example Street, New York, NY",
    "beneficiary_address": "2 Example Avenue, Austin, TX",
    "transfer_instructions": "Put the order reference in the transfer memo.",
    "discount_fee_bps": 0,
    "transaction_fee_cents": 0,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `{"error":"Invalid bank account fields"}` when the id is not a UUID or the body fails the schema (wrong type, out of bounds, unknown field: the schema is strict).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `404` `{"error":"Bank account not found"}` when the id does not exist or belongs to another account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID id answers 400 `Invalid bank account fields`, not 404.

##### `PATCH /v1/bank-accounts/:id`

**Scope** `routing.write` - **Update a bank account**

Partially updates a bank account: send only the fields to change. The merged result (stored values plus your changes) is validated again, including the account number or IBAN and routing number or SWIFT/BIC rules.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Bank account id (one of this account's, from GET /v1/bank-accounts). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-500, trimmed) | no | Display name of the bank account. |
| `is_active` | boolean | no | Whether the account can be used as a wire payment source. DELETE sets it to false; PATCH true reactivates. |
| `currency` | string (ISO 4217, 3 letters) | no | Transfer currency; trimmed and upper-cased, must match ^[A-Z]{3}$. |
| `country` | string (ISO 3166-1 alpha-2) | no | Bank country; trimmed and upper-cased, must match ^[A-Z]{2}$. |
| `bank_name` | string (1-500, trimmed) | no | Name of the receiving bank. |
| `account_holder` | string (1-500, trimmed) | no | Beneficiary name shown to the buyer. |
| `account_number` | string (0-500, trimmed) | no | Account number, kept as text so leading zeros survive. Required when iban is empty. |
| `routing_number` | string (0-500, trimmed) | no | Routing number (ABA, sort code...). Required when swift_bic is empty. |
| `iban` | string (0-500) | no | IBAN; spaces removed and upper-cased before the format check. Required when account_number is empty. |
| `swift_bic` | string (0-500) | no | SWIFT/BIC, upper-cased before the format check (8 or 11 characters). Required when routing_number is empty. |
| `bank_address` | string (0-500, trimmed) | no | Address of the bank. |
| `beneficiary_address` | string (0-500, trimmed) | no | Address of the beneficiary. |
| `transfer_instructions` | string (0-2000, trimmed) | no | Free text instructions shown with the wire details. |
| `discount_fee_bps` | integer (0-10000) | no | Percentage fee in basis points (100 = 1%) charged on a successful wire, used by the fee and net reports. |
| `transaction_fee_cents` | integer (0-2147483647) | no | Flat fee per successful wire transaction in minor units (cents), used by the fee and net reports. |

**Request body**

```json
{
  "transfer_instructions": "Use reference ORDER-1234 in the memo.",
  "is_active": true
}
```

**Response**

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000001",
    "owner_email": "owner@example.com",
    "name": "USD account",
    "is_active": true,
    "currency": "USD",
    "country": "US",
    "bank_name": "Example Bank",
    "account_holder": "Example Company LLC",
    "account_number": "0012345678",
    "routing_number": "021000021",
    "iban": "",
    "swift_bic": "",
    "bank_address": "1 Example Street, New York, NY",
    "beneficiary_address": "2 Example Avenue, Austin, TX",
    "transfer_instructions": "Put the order reference in the transfer memo.",
    "discount_fee_bps": 0,
    "transaction_fee_cents": 0,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `{"error":"Invalid bank account fields"}` when the id is not a UUID or the body fails the schema (wrong type, out of bounds, unknown field: the schema is strict).
- `400` `{"error":"Account number or IBAN is required"}`, `{"error":"Routing number or SWIFT/BIC is required"}`, `{"error":"Invalid IBAN"}` (after spaces are removed and letters upper-cased it must match 2 letters, 2 digits, 11 to 30 letters or digits) or `{"error":"Invalid SWIFT/BIC"}` (6 letters, 2 letters or digits, optional 3 more).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `404` `{"error":"Bank account not found"}` when the id does not exist or belongs to another account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Same field rules as the create call, but every field is optional; omitted fields keep their stored value. Clearing account_number with an empty string fails unless an IBAN is stored or sent.
- Setting is_active to true reactivates an account deactivated by DELETE.

##### `DELETE /v1/bank-accounts/:id`

**Scope** `routing.write` - **Deactivate a bank account**

Soft-deletes a bank account: sets is_active to false. The row is kept (past wire transactions reference it) and still appears in the list.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Bank account id (one of this account's, from GET /v1/bank-accounts). |

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` `{"error":"Invalid bank account fields"}` when the id is not a UUID or the body fails the schema (wrong type, out of bounds, unknown field: the schema is strict).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `404` `{"error":"Bank account not found"}` when the id does not exist or belongs to another account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Nothing is erased. Reactivate with PATCH /v1/bank-accounts/:id and {"is_active":true}.

#### Card ATRIs

The card routing pools (ATRIs, "trips" in the addresses): their member MIDs, weights, caps and the default pool. GET /v1/atris is the picker.

- Archive and delete coexist. `POST /v1/trips/:id/archive` keeps the ATRI for its history: it is switched off, loses its default flag and leaves `GET /v1/trips` and `GET /v1/atris`; a charge, checkout or key that still names it falls through to the default ATRI. `GET /v1/trips?archived=true` lists the archived ones; `POST /v1/trips/:id/restore` brings one back, inactive and not the default. An archived ATRI cannot be switched on or made the default (409) and keeps its name. `DELETE /v1/trips/:id` erases an ATRI for good (live or archived). The dashboard shows the two lists as the ATRIs and Archived tabs.
- Smart select (ATRI window > Gateways) ranks candidate MIDs in the browser from yesterday's `perMid` of `GET /v1/metrics`. Candidates: available MIDs with at least one attempt. Prior = sum(approvalRateMidFixable x midFixableDenom) / sum(midFixableDenom) over the candidates; score = (approvalRateMidFixable x midFixableDenom + prior x 20) / (midFixableDenom + 20); highest score first, ties to the larger number of attempts. No endpoint returns this ranking.
- "Distribute equally / by cap" (weights by largest remainder, an uncapped MID counted as the largest cap) and the 100% check of the smart strategy are draft helpers; the result is saved with `PUT /v1/trips/:id/accounts`.

##### `GET /v1/atris`

**Scope** `routing.read` - **List routable ATRIs (id, name, default)**

The ATRI picker: the active classic ATRIs of the key's account (id, name, default), the values a charge or a routing setting takes; GET /v1/trips lists every ATRI with its configuration, member MIDs and month usage. Returns the ATRIs this key's account can route a charge to, for a selector: only active classic ATRIs (cascade ATRIs are internal fallbacks). Each id is what you pass as routeID (or atri) on POST /v1/charge. Read-only, apart from a best-effort last_used_at update on the key.

*No parameters.*

**Response**

```json
{
  "atris": [
    {
      "id": "6f2b1c94-8d3a-4a71-b0e5-1c7d9f4e2a83",
      "name": "Main US Retail",
      "default": true
    },
    {
      "id": "a1d4e7b2-5c60-4f38-9e11-77c3b8a0d5f9",
      "name": "EU Subscriptions",
      "default": false
    },
    {
      "id": "c93f0e55-2b18-4d6a-8c72-4ab1f60d3e27",
      "name": "High Ticket",
      "default": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `atris` | object[] | Selectable ATRIs, default first then by name. Always present; [] for an account without one (or a key without an account). |
| `atris[].id` | uuid | ATRI id: the value of routeID / atri on POST /v1/charge. |
| `atris[].name` | string | ATRI name, unique within the account. |
| `atris[].default` | boolean | true for the account's default ATRI (the one used when a charge names no route and the key has no default of its own). At most one per account; an account may have none. |

**Errors**

- `401` {"error":"Missing API key"}: neither Authorization: Bearer <key> nor a non-empty X-Api-Key header.
- `401` {"error":"Invalid API key"}: unknown or inactive key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden"} from the global bot guard for a crawler User-Agent.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: the ATRI query failed after authentication.
- `503` {"error":"Service temporarily unavailable","detail":"authentication backend error"}: the key lookup failed (retry); {"error":"Server busy, retry"} with Retry-After: 1 when the instance sheds load.

**Gotchas**

- Three fixed filters: active = true, classic ATRIs only, owned by the key's account. Inactive and cascade ATRIs never appear.
- Platform-wide ATRIs without an owning account are never listed, even though a charge may still reach one through a default. Do not treat this list as a full routing map.
- No parameter is read: query strings are ignored, there is no pagination.
- The field is `default` (renamed from the database column is_default).
- Bad key = 401 (do not retry); authentication backend down = 503 (retry).
- The last_used_at update is fire-and-forget; do not use it to prove a call happened.
- Scope routing.read: the dashboard-only ATRI lists of the subscription and store pickers are not public, so an integration that read them with subscriptions.read or checkouts.read uses this route.

##### `GET /v1/trips`

**Scope** `routing.read` - **List ATRIs with configuration, member MIDs and month usage**

The ATRIs of the account (the live ones by default; archived=true for the archived ones, archived=all for both) with their configuration, ordered member MIDs, caps and this month's usage (the full routing read); GET /v1/atris is the short picker (active classic ATRIs: id, name, default). Every ATRI (routing pool) of the account with its ordered gateway membership, this month's usage against caps, its BIN profile names and the name of its cascade ATRI. There is no single-ATRI read; filter this list.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `archived` | string (true\|false\|all); default `false` | no | false (or absent): the live ATRIs only, the ones you route with. true: the archived ATRIs only (archived with POST .../archive, kept for history; a deleted row is gone). all: both; each row says which it is in archived_at. Any other value answers 400. |

**Response**

```json
{
  "trips": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "name": "US Primary Pool",
      "description": null,
      "active": true,
      "archived_at": null,
      "dispatch_strategy": "volume",
      "bin_routing_enabled": true,
      "trip_type": "classic",
      "retry_count": 1,
      "cascade_trip_id": null,
      "max_decline_enabled": false,
      "max_decline_threshold": 0,
      "force_same_category": false,
      "prefer_same_category": false,
      "bin_map_profile_id": "55555555-5555-4555-8555-555555555555",
      "bin_scrub_profile_id": null,
      "bin_threeds_profile_id": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "is_default": true,
      "bin_map_profile_name": "Default mapping",
      "bin_scrub_profile_name": null,
      "bin_threeds_profile_name": null,
      "cascade_trip_name": null,
      "accounts": [
        {
          "trip_id": "11111111-1111-4111-8111-111111111111",
          "nmi_account_id": "33333333-3333-4333-8333-333333333333",
          "position": 0,
          "active": true,
          "weight": 60,
          "daily_limit": 0,
          "consecutive_declines": 0,
          "auto_disabled": false,
          "auto_disabled_reason": null,
          "account_name": "NMI US 01",
          "account_activated": true,
          "monthly_cap_cents": "5000000",
          "processor_id": null,
          "processor_name": null,
          "acquiring_bank_id": null,
          "acquiring_bank_name": null,
          "company_id": null,
          "company_name": null,
          "used_cents": "1234500",
          "categories": [
            {
              "id": "44444444-4444-4444-8444-444444444444",
              "name": "Supplements"
            }
          ]
        }
      ],
      "account_count": 1,
      "cap_cents": 5000000,
      "used_cents": 1234500,
      "has_unlimited": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `trips[]` | object[] | ATRIs ordered by name: the trip fields (see POST) plus is_default, bin_map_profile_name, bin_scrub_profile_name, bin_threeds_profile_name, cascade_trip_name. |
| `trips[].accounts[]` | object[] | Members by position: trip_id, nmi_account_id, position, active (membership flag), weight, daily_limit, consecutive_declines, auto_disabled, auto_disabled_reason, account_name, account_activated (the MID own switch), monthly_cap_cents (string, 0 = unlimited), processor / acquiring bank / company ids and names, used_cents (string, this UTC month), categories[] {id, name}. |
| `trips[].account_count / cap_cents / used_cents / has_unlimited` | integer / integer / integer / boolean | Members, sum of the non-zero member caps, sum of member usage this UTC month, and whether a member has no cap. |
| `trips[].archived_at` | string (ISO 8601) \| null | When the ATRI was archived (POST /v1/trips/:id/archive); null for a live ATRI. An archived ATRI is always inactive and never the default. |
| `trips[].accounts[].account_archived_at` | string (ISO 8601) \| null | Set when the member gateway is archived: it stays listed as a member, off (account_activated false), until removed or restored. |

**Errors**

- `400` {"error":"archived must be true, false or all"}: the archived query value is not one of the three.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Member monthly_cap_cents and used_cents are JSON strings (bigint); the trip-level cap_cents and used_cents are numbers.
- Usage is per MID: a MID in two ATRIs counts its whole month in both.
- Set processor, acquiring bank and company on the gateway itself (PATCH /v1/accounts/:id); they are read-only here.
- Archived ATRIs are left out unless you ask for them (archived=true or archived=all). GET /v1/atris never lists them.

##### `POST /v1/trips`

**Scope** `routing.write` - **Create an ATRI**

Create an ATRI owned by the account. It is created with NO members: add gateways with PUT /v1/trips/:id/accounts. It is not the default until POST /v1/trips/:id/default.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1..128) | **yes** | Unique within the account. Archived ATRIs keep their name: rename or restore the archived one to reuse it. |
| `description` | string (max 1024) | no | Free text. |
| `active` | boolean; default `true` | no | An inactive ATRI does not route. |
| `dispatchStrategy` | string (random\|cap\|volume\|orders\|round_robin\|best_ar\|velocity\|lru\|cost\|smart); default `volume` | no | How the first gateway is picked: random, cap (fill by monthly cap), volume (weighted share of volume), orders (weighted share of orders), round_robin, best_ar (highest recent approval rate), velocity (per-MID daily count limit, dailyLimit), lru (least recently used), cost (cheapest processing fee) or smart (weights are exact percentages of the day; active weights must sum to 100 when members are saved). |
| `binRoutingEnabled` | boolean; default `true` | no | Pin the first attempt to the card BIN's best-approval MID (through the BIN mapping profile). Off lets the dispatch strategy decide alone. |
| `binMapProfileId` | uuid \| null | no | BIN mapping profile of this account (kind mapping, enabled). null turns mapping off. Omitted on a classic ATRI with BIN routing on: the account's default mapping profile. |
| `binScrubProfileId` | uuid \| null | no | BIN scrubbing profile of this account (kind scrubbing). null turns scrubbing off. Omitted on a classic ATRI: the account's default scrubbing profile. |
| `binThreedsProfileId` | uuid \| null | no | BIN 3DS rule profile of this account (kind threeds). null turns it off. Omitted on a classic ATRI: the account's default 3DS profile. |
| `tripType` | string (classic\|cascade); default `classic` | no | classic picks one gateway by the strategy; cascade retries across members (retryCount) when it is the target of another ATRI. |
| `retryCount` | integer (1..20); default `1` | no | Attempts for a cascade ATRI. |
| `cascadeTripId` | uuid \| null | no | Another ATRI of this account to fail over to after this one declines; null unlinks. |
| `maxDeclineEnabled` | boolean; default `false` | no | Auto-disable a member after maxDeclineThreshold consecutive declines. |
| `maxDeclineThreshold` | integer (0..1000); default `0` | no | Consecutive declines before a member is auto-disabled. |
| `forceSameCategory` | boolean; default `false` | no | Cascade: only retry on gateways of the same category (wins over prefer). |
| `preferSameCategory` | boolean; default `false` | no | Cascade: try same-category gateways first. |

**Request body**

```json
{
  "name": "US Primary Pool",
  "dispatchStrategy": "volume",
  "binRoutingEnabled": true,
  "maxDeclineEnabled": true,
  "maxDeclineThreshold": 10
}
```

**Response** `201`

```json
{
  "trip": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "US Primary Pool",
    "description": null,
    "active": true,
    "dispatch_strategy": "volume",
    "bin_routing_enabled": true,
    "trip_type": "classic",
    "retry_count": 1,
    "cascade_trip_id": null,
    "max_decline_enabled": false,
    "max_decline_threshold": 0,
    "force_same_category": false,
    "prefer_same_category": false,
    "bin_map_profile_id": "55555555-5555-4555-8555-555555555555",
    "bin_scrub_profile_id": null,
    "bin_threeds_profile_id": null,
    "created_at": "2026-11-20T10:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `trip` | object | id, name, description, active, dispatch_strategy, bin_routing_enabled, trip_type, retry_count, cascade_trip_id, max_decline_enabled, max_decline_threshold, force_same_category, prefer_same_category, bin_map_profile_id, bin_scrub_profile_id, bin_threeds_profile_id, created_at (snake_case; is_default is not included). |

**Errors**

- `400` Invalid (details: zod flatten); Cascade ATRI not found; BIN mapping profile not found for this account; BIN scrubbing profile not found for this account; or BIN 3DS profile not found for this account.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `409` An ATRI with this name already exists in this account.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Body keys are camelCase, the response is snake_case.
- Unknown body keys are ignored silently (members, is_default, owner cannot be set here).
- Omitted profile pointers take the account's default profiles on a classic ATRI; send null to turn a kind off.
- smart is accepted here without checking weights; the 100% rule applies when members are saved.

##### `PATCH /v1/trips/:id`

**Scope** `routing.write` - **Update an ATRI**

Change some of an ATRI configuration fields; only the fields sent are written. Membership and the default flag are not edited here. The change applies to routing at once.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1..128) | no | New name, unique within the account. |
| `description` | string (max 1024) | no | Free text. Cannot be set back to null here. |
| `active` | boolean | no | An inactive ATRI does not route. On an archived ATRI, true is refused with 409 (restore it first with POST /v1/trips/:id/restore); its other fields can still be edited. |
| `dispatchStrategy` | string (random\|cap\|volume\|orders\|round_robin\|best_ar\|velocity\|lru\|cost\|smart) | no | How the first gateway is picked: random, cap (fill by monthly cap), volume (weighted share of volume), orders (weighted share of orders), round_robin, best_ar (highest recent approval rate), velocity (per-MID daily count limit, dailyLimit), lru (least recently used), cost (cheapest processing fee) or smart (weights are exact percentages of the day; active weights must sum to 100 when members are saved). |
| `binRoutingEnabled` | boolean | no | Pin the first attempt to the card BIN's best-approval MID (through the BIN mapping profile). Off lets the dispatch strategy decide alone. |
| `binMapProfileId` | uuid \| null | no | BIN mapping profile of this account (kind mapping, enabled). null turns mapping off. |
| `binScrubProfileId` | uuid \| null | no | BIN scrubbing profile of this account (kind scrubbing). null turns scrubbing off. |
| `binThreedsProfileId` | uuid \| null | no | BIN 3DS rule profile of this account (kind threeds). null turns it off. |
| `tripType` | string (classic\|cascade) | no | classic picks one gateway by the strategy; cascade retries across members (retryCount) when it is the target of another ATRI. |
| `retryCount` | integer (1..20) | no | Attempts for a cascade ATRI. |
| `cascadeTripId` | uuid \| null | no | Another ATRI of this account to fail over to after this one declines; null unlinks. |
| `maxDeclineEnabled` | boolean | no | Auto-disable a member after maxDeclineThreshold consecutive declines. |
| `maxDeclineThreshold` | integer (0..1000) | no | Consecutive declines before a member is auto-disabled. |
| `forceSameCategory` | boolean | no | Cascade: only retry on gateways of the same category (wins over prefer). |
| `preferSameCategory` | boolean | no | Cascade: try same-category gateways first. |

**Request body**

```json
{
  "dispatchStrategy": "best_ar",
  "cascadeTripId": "22222222-2222-4222-8222-222222222222"
}
```

**Response**

```json
{
  "trip": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "US Primary Pool",
    "description": null,
    "active": true,
    "dispatch_strategy": "best_ar",
    "bin_routing_enabled": true,
    "trip_type": "classic",
    "retry_count": 1,
    "cascade_trip_id": "22222222-2222-4222-8222-222222222222",
    "max_decline_enabled": false,
    "max_decline_threshold": 0,
    "force_same_category": false,
    "prefer_same_category": false,
    "bin_map_profile_id": "55555555-5555-4555-8555-555555555555",
    "bin_scrub_profile_id": null,
    "bin_threeds_profile_id": null,
    "created_at": "2026-11-20T10:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `trip` | object | id, name, description, active, dispatch_strategy, bin_routing_enabled, trip_type, retry_count, cascade_trip_id, max_decline_enabled, max_decline_threshold, force_same_category, prefer_same_category, bin_map_profile_id, bin_scrub_profile_id, bin_threeds_profile_id, created_at (snake_case; is_default is not included). |

**Errors**

- `400` Invalid (details: zod flatten); No fields to update (checked before ownership); Cascade ATRI not found; a BIN profile not found for this account; or A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `409` An ATRI with this name already exists in this account.; or This ATRI is archived. Restore it before switching it on. (active true on an archived ATRI; nothing is written)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- An ATRI may be linked to cascade to itself; nothing refuses it.
- Switching to smart here does not check member weights.

##### `DELETE /v1/trips/:id`

**Scope** `routing.write` - **Delete an ATRI**

Permanently delete an ATRI (live or archived) and its membership, BIN map rows and member ATRI grants. Answers 204 with no body. To keep its history, archive it instead (POST /v1/trips/:id/archive).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Response** `204`

No example body: see the purpose above for what the response carries.

| response field | type | description |
|---|---|---|
| `(none)` | empty | 204 No Content with an EMPTY body on success — do not try to parse JSON. |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `409` This references a record that does not exist, or is still in use elsewhere. (a payment method routing still points at it)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Irreversible. Keys, checkouts and other ATRIs that pointed at it lose the link silently (set to null); historical transactions keep no ATRI link.
- Deleting the default ATRI leaves the account with no default: charges that rely on the default fallback stop routing until another ATRI is made default.
- Archive and delete coexist: POST /v1/trips/:id/archive is the reversible alternative, and an archived ATRI (GET /v1/trips?archived=true) can still be deleted here.

##### `PUT /v1/trips/:id/accounts`

**Scope** `routing.write` - **Replace ATRI members**

Replace the ATRI's whole ordered gateway membership in one transaction. For a smart ATRI the active weights must sum to 100 (plus or minus 0.5).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `accounts` | array | **yes** | The complete membership; [] empties the ATRI. |
| `accounts[].nmiAccountId` | uuid | **yes** | Gateway (MID) of this account; each at most once. |
| `accounts[].position` | integer (>= 0) | **yes** | Order (failover and cascade order). |
| `accounts[].active` | boolean; default `true` | no | Membership switch. |
| `accounts[].weight` | number (0..100); default `0` | no | Target share in percent for volume, orders, round_robin and smart. |
| `accounts[].dailyLimit` | integer (0..1000000); default `0` | no | Charges per day for velocity (account timezone); 0 = unlimited. |

**Request body**

```json
{
  "accounts": [
    {
      "nmiAccountId": "33333333-3333-4333-8333-333333333333",
      "position": 0,
      "active": true,
      "weight": 60
    },
    {
      "nmiAccountId": "44444444-4444-4444-8444-444444444444",
      "position": 1,
      "active": true,
      "weight": 40,
      "dailyLimit": 500
    }
  ]
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on a 200. The stored rows are NOT echoed — re-read GET /v1/trips to see what was actually written. |

**Errors**

- `400` Invalid (details: zod flatten); One or more MIDs not found; Smart strategy: active gateway weights must sum to 100% (currently N%). Use "Distribute equally" or adjust.; or A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `409` A record with these details already exists. (the same nmiAccountId twice)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A full REPLACE: omitted members are removed. Build the list from a fresh GET /v1/trips.
- Omitted optionals are written as defaults (weight 0, dailyLimit 0 = unlimited, active true), so leaving dailyLimit out removes an existing cap.
- Every save resets each member's consecutive-decline counter and auto-disabled state.
- For smart, today's share window restarts only when the active weights actually change.

##### `POST /v1/trips/:id/archive`

**Scope** `routing.write` - **Archive an ATRI**

Archive an ATRI of the account instead of deleting it: it is switched off, loses the default flag, leaves the live list and every picker, and keeps its history. Answers the archived row. Undo it with POST /v1/trips/:id/restore; DELETE /v1/trips/:id erases it for good.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Response** `200`

```json
{
  "trip": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "US Primary Pool",
    "active": false,
    "is_default": false,
    "archived_at": "2026-11-24T14:05:12.640Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `trip.id` | string (uuid) | The ATRI id. |
| `trip.name` | string | Its name, unchanged. |
| `trip.active` | boolean | Always false: an archived ATRI is off. |
| `trip.is_default` | boolean | Always false: an archived ATRI is never the default. |
| `trip.archived_at` | string (ISO 8601) | When it was archived (the first archive when it already was). |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Nothing is erased: past transactions and attempts keep naming the ATRI, and its configuration, BIN profiles and gateway membership stay as they were.
- Routing stops at once: the ATRI is switched off and stops being the default. A charge, checkout or key that still names it falls through to the account's default ATRI, exactly as when a deleted ATRI's links were cleared. Point them at another ATRI to choose where that traffic goes.
- Archiving the default ATRI leaves the account with no default until you make another ATRI the default (POST /v1/trips/:id/default): charges that rely on the default fallback stop routing meanwhile.
- GET /v1/trips and GET /v1/atris leave it out; GET /v1/trips?archived=true lists it. An archived ATRI keeps its name: a new ATRI cannot take that name until the archived one is renamed.
- POST /v1/trips/:id/restore brings it back, still inactive and not the default.
- Idempotent: archiving an archived ATRI keeps the date of the first archive.
- No body.

##### `POST /v1/trips/:id/default`

**Scope** `routing.write` - **Toggle the default ATRI**

TOGGLE this ATRI as the account's default ATRI (the routing fallback when a charge names no ATRI and its key has none). If it is already the default the flag is CLEARED; otherwise it becomes the default and the account's previous default is unset. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Response**

```json
{
  "ok": true,
  "is_default": true
}
```

| response field | type | description |
|---|---|---|
| `is_default` | boolean | The new state: false means you just removed the default. |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `409` This account already has a default ATRI. (concurrent toggle); or This ATRI is archived. Restore it before making it the default ATRI. (the previous default stays)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A toggle, not a setter: calling it twice leaves the account with no default. After an uncertain answer, read is_default from GET /v1/trips before retrying.
- One default per account; other accounts are not affected. An inactive or empty ATRI can be made default; an archived one cannot.

##### `GET /v1/trips/:id/dispatch-share`

**Scope** `routing.read` - **Read smart dispatch share**

For the smart strategy: target vs actual share of today's approved volume per active member (account timezone day), plus the 50 latest dispatch decisions of the ATRI.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Response**

```json
{
  "window_date": "2026-11-20",
  "total_cents": 250000,
  "gateways": [
    {
      "nmi_account_id": "33333333-3333-4333-8333-333333333333",
      "name": "NMI US 01",
      "weight": 60,
      "target_pct": 60,
      "actual_pct": 58.4,
      "gap_pct": -1.6,
      "approved_cents": 146000
    }
  ],
  "timezone": "America/New_York",
  "decisions": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "transaction_id": "44444444-4444-4444-8444-444444444444",
      "amount_cents": "4999",
      "chosen_account_id": "33333333-3333-4333-8333-333333333333",
      "chosen_reason": "highest volume deficit",
      "candidates": [
        {
          "account_id": "33333333-3333-4333-8333-333333333333",
          "name": "NMI US 01",
          "weight": 60,
          "norm_weight": 0.6,
          "volume_cents": 146000,
          "deficit": 4000
        }
      ],
      "excluded": [],
      "duration_ms": 3,
      "created_at": "2026-11-20T14:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `window_date / timezone` | string | The local day measured and the account timezone. |
| `total_cents` | integer | Approved cents across the active members today. |
| `gateways[]` | object[] | Active members only: nmi_account_id, name, weight, target_pct (weight renormalised over active weights, 0..100), actual_pct, gap_pct (points), approved_cents. |
| `decisions[]` | object[] | Up to 50 newest decisions: id, transaction_id, amount_cents (string), chosen_account_id, chosen_reason (highest volume deficit, or no eligible gateway (all weight 0)), candidates[] {account_id, name, weight, norm_weight, volume_cents, deficit}, excluded, duration_ms, created_at. |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Only the smart strategy records this data: other strategies return zeros and no decisions.

##### `POST /v1/trips/:id/duplicate`

**Scope** `routing.write` - **Duplicate an ATRI**

Copy an ATRI (configuration, its three BIN profiles, cascade link) and its membership (position, active, weight, daily limit) into a new ATRI named "<name> (copy)" or "(copy N)". The copy is never the default. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Source ATRI id. |

**Response** `201`

```json
{
  "trip": {
    "id": "22222222-2222-4222-8222-222222222222",
    "name": "US Primary Pool (copy)"
  }
}
```

| response field | type | description |
|---|---|---|
| `trip` | object | {id, name} of the copy only; read GET /v1/trips for the rest. |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `409` An ATRI with this name already exists in this account. (all copy names taken, or a concurrent duplicate)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Members start with clean decline counters (auto-disabled members are active again in the copy). Rename with PATCH /v1/trips/:id.

##### `POST /v1/trips/:id/restore`

**Scope** `routing.write` - **Restore an archived ATRI**

Bring an archived ATRI back to the live list (GET /v1/trips) and the pickers. It stays INACTIVE and is not the default: switch it on with PATCH /v1/trips/:id { "active": true } and make it the default again with POST /v1/trips/:id/default if needed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | ATRI id. |

**Response** `200`

```json
{
  "trip": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "US Primary Pool",
    "active": false,
    "is_default": false,
    "archived_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `trip.id` | string (uuid) | The ATRI id. |
| `trip.name` | string | Its name, unchanged. |
| `trip.active` | boolean | false: a restored ATRI stays off until you switch it on. |
| `trip.is_default` | boolean | false: set the default again with POST /v1/trips/:id/default if needed. |
| `trip.archived_at` | null | null: the ATRI is live again. |

**Errors**

- `400` A value has an invalid format. (the id is not a uuid).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module payments).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Restoring an ATRI that is not archived changes nothing and answers the row.
- Its gateway membership and BIN profiles were kept while it was archived. Checkouts and keys that still name it route to it again once it is switched on.
- No body.

#### Wallet and wire ATRIs

The routing pools of wallet payments and of wire payments: one family of endpoints, the method (wallet or wire) is a field of the pool.

##### `GET /v1/payment-atris`

**Scope** `routing.read` - **List wallet and wire ATRIs**

Lists the account's payment ATRIs (routing pools for wallet payments and bank wires) with their members and the dispatch strategies they may use. Card routing uses the ATRIs of /v1/trips instead.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `method` | string | no | wallet or wire. Omitted: both. Other query keys are ignored. |

**Response**

```json
{
  "atris": [
    {
      "id": "00000000-0000-4000-8000-000000000101",
      "owner_email": "owner@example.com",
      "method": "wallet",
      "name": "Wallet ATRI",
      "description": null,
      "active": true,
      "is_default": true,
      "dispatch_strategy": "volume",
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-24T09:00:00.000Z",
      "members": [
        {
          "atri_id": "00000000-0000-4000-8000-000000000101",
          "source_id": "00000000-0000-4000-8000-000000000201",
          "position": 0,
          "active": true,
          "weight": 100,
          "daily_limit": 0,
          "monthly_cap_minor": 0,
          "source_name": "Demo wallet",
          "source_active": true,
          "currency": null,
          "discount_fee_bps": 0,
          "transaction_fee_cents": 0
        }
      ]
    }
  ],
  "strategies": [
    {
      "id": "volume",
      "label": "Weighted volume"
    },
    {
      "id": "orders",
      "label": "Weighted orders"
    },
    {
      "id": "round_robin",
      "label": "Round robin"
    },
    {
      "id": "random",
      "label": "Random"
    },
    {
      "id": "cap",
      "label": "Capacity"
    },
    {
      "id": "best_ar",
      "label": "Approval rate"
    },
    {
      "id": "velocity",
      "label": "Daily volume"
    },
    {
      "id": "lru",
      "label": "Least recently used"
    },
    {
      "id": "cost",
      "label": "Lowest fees"
    },
    {
      "id": "smart",
      "label": "Smart volume"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `atris[]` | object[] | ATRI rows with members[] (see POST /v1/payment-atris). |
| `strategies` | object[] | The ten dispatch strategies, {id, label}. |

**Errors**

- `400` {"error":"Invalid method"}: method is not wallet or wire.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Sorted by name, then id. An ATRI with no active member exists but cannot route a payment.
- is_default marks the account default of its method, used by a store that has no explicit wallet or wire setting (GET /v1/checkouts/:shopId/payment-methods).

##### `POST /v1/payment-atris`

**Scope** `routing.write` - **Create a wallet or wire ATRI**

Creates a payment ATRI for one method and, optionally, its members, in one transaction. The new ATRI is not the default; choose it with POST /v1/payment-atris/:id/default or select it on a store.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `method` | string | **yes** | wallet or wire. Fixed for the life of the ATRI. |
| `name` | string | **yes** | Trimmed, 1 to 128 characters. |
| `description` | string \| null | no | At most 1024 characters. |
| `active` | boolean; default `True` | no | Inactive ATRIs never route. |
| `dispatchStrategy` | string; default `volume` | no | random, cap, volume, orders, round_robin, best_ar, velocity, lru, cost or smart. |
| `members` | object[] | no | Complete membership, at most 1000 rows; each sourceId once ("Duplicate payment source" otherwise). It REPLACES every existing member. |
| `members[].sourceId` | string (uuid) | **yes** | A wallet provider id (GET /v1/wallet-providers) for a wallet ATRI, a bank account id (GET /v1/bank-accounts) for a wire ATRI. Must belong to this account. |
| `members[].position` | integer | **yes** | Order of the member, 0 or more. |
| `members[].active` | boolean; default `True` | no | An inactive member never routes. |
| `members[].weight` | number \| null | no | 0 to 100 for the weighted strategies; 0 stops routing to the member; null = no weight. |
| `members[].dailyLimit` | integer; default `0` | no | Orders per day, 0 to 1000000; 0 = no limit. |
| `members[].monthlyCapMinor` | integer; default `0` | no | Monthly volume cap in minor units (reserved or successful volume); 0 = no cap. |

**Request body**

```json
{
  "method": "wallet",
  "name": "Wallet ATRI",
  "description": null,
  "active": true,
  "dispatchStrategy": "volume",
  "members": [
    {
      "sourceId": "00000000-0000-4000-8000-000000000201",
      "position": 0,
      "active": true,
      "weight": 100,
      "dailyLimit": 0,
      "monthlyCapMinor": 0
    }
  ]
}
```

**Response**

```json
{
  "atri": {
    "id": "00000000-0000-4000-8000-000000000101",
    "owner_email": "owner@example.com",
    "method": "wallet",
    "name": "Wallet ATRI",
    "description": null,
    "active": true,
    "is_default": true,
    "dispatch_strategy": "volume",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-24T09:00:00.000Z",
    "members": [
      {
        "atri_id": "00000000-0000-4000-8000-000000000101",
        "source_id": "00000000-0000-4000-8000-000000000201",
        "position": 0,
        "active": true,
        "weight": 100,
        "daily_limit": 0,
        "monthly_cap_minor": 0,
        "source_name": "Demo wallet",
        "source_active": true,
        "currency": null,
        "discount_fee_bps": 0,
        "transaction_fee_cents": 0
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The ATRI row: id, owner_email, method, name, description, active, is_default, dispatch_strategy, created_at, updated_at, and members[]. |
| `atri.members[]` | object[] | atri_id, source_id, position, active, weight, daily_limit, monthly_cap_minor, with the source's source_name, source_active, currency (bank accounts only, else null), discount_fee_bps and transaction_fee_cents; ordered by position. |

**Errors**

- `400` {"error":"Invalid ATRI","details":<zod flatten>}: a missing or invalid field, an unknown key (strict body), a duplicate sourceId.
- `400` {"error":"Choose payment sources from this account"}: a member sourceId is not a wallet (wallet ATRI) or bank account (wire ATRI) of this account.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Answers 201.
- Members of the other method's source type are refused: a wallet ATRI takes wallet providers only, a wire ATRI bank accounts only.

##### `PATCH /v1/payment-atris/:id`

**Scope** `routing.write` - **Edit a wallet or wire ATRI**

Updates the name, description, active flag or strategy of a payment ATRI and, when members is sent, replaces its whole membership, in one transaction. Fields left out keep their value.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Payment ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed, 1 to 128 characters. |
| `description` | string \| null | no | At most 1024 characters; null clears it. |
| `active` | boolean | no | Deactivating keeps is_default set, but an inactive ATRI is never used as the store default. |
| `dispatchStrategy` | string | no | random, cap, volume, orders, round_robin, best_ar, velocity, lru, cost or smart. |
| `members` | object[] | no | Complete membership, at most 1000 rows; each sourceId once ("Duplicate payment source" otherwise). It REPLACES every existing member. |
| `members[].sourceId` | string (uuid) | **yes** | A wallet provider id (GET /v1/wallet-providers) for a wallet ATRI, a bank account id (GET /v1/bank-accounts) for a wire ATRI. Must belong to this account. |
| `members[].position` | integer | **yes** | Order of the member, 0 or more. |
| `members[].active` | boolean; default `True` | no | An inactive member never routes. |
| `members[].weight` | number \| null | no | 0 to 100 for the weighted strategies; 0 stops routing to the member; null = no weight. |
| `members[].dailyLimit` | integer; default `0` | no | Orders per day, 0 to 1000000; 0 = no limit. |
| `members[].monthlyCapMinor` | integer; default `0` | no | Monthly volume cap in minor units (reserved or successful volume); 0 = no cap. |

**Request body**

```json
{
  "name": "Wire pool",
  "dispatchStrategy": "round_robin"
}
```

**Response**

```json
{
  "atri": {
    "id": "00000000-0000-4000-8000-000000000101",
    "owner_email": "owner@example.com",
    "method": "wire",
    "name": "Wire pool",
    "description": null,
    "active": true,
    "is_default": false,
    "dispatch_strategy": "round_robin",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-24T09:00:00.000Z",
    "members": []
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The ATRI row: id, owner_email, method, name, description, active, is_default, dispatch_strategy, created_at, updated_at, and members[]. |
| `atri.members[]` | object[] | atri_id, source_id, position, active, weight, daily_limit, monthly_cap_minor, with the source's source_name, source_active, currency (bank accounts only, else null), discount_fee_bps and transaction_fee_cents; ordered by position. |

**Errors**

- `400` {"error":"Invalid ATRI","details":<zod flatten>}: an invalid field or an unknown key (method cannot be changed).
- `400` {"error":"Choose payment sources from this account"}: a member sourceId is not a wallet (wallet ATRI) or bank account (wire ATRI) of this account.
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: the path id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"ATRI not found"}: unknown id, or an ATRI of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Sending members: [] removes every member.

##### `DELETE /v1/payment-atris/:id`

**Scope** `routing.write` - **Delete an unused ATRI**

Deletes a payment ATRI and its members when nothing uses it. Answers 204 with no body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Payment ATRI id. |

**Response**

No example body: see the purpose above for what the response carries.

**Errors**

- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: the path id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"ATRI not found"}: unknown id, or an ATRI of another account.
- `409` {"error":"This ATRI is in use. Deactivate it or select another source first."}: it is the default of its method, a store uses it, or a payment was already routed through it.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An ATRI with routing history can never be deleted: deactivate it instead (PATCH /v1/payment-atris/:id with active false).

##### `POST /v1/payment-atris/:id/default`

**Scope** `routing.write` - **Make an ATRI the default of its method**

Makes an active payment ATRI the account default for its method (wallet or wire) and clears the previous default of that method. Stores with an explicit setting keep it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Payment ATRI id. |

**Response**

```json
{
  "ok": true,
  "is_default": true
}
```

**Errors**

- `400` {"error":"Activate the ATRI first"}: the ATRI is inactive.
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: the path id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"ATRI not found"}: unknown id, or an ATRI of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- No body is read.

##### `PUT /v1/payment-atris/:id/members`

**Scope** `routing.write` - **Replace the members of an ATRI**

Replaces the complete membership of a payment ATRI in one transaction.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Payment ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `members` | object[] | **yes** | Complete membership, at most 1000 rows; each sourceId once ("Duplicate payment source" otherwise). It REPLACES every existing member. |
| `members[].sourceId` | string (uuid) | **yes** | A wallet provider id (GET /v1/wallet-providers) for a wallet ATRI, a bank account id (GET /v1/bank-accounts) for a wire ATRI. Must belong to this account. |
| `members[].position` | integer | **yes** | Order of the member, 0 or more. |
| `members[].active` | boolean; default `True` | no | An inactive member never routes. |
| `members[].weight` | number \| null | no | 0 to 100 for the weighted strategies; 0 stops routing to the member; null = no weight. |
| `members[].dailyLimit` | integer; default `0` | no | Orders per day, 0 to 1000000; 0 = no limit. |
| `members[].monthlyCapMinor` | integer; default `0` | no | Monthly volume cap in minor units (reserved or successful volume); 0 = no cap. |

**Request body**

```json
{
  "members": [
    {
      "sourceId": "00000000-0000-4000-8000-000000000201",
      "position": 0,
      "active": true,
      "weight": 100,
      "dailyLimit": 0,
      "monthlyCapMinor": 0
    }
  ]
}
```

**Response**

```json
{
  "atri": {
    "id": "00000000-0000-4000-8000-000000000101",
    "owner_email": "owner@example.com",
    "method": "wallet",
    "name": "Wallet ATRI",
    "description": null,
    "active": true,
    "is_default": true,
    "dispatch_strategy": "volume",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-24T09:00:00.000Z",
    "members": [
      {
        "atri_id": "00000000-0000-4000-8000-000000000101",
        "source_id": "00000000-0000-4000-8000-000000000201",
        "position": 0,
        "active": true,
        "weight": 100,
        "daily_limit": 0,
        "monthly_cap_minor": 0,
        "source_name": "Demo wallet",
        "source_active": true,
        "currency": null,
        "discount_fee_bps": 0,
        "transaction_fee_cents": 0
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The ATRI row: id, owner_email, method, name, description, active, is_default, dispatch_strategy, created_at, updated_at, and members[]. |
| `atri.members[]` | object[] | atri_id, source_id, position, active, weight, daily_limit, monthly_cap_minor, with the source's source_name, source_active, currency (bank accounts only, else null), discount_fee_bps and transaction_fee_cents; ordered by position. |

**Errors**

- `400` {"error":"Invalid members","details":<zod flatten>}: members missing, an invalid row, a duplicate sourceId, or another key in the body.
- `400` {"error":"Choose payment sources from this account"}: a member sourceId is not a wallet (wallet ATRI) or bank account (wire ATRI) of this account.
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: the path id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"ATRI not found"}: unknown id, or an ATRI of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Daily limits count orders; monthlyCapMinor caps the reserved or successful volume of the month.

#### Filters

The account filters and rules (traffic, cards, routing, subscriptions, alerts) and the rejections log of the charges they refused.

##### `GET /v1/filters`

**Scope** `routing.read` - **List the account filters and rules**

Returns the account's seven pre-charge filters and rules with their enabled flag and config: email_provider (only personal e-mail domains in config.providers are accepted), max_order_per_ip (refuse when the IP already has config.limit approvals in config.windowDays days), device_mobile_only (device type allowlist), acquisition_required (traffic type allowlist), commercial_card_block (refuse cards whose BIN level contains a keyword), velocity_guard (trailing-hour limits per IP, card and e-mail) and credential_cutoff (a gateway whose credentials are refused is cut from every ATRI after config.consecutive failures). Read-only.

*No parameters.*

**Response**

```json
{
  "filters": [
    {
      "key": "email_provider",
      "enabled": false,
      "config": {
        "providers": [
          "gmail.com",
          "yahoo.com",
          "outlook.com",
          "icloud.com"
        ]
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "max_order_per_ip",
      "enabled": true,
      "config": {
        "limit": 1,
        "windowDays": 30
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "device_mobile_only",
      "enabled": false,
      "config": {
        "allowed": []
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "acquisition_required",
      "enabled": false,
      "config": {
        "allowed": []
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "commercial_card_block",
      "enabled": false,
      "config": {
        "levelKeywords": [
          "BUSINESS",
          "CORPORATE",
          "COMMERCIAL"
        ]
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "velocity_guard",
      "enabled": false,
      "config": {
        "maxDeclinesPerIpPerHour": 0,
        "maxOrdersPerCardPerHour": 0,
        "maxOrdersPerEmailPerHour": 0
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    },
    {
      "key": "credential_cutoff",
      "enabled": true,
      "config": {
        "consecutive": 3
      },
      "updated_at": "2026-11-20T09:14:02.318Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `filters` | object[] | One row per filter from the `transaction_filters` table. Always the same six keys in practice (seeded by migrations 054/055/060). NOT sorted — the query has no ORDER BY, so array order is whatever Postgres returns and may change between calls. Do not index positionally; match on `key`. |
| `filters[].key` | string | Stable filter slug: `email_provider`, `max_order_per_ip`, `device_mobile_only`, `acquisition_required`, `commercial_card_block`, `velocity_guard`. |
| `filters[].enabled` | boolean | Whether the filter runs on the charge hot path. All six ship disabled (`false`) by default. |
| `filters[].config` | object | Free-form jsonb. Shape is NOT enforced anywhere and differs per filter: `email_provider` -> {providers: string[]}; `max_order_per_ip` -> {limit: number, windowDays: number}; `device_mobile_only` -> {allowed: ('desktop'\|'mobile'\|'tablet'\|'other')[]}; `acquisition_required` -> {allowed: ('meta'\|'tiktok'\|'google'\|'other'\|'organic')[]} (v3.9.18 google: a gclid / gbraid / wbraid, the checkout's label google, or utm_source=google with a paid utm_medium cpc \| ppc \| paid); `commercial_card_block` -> {levelKeywords: string[]}; `velocity_guard` -> {maxDeclinesPerIpPerHour, maxOrdersPerCardPerHour, maxOrdersPerEmailPerHour, samplePct?}. No money fields and no 0..1 rates on this route (`samplePct` is 0..100, a percent, not a ratio). |
| `filters[].updated_at` | string (ISO-8601 datetime) | Last write to the row. Comes back as a JSON ISO string with milliseconds and a trailing Z. |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A new account is seeded with the defaults on its first read: every filter off, credential_cutoff on with consecutive 3.
- Served from a 30-second per-process cache. If the database read fails the route still answers 200 with the last cached rows or an empty list (the filters fail open); an empty filters array therefore means the read failed, not that the account has no filters.
- `enabled: true` alone does not block anything: device_mobile_only and acquisition_required accept everything while config.allowed is empty; a velocity_guard limit of 0 is off.
- device_mobile_only is a legacy name: it is a general device allowlist over desktop, mobile, tablet, other.
- Filters run on initial charges only, never on rebills.

##### `PATCH /v1/filters/:key`

**Scope** `routing.write` - **Update an account filter**

Turns one of the account's filters on or off and/or replaces its config. The config is checked against the shape of that filter before it is saved; the change applies on the charge path of this server process at once and on the others within 30 seconds.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | enum: email_provider \| max_order_per_ip \| device_mobile_only \| acquisition_required \| commercial_card_block \| velocity_guard \| credential_cutoff | **yes** | Filter to update. Checked before the body; anything else answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | no | Turn the filter on or off. At least one of enabled or config is required. |
| `config` | object | no | Replaces the whole config (no merge). Shape per key, every field optional, unknown fields refused: email_provider {providers: string[]}; max_order_per_ip {limit: positive integer, windowDays: positive integer}; device_mobile_only {allowed: string[] of desktop, mobile, tablet, other}; acquisition_required {allowed: string[] of meta, tiktok, snapchat, google, pinterest, applovin, x, other, organic}; commercial_card_block {levelKeywords: string[], case-insensitive substrings of the BIN level}; credential_cutoff {consecutive: positive integer}; velocity_guard: free object (maxDeclinesPerIpPerHour, maxOrdersPerCardPerHour, maxOrdersPerEmailPerHour: integers, 0 = off; samplePct: 0-100 share of orders the guard runs on, default 100). |
| `config.providers` | string[] | no | email_provider: accepted e-mail domains (an empty or missing list falls back to the built-in consumer list). |
| `config.limit` | integer (> 0) | no | max_order_per_ip: approvals allowed per IP in the window (read as at least 1). |
| `config.windowDays` | integer (> 0) | no | max_order_per_ip: window in days (read as 30 when absent). |
| `config.allowed` | string[] | no | device_mobile_only: accepted device types; acquisition_required: accepted traffic types. Empty = accept all. |
| `config.levelKeywords` | string[] | no | commercial_card_block: BIN level substrings treated as commercial cards. |
| `config.consecutive` | integer (> 0) | no | credential_cutoff: consecutive credential failures before the gateway is cut. |
| `config.maxDeclinesPerIpPerHour` | integer (>= 0) | no | velocity_guard: declined or refused attempts allowed from one IP in the trailing hour (0 = off). |
| `config.maxOrdersPerCardPerHour` | integer (>= 0) | no | velocity_guard: orders allowed on one card in the trailing hour (0 = off). |
| `config.maxOrdersPerEmailPerHour` | integer (>= 0) | no | velocity_guard: orders allowed for one e-mail in the trailing hour (0 = off). |
| `config.samplePct` | number (0-100); default `100` | no | velocity_guard: percentage of orders the guard runs on, bucketed by e-mail, else IP, else card. |

**Request body**

```json
{
  "enabled": true,
  "config": {
    "limit": 2,
    "windowDays": 7
  }
}
```

**Response**

```json
{
  "filter": {
    "key": "max_order_per_ip",
    "enabled": true,
    "config": {
      "limit": 2,
      "windowDays": 7
    },
    "updated_at": "2026-11-24T10:31:47.512Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `filter` | object | The updated row, straight from the SQL `returning` clause. Note the singular key `filter` — NOT `filters` as on the list route. |
| `filter.key` | string | Echo of the path key. |
| `filter.enabled` | boolean | Post-update value. |
| `filter.config` | object | Post-update jsonb, exactly what you sent (or the untouched previous value if you only sent `enabled`). No money fields; `samplePct` is 0..100 percent, not a 0..1 ratio. |
| `filter.updated_at` | string (ISO-8601 datetime) | Server `now()` at write time, as an ISO string. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when enabled is not a boolean, config is not an object, or neither is sent (`Nothing to update`); `{"error":"This <key> configuration cannot be read, so it is not saved","details":{...}}` when config does not match the shape of that filter (details names the field).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `404` `{"error":"Unknown filter"}` when :key is not one of the seven keys; `{"error":"Filter not found"}` when the row could not be updated.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- config is a full replace: sending {"config":{"limit":5}} to max_order_per_ip drops windowDays (the filter then reads 30). Read GET /v1/filters first and send the whole object.
- Sending only {"enabled":false} keeps the config, so re-enabling restores it.
- velocity_guard config is not shape-checked; its reader clamps each field.

##### `GET /v1/rejections`

**Scope** `operations.read` - **Read the rejections log**

Every charge the platform refused before any gateway on this account (blacklist, filter, velocity guard, BIN scrub, card pre-check, card cooldown, 3DS policy, abandoned 3DS challenge, checkout limit, test card), newest first and paged, plus per-family counts (last 24 hours and total). A rejection is not a decline and has no transaction row. Rows are kept 30 days.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer (1-10000); default `100` | no | Page size. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |
| `family` | enum: blacklist \| filter \| velocity_guard \| bin_scrub \| card_precheck \| card_cooldown \| three_ds_policy \| three_ds_abandoned \| checkout_limit \| test_card | no | Restrict rows and total to one family. |
| `since` | ISO 8601 datetime | no | Only rows created at or after this instant (full datetime with Z offset, e.g. 2026-11-24T00:00:00.000Z; a bare date is refused). |
| `orderId` | string (1-128, trimmed) | no | Exact merchant order id. |
| `order_id` | string (1-128, trimmed) | no | Alias of orderId; orderId wins when both are sent. |
| `flow` | enum: initial \| rebill | no | Flow of the refused charge. |
| `filterKey` | enum: email_provider \| max_order_per_ip \| device_mobile_only \| acquisition_required \| commercial_card_block \| velocity_guard \| credential_cutoff | no | The filter that fired (set on family filter and velocity_guard rows). |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000021",
      "created_at": "2026-11-24T09:58:11.402Z",
      "order_id": "ORDER-1001",
      "trip_id": "00000000-0000-4000-8000-000000000031",
      "family": "velocity_guard",
      "reason": "Blocked by velocity guard: 7 declined or refused attempts from this IP in the last hour (limit 6)",
      "channel": "checkout",
      "flow": "initial",
      "masked_card": "411111..1111",
      "ip": "203.0.113.7",
      "amount_cents": 4999,
      "currency": "USD",
      "storefront_url": "https://shop.example.com",
      "bin": "411111",
      "filter_key": "velocity_guard",
      "api_key_id": "00000000-0000-4000-8000-000000000041"
    }
  ],
  "total": 1,
  "stats": [
    {
      "family": "velocity_guard",
      "hits_24h": 1,
      "hits_total": 9
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | The page of rejections, ordered `created_at desc` (newest first). Length <= `limit`. |
| `rows[].id` | string (uuid) | Primary key of the `charge_rejections` row. |
| `rows[].created_at` | string (ISO-8601 datetime) | When cocoapi refused the charge. The sort column. |
| `rows[].order_id` | string | The merchant's order id (text). No transaction carries it unless the customer re-submitted and got through. |
| `rows[].trip_id` | string (uuid) \| null | The ATRI the order was routed to, when routing had been resolved before the refusal. |
| `rows[].family` | string | Why cocoapi refused it: blacklist \| filter \| velocity_guard \| bin_scrub \| card_precheck \| card_cooldown \| three_ds_policy \| three_ds_abandoned (a swept 3DS park — the challenge was never completed; the row carries the provider fee). Match on this, never on `reason`. |
| `rows[].reason` | string | The INTERNAL reason — the text the old transaction row used to carry. For an interceptor filter the customer received a generic decline instead; for every other family it is the `declineReason` the caller got. A 3DS policy refusal may carry the suffix ' (3DS fee X.XX)' — the provider fee that was paid for nothing. |
| `rows[].channel` | string \| null | The order's channel as sent (`checkout`, `rebill`, `dashboard`, `retry`, …). |
| `rows[].flow` | string \| null | `initial` \| `rebill`. |
| `rows[].masked_card` | string \| null | first6..last4 of the card, e.g. `414720..1188`. Never a PAN; the keyed card hash and the hashed e-mail are stored but never returned. |
| `rows[].ip` | string \| null | The customer's IP as supplied (what the IP velocity rule counts). |
| `rows[].amount_cents` | integer \| null | The refused amount, integer cents. |
| `rows[].storefront_url` | string \| null | The order's storefront URL as sent. |
| `rows[].bin` | string \| null | First 6 digits of the PAN (BIN scrub / analytics). |
| `rows[].filter_key` | string \| null | The interceptor filter that fired — only on family `filter` / `velocity_guard`; null otherwise. |
| `rows[].api_key_id` | string (uuid) \| null | The API key that sent the order (null for an internal charge). |
| `total` | integer | Count of ALL rows matching the filters, before limit/offset (window function read off the first returned row — 0 when the page is past the end). |
| `stats` | object[] | Per-family counts over the account's WHOLE log (30-day retention), ordered `hits_total desc`. Independent of every filter and of the paging. |
| `stats[].family` | string | Rejection family. A family with no row is absent, not zero. |
| `stats[].hits_24h` | integer | Rejections in the trailing 24 hours (`created_at >= now() - interval '24 hours'`). |
| `stats[].hits_total` | integer | Rejections kept by the retention (30 days) for that family. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when limit / offset is out of bounds, family / flow / filterKey is not an allowed value, since is not a full ISO datetime, or orderId is empty or longer than 128 characters.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- These order ids are not in GET /v1/transactions and never count in approval rates.
- stats is computed over the 30-day retention and ignores the filters.
- total is read from the first row: an offset past the end returns total 0. Use since to window a pull rather than deep offsets.
- Cards are first6..last4 only. A 3DS challenge that is merely pending is not a rejection and is not listed.

#### BIN intelligence

BIN profiles (mapping, scrubbing, 3-D Secure), their rules, generation and import jobs, analytics, decisions, the card catalogue and the scrub lists.

- Analytics totals (per rule): the browser sums the arms of `GET /v1/bin-profiles/:id/analytics` and recomputes approval rate (sum(approved) / sum(completed)) and lift; only `evaluations` and `baseline_atri` come as is.
- Decision log page totals ("x applied, y% of z matched", approval rate) are computed from the page of `GET /v1/bin-profiles/:id/decisions`.
- "Never reached" rules: a rule shadowed by an earlier rule of the same profile is flagged in the browser from the ordered rules of `GET /v1/bin-profiles/:id/rules`.
- Server files: `GET /v1/bin-profiles/export.csv`, `GET /v1/bin-profiles/:id/rules/export.csv`, `GET /v1/bin-profiles/csv-template`. Every other export is built in the browser.

##### `GET /v1/bin-catalog`

**Scope** `routing.read` - **Read the account card catalogue**

The account's own pick list for BIN rules: every canonical issuer (kind=issuer) or 6-digit BIN (kind=bin) the account has seen on a live card charge, ranked by its own order volume, searched and paged on the server. kind=country and kind=issuer_country list the whole ISO country table ranked by the account's orders of the last 90 days (customer country, or the issuing country of the card BIN).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: issuer \| bin \| country \| issuer_country | **yes** | Which catalogue to read. |
| `q` | string (0-120); default `""` | no | Search. bin: digits-only prefix (non-digits are stripped). issuer: case-insensitive substring of the key, display name or any alias label. country kinds: code or name. |
| `limit` | integer (1-500); default `50` | no | Page size. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |

**Response**

```json
{
  "rows": [
    {
      "kind": "issuer",
      "value": "EXAMPLE BANK",
      "display_name": "Example Bank",
      "orders": 17176,
      "bins": 23,
      "first_seen": "2026-06-09T14:02:11.000Z",
      "last_seen": "2026-11-20T06:41:03.000Z"
    }
  ],
  "total": 2542,
  "limit": 50,
  "offset": 0,
  "synced_to": "2026-11-23T06:50:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `rows[].kind` | enum: issuer\|bin\|country\|issuer_country |  |
| `rows[].value` | string | The canonical issuer key, the 6-digit BIN or the ISO alpha-2 code — exactly what a rule's match_value stores. |
| `rows[].display_name` | string \| null | issuer: the alias row's display name, else the most frequent raw bin_info label, else the key. bin: null. country / issuer_country: the English short name. |
| `rows[].orders` | integer | issuer / bin: the account's live card rows ever seen on the value (attempts, any status) — the ranking. country / issuer_country: the account's live rows of the last 90 days (0 = unseen). |
| `rows[].bins` | integer \| null | issuer: the account's enriched BINs behind the key. Others: null. |
| `rows[].first_seen` | timestamptz \| null | null on an unseen country. |
| `rows[].last_seen` | timestamptz \| null | null on an unseen country. |
| `rows[].issuer` | string \| null | kind=bin only: the raw bin_info issuer label (null when the BIN is not enriched yet). |
| `rows[].issuer_key` | string \| null | kind=bin only: the CANONICAL issuer key of the BIN (the same fold the engine uses) — what the editor's BIN ↔ issuer conflict check compares; null when unknown / not enriched / an excluded programme. |
| `rows[].brand` | string \| null | kind=bin only (bin_info). |
| `rows[].type` | string \| null | kind=bin only (bin_info: debit / credit / prepaid…). |
| `rows[].country_code` | string \| null | kind=bin only (bin_info). |
| `total` | integer | Rows matching q (the picker shows "N more — refine the search"); country / issuer_country: at most 250. |
| `limit` | integer |  |
| `offset` | integer |  |
| `synced_to` | timestamptz \| null | issuer / bin: the account's cursor — every live row with created_at <= synced_to is counted (the daily pass bounds at now − 70 min, the 3DS session lifetime — a parked challenge completed late is still counted); null = never built (migration 145 builds every account; a brand-new account waits for the next pass or POST …/sync). country / issuer_country: always null (nothing is synced). |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when kind is missing or not one of the four values, q is longer than 120 characters, or limit / offset is out of bounds.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Customer reads are busy. Please retry shortly."}` for the country kinds when the read queue is full.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the bounded read (15 s for issuer / bin, 25 s for the country kinds) expires.

**Gotchas**

- Always ordered by orders descending, then value ascending; there is no sort parameter.
- orders counts live card transactions of any status (attempts), not approvals.
- kind=bin rows also carry issuer, issuer_key, brand, type and country_code from the BIN referential (null when the BIN is not enriched yet).
- The issuer and bin kinds are maintained by a daily sync and by POST /v1/bin-catalog/sync; synced_to is the cursor of the last sync (null before the first). The country kinds are computed live, list every ISO code (unseen ones with 0 orders and null first_seen / last_seen) and have synced_to null.

##### `GET /v1/bin-catalog/jobs`

**Scope** `routing.read` - **List BIN catalogue jobs**

Lists the caller's last 20 BIN catalogue sync jobs, queued and running first, then newest first.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "3f6b1d2a-8c4e-4a71-b5d9-0e2c7a9f1b34",
      "requestId": "0b9e4c7d-2a1f-4e6b-8d3c-5f7a1e2b9c40",
      "status": "running",
      "phase": "scan",
      "full": false,
      "scanned": 1000,
      "matched": 805,
      "pages": 1,
      "error": null,
      "createdAt": "2026-11-20T14:00:00.000Z",
      "updatedAt": "2026-11-20T14:00:09.412Z",
      "finishedAt": null,
      "syncedTo": "2026-11-20 13:59:58.123456+00"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | At most 20 jobs. |
| `jobs[].id` | string (uuid) | Job id. |
| `jobs[].requestId` | string (uuid) | The requestId sent with POST /v1/bin-catalog/sync (async: true). |
| `jobs[].status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `jobs[].phase` | string | Current worker phase (for example scan, copy, done). |
| `jobs[].full` | boolean | True for a full rebuild (the account's catalogue rows are recounted from every live charge). |
| `jobs[].scanned` | integer | Charges scanned so far. |
| `jobs[].matched` | integer | Charges that contributed a BIN or issuer so far. |
| `jobs[].pages` | integer | Pages committed so far. |
| `jobs[].error` | string \| null | Failure reason when status is failed. |
| `jobs[].createdAt` | string (ISO 8601) | Creation time. |
| `jobs[].updatedAt` | string (ISO 8601) | Last progress time. |
| `jobs[].finishedAt` | string \| null | End time, null while queued or running. |
| `jobs[].syncedTo` | string | Upper time bound of the charges the job covers (timestamp text with microseconds). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Catalogue access changed; create a new sync with current permissions"} when the caller's account, grants or key changed since the job scope was taken, or the key belongs to a sub-account login rather than the account owner.
- `404` {"error":"Catalogue jobs unavailable"} when the deployment has no job storage.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- No pagination: only the 20 most relevant jobs are returned.
- Progress has no percentage: scanned and matched grow until status leaves running.
- Jobs are visible only to the caller that created them (the same API key or login, with the same account scope) and as scheduler jobs of the account; a job created by another key of the account is invisible (404).

##### `GET /v1/bin-catalog/jobs/:id`

**Scope** `routing.read` - **Get a BIN catalogue job**

Reads the progress of one BIN catalogue sync job. Poll it after POST /v1/bin-catalog/sync with async: true until status is success, failed or cancelled.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id (jobId of the sync answer). |

**Response**

```json
{
  "job": {
    "id": "3f6b1d2a-8c4e-4a71-b5d9-0e2c7a9f1b34",
    "requestId": "0b9e4c7d-2a1f-4e6b-8d3c-5f7a1e2b9c40",
    "status": "running",
    "phase": "scan",
    "full": false,
    "scanned": 1000,
    "matched": 805,
    "pages": 1,
    "error": null,
    "createdAt": "2026-11-20T14:00:00.000Z",
    "updatedAt": "2026-11-20T14:00:09.412Z",
    "finishedAt": null,
    "syncedTo": "2026-11-20 13:59:58.123456+00"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job. |
| `job.id` | string (uuid) | Job id. |
| `job.requestId` | string (uuid) | The requestId sent with POST /v1/bin-catalog/sync (async: true). |
| `job.status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `job.phase` | string | Current worker phase (for example scan, copy, done). |
| `job.full` | boolean | True for a full rebuild (the account's catalogue rows are recounted from every live charge). |
| `job.scanned` | integer | Charges scanned so far. |
| `job.matched` | integer | Charges that contributed a BIN or issuer so far. |
| `job.pages` | integer | Pages committed so far. |
| `job.error` | string \| null | Failure reason when status is failed. |
| `job.createdAt` | string (ISO 8601) | Creation time. |
| `job.updatedAt` | string (ISO 8601) | Last progress time. |
| `job.finishedAt` | string \| null | End time, null while queued or running. |
| `job.syncedTo` | string | Upper time bound of the charges the job covers (timestamp text with microseconds). |

**Errors**

- `400` {"error":"Invalid job ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Catalogue access changed; create a new sync with current permissions"} when the caller's account, grants or key changed since the job scope was taken, or the key belongs to a sub-account login rather than the account owner.
- `404` {"error":"Catalogue job not found"}; {"error":"Catalogue jobs unavailable"} when the deployment has no job storage.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- The new catalogue is published only after every page commits; until then pickers read the previous one.
- Jobs are visible only to the caller that created them (the same API key or login, with the same account scope) and as scheduler jobs of the account; a job created by another key of the account is invisible (404).

##### `POST /v1/bin-catalog/jobs/:id/cancel`

**Scope** `routing.write` - **Cancel a BIN catalogue job**

Cancels a queued or running BIN catalogue sync job and returns it. A job already finished is returned unchanged. The previously published catalogue stays in use.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "3f6b1d2a-8c4e-4a71-b5d9-0e2c7a9f1b34",
    "requestId": "0b9e4c7d-2a1f-4e6b-8d3c-5f7a1e2b9c40",
    "status": "cancelled",
    "phase": "done",
    "full": false,
    "scanned": 1000,
    "matched": 805,
    "pages": 1,
    "error": null,
    "createdAt": "2026-11-20T14:00:00.000Z",
    "updatedAt": "2026-11-20T14:00:09.412Z",
    "finishedAt": "2026-11-20T14:01:02.000Z",
    "syncedTo": "2026-11-20 13:59:58.123456+00"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after cancellation (status cancelled, phase done, when it was queued or running). |
| `job.id` | string (uuid) | Job id. |
| `job.requestId` | string (uuid) | The requestId sent with POST /v1/bin-catalog/sync (async: true). |
| `job.status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `job.phase` | string | Current worker phase (for example scan, copy, done). |
| `job.full` | boolean | True for a full rebuild (the account's catalogue rows are recounted from every live charge). |
| `job.scanned` | integer | Charges scanned so far. |
| `job.matched` | integer | Charges that contributed a BIN or issuer so far. |
| `job.pages` | integer | Pages committed so far. |
| `job.error` | string \| null | Failure reason when status is failed. |
| `job.createdAt` | string (ISO 8601) | Creation time. |
| `job.updatedAt` | string (ISO 8601) | Last progress time. |
| `job.finishedAt` | string \| null | End time, null while queued or running. |
| `job.syncedTo` | string | Upper time bound of the charges the job covers (timestamp text with microseconds). |

**Errors**

- `400` {"error":"Invalid job ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Catalogue access changed; create a new sync with current permissions"} when the caller's account, grants or key changed since the job scope was taken, or the key belongs to a sub-account login rather than the account owner.
- `404` {"error":"Catalogue job not found"}; {"error":"Catalogue jobs unavailable"}.
- `409` {"error":"Catalogue page is committing; retry cancellation"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- No body is read.
- Answers 409 while a page is being committed: retry after a moment.
- Idempotent: cancelling a finished job returns it as it is.
- Jobs are visible only to the caller that created them (the same API key or login, with the same account scope) and as scheduler jobs of the account; a job created by another key of the account is invisible (404).

##### `GET /v1/bin-catalog/jobs/capabilities`

**Scope** `routing.read` - **BIN catalogue job capability**

Says whether background BIN catalogue syncs can be submitted (POST /v1/bin-catalog/sync with async: true). Read-only.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | True when background jobs run on this deployment and the catalogue job storage exists. When false, use the synchronous POST /v1/bin-catalog/sync (async omitted). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Catalogue access changed; create a new sync with current permissions"} when the caller's account, grants or key changed since the job scope was taken, or the key belongs to a sub-account login rather than the account owner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Required storage for BIN catalog jobs is unavailable. Complete the current database migrations.","requestId":"<id>"} when background jobs run but the job storage is missing.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- When background jobs run but the job storage is missing, the answer is a 503 {"error":"Required storage for BIN catalog jobs is unavailable. Complete the current database migrations.","requestId":"<id>"} (the server reports a missing migration), not enabled:false.

##### `POST /v1/bin-catalog/sync`

**Scope** `routing.write` - **Sync the account card catalogue**

Refreshes the account's card catalogue now instead of waiting for the daily pass. Two modes: without async the pass runs inline and answers 200 with its counts; with async true and a requestId it admits a resumable background job and answers 202 with the job (follow it with GET /v1/bin-catalog/jobs/:id).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `full` | boolean; default `false` | no | true drops the account's rows and recounts every live transaction from the start (use after a gateway moved between accounts). A background job also goes full on its own when there is no cursor yet or the account's sources changed. |
| `async` | boolean; default `false` | no | true admits a background job instead of running inline. Requires requestId. |
| `requestId` | uuid | no | Idempotency key of the background job, required when async is true. Replaying the same requestId with the same input returns the same job. |

**Request body**

```json
{
  "full": false,
  "async": true,
  "requestId": "00000000-0000-4000-8000-0000000000aa"
}
```

**Response**

```json
// inline (async omitted or false): 200
{"full":false,"bins_upserted":312,"issuers_upserted":2542,"issuers_removed":0,"synced_to":"2026-11-24T08:50:00.000Z"}

// async true: 202
{"jobId":"00000000-0000-4000-8000-0000000000bb","job":{"id":"00000000-0000-4000-8000-0000000000bb","requestId":"00000000-0000-4000-8000-0000000000aa","status":"queued","phase":"scan","full":false,"scanned":0,"matched":0,"pages":0,"error":null,"createdAt":"2026-11-24T08:50:00.000Z"}}
```

| response field | type | description |
|---|---|---|
| `full` | boolean | true when the pass counted from the beginning (no cursor yet, or full requested). |
| `bins_upserted` | integer | BIN rows inserted or updated by this pass (0 when the window since the last pass is not open yet: two passes within 70 minutes). |
| `issuers_upserted` | integer | Issuer rows (re)derived — the whole set, every pass. |
| `issuers_removed` | integer | Issuer rows whose key folded away / was excluded since the last pass. |
| `synced_to` | timestamptz | The account's new cursor (now − 70 min, DB clock; unchanged when the window was not open). |
| `jobId, job` | object (async202 only) | Persisted job reference and current state: id,requestId,status,phase,full,scanned,matched,pages,error,createdAt,updatedAt,finishedAt,syncedTo. Scanned counts physical rows; matched counts original eligible charge rows. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body has an unknown field (strict), full or async is not a boolean, requestId is not a UUID, or async is true without requestId (`requestId required for resumable sync`).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `409` Background mode: `{"error":"Catalogue is currently busy"}` (another pass holds the account lock), `{"error":"Request ID already used with different input or permissions"}`, or `{"error":"A catalogue sync is already active","jobId":"..."}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Catalogue job migration is not available"}`, `{"error":"Resumable catalogue admission is disabled; accepted jobs remain readable and cancellable"}` (background jobs are switched off; an existing requestId still replays),.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the inline pass (25 s budget) or the job admission (15 s) expires; for a background job resend the same requestId to learn whether it was admitted.

**Gotchas**

- Only the calling account is synced.
- The inline pass is one transaction: readers never see a half-synced catalogue and a failure changes nothing. Two inline passes within about 70 minutes: the second finds no new window and counts nothing (issuer rows are still re-derived).
- For the background mode, if the answer is lost, resend the same requestId; never start a second job with a new id while one is active (409 with its jobId).

##### `GET /v1/bin-generation-jobs/:id`

**Scope** `routing.write` - **Read a BIN generation job**

Progress of one generation job: status (queued, running, ready, applied, failed or cancelled) and counters. Permissions are re-checked on every read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id from POST /v1/bin-profiles/:id/generation-jobs. |

**Response**

```json
{
  "job": {
    "id": "66666666-6666-4666-8666-666666666666",
    "request_id": "77777777-7777-4777-8777-777777777777",
    "profileId": "11111111-1111-4111-8111-111111111111",
    "mode": "bin",
    "origin": "manual",
    "status": "running",
    "processed": 1,
    "total": 2,
    "error": null,
    "cancel_requested": false,
    "expires_at": "2026-11-25T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`.
- `404` `Generation not found` (no such job, or not visible to this caller).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- `job` = {id, request_id, profileId, mode (bin|issuer), origin (manual|automatic), status (queued|running|ready|applied|failed|cancelled), processed, total, error (failure text or null), cancel_requested, expires_at}. total = the ATRIs to measure plus one final step that builds the proposals; processed counts finished steps.
- ready = proposals saved, read them with GET /v1/bin-generation-jobs/:id/result; applied = rules written; failed = see `error`.

##### `POST /v1/bin-generation-jobs/:id/apply`

**Scope** `routing.write` - **Apply the proposals of a BIN generation job**

Asks the worker to write the saved proposals of a READY job (never a fresh computation). Answers 202 with the job queued again; poll GET /v1/bin-generation-jobs/:id until status is applied or failed. The worker re-checks the profile, rules, fees, issuer definitions and permissions under the profile lock and writes the new proposals after the existing rules with source `generated:<job id>` (with replace_generated the previous generated rules of the same mode go first); manual, import, rb_sync and migration rules are never touched.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | **yes** | The enabled flag of the inserted rules (false = staged). The body must be exactly {enabled}. |

**Request body**

```json
{
  "enabled": true
}
```

**Response**

```json
{
  "job": {
    "id": "66666666-6666-4666-8666-666666666666",
    "request_id": "77777777-7777-4777-8777-777777777777",
    "profileId": "11111111-1111-4111-8111-111111111111",
    "mode": "bin",
    "origin": "manual",
    "status": "queued",
    "processed": 2,
    "total": 2,
    "error": null,
    "cancel_requested": false,
    "expires_at": "2026-11-25T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when :id is not a UUID or the body is not exactly {"enabled": <boolean>}.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`. Also `An attached ATRI is outside your grants`.
- `404` `Generation not found`.
- `409` `Preview is not ready or has expired. Generate again.`; `Application already requested with different settings`.
- `422` `Profile, rules, ownership, fees or issuer definitions changed. Generate a fresh preview.`
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Background BIN generation is unavailable` (background jobs off) or `Required storage for BIN generation is unavailable. Complete the current database migrations.`
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- `job` = {id, request_id, profileId, mode (bin|issuer), origin (manual|automatic), status (queued|running|ready|applied|failed|cancelled), processed, total, error (failure text or null), cancel_requested, expires_at}. total = the ATRIs to measure plus one final step that builds the proposals; processed counts finished steps.
- Idempotent: an applied job is returned unchanged; a repeat with the same enabled while the apply is queued or running returns the same job.
- A failed apply leaves the rules untouched and sets `error`, for example `Nothing evaluated: previous generated rules are untouched`, `Some proposals are invalid: previous generated rules are untouched`, a changed-configuration message, or `Generation permissions changed`.

##### `POST /v1/bin-generation-jobs/:id/cancel`

**Scope** `routing.write` - **Cancel a BIN generation job**

Cancels a job. A queued or ready job is cancelled at once; a running one is flagged (cancel_requested) and stops at its next heartbeat (about 20 seconds). A finished job is returned unchanged. Rules already applied stay. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "66666666-6666-4666-8666-666666666666",
    "request_id": "77777777-7777-4777-8777-777777777777",
    "profileId": "11111111-1111-4111-8111-111111111111",
    "mode": "bin",
    "origin": "manual",
    "status": "cancelled",
    "processed": 0,
    "total": 2,
    "error": null,
    "cancel_requested": true,
    "expires_at": "2026-11-25T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`.
- `404` `Generation not found`.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- `job` = {id, request_id, profileId, mode (bin|issuer), origin (manual|automatic), status (queued|running|ready|applied|failed|cancelled), processed, total, error (failure text or null), cancel_requested, expires_at}. total = the ATRIs to measure plus one final step that builds the proposals; processed counts finished steps.
- Works even when background jobs are off.

##### `GET /v1/bin-generation-jobs/:id/result`

**Scope** `routing.write` - **Read the proposals of a BIN generation job**

The saved proposals of a ready or applied job, with the diff against the profile's rules and the stored input. Never recomputed against moving traffic.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "66666666-6666-4666-8666-666666666666",
    "request_id": "77777777-7777-4777-8777-777777777777",
    "profileId": "11111111-1111-4111-8111-111111111111",
    "mode": "bin",
    "origin": "manual",
    "status": "ready",
    "processed": 2,
    "total": 2,
    "error": null,
    "cancel_requested": false,
    "expires_at": "2026-11-25T10:00:00.000Z"
  },
  "result": {
    "run": "66666666-6666-4666-8666-666666666666",
    "source": "generated:66666666-6666-4666-8666-666666666666",
    "kind": "threeds",
    "mode": "issuer",
    "dry_run": true,
    "replace_generated": true,
    "criteria": {
      "window_days": 30,
      "min_attempts": 30,
      "min_lift_pts": 8,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "trips": [
      {
        "trip_id": "44444444-4444-4444-8444-444444444444",
        "trip_name": "Main"
      }
    ],
    "proposed": [
      {
        "match_type": "issuer",
        "match_value": "CAPITAL ONE",
        "display_name": "Capital One",
        "actions": {
          "mode": "challenge_requested"
        },
        "note": "Generated: 3DS 31.2% (212) vs holdout 18.5% (140), +12.7 pts over 30 d",
        "evidence": {
          "generator": "threeds",
          "mode": "issuer",
          "window_days": 30,
          "applied": {
            "n": 212,
            "approved": 66,
            "ar": 31.2
          },
          "holdout": {
            "n": 140,
            "approved": 26,
            "ar": 18.5
          },
          "lift_pts": 12.7,
          "per_trip": []
        }
      }
    ],
    "diff": {
      "new": [
        {
          "match_type": "issuer",
          "match_value": "CAPITAL ONE"
        }
      ],
      "kept": [],
      "would_remove": []
    },
    "applied": null
  },
  "input": {
    "dryRun": true,
    "mode": "issuer",
    "criteria": {
      "window_days": 30,
      "min_attempts": 30,
      "min_lift_pts": 8,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "replaceGenerated": true,
    "by": "owner@example.com"
  }
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`.
- `404` `Generation not found`.
- `409` `Result is unavailable or expired` (status not ready or applied, no result saved, or past expires_at).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- result = {run (the job id), source (`generated:<job id>`, carried by applied rules), kind, mode, dry_run, replace_generated, criteria (effective), trips, proposed[] {match_type, match_value, display_name, actions, note, evidence}, diff {new = what apply inserts, kept = proposals a rule already covers (rule_id, source, changed), would_remove = generated rules replace_generated drops}, applied (null until applied, then {inserted, removed, errors, refused})}.
- Mapping proposals always target MIDs (type mid).
- Limits: 10000 proposals and 16 MB of evidence per job; above them the job fails with that reason.

##### `GET /v1/bin-generation/capabilities`

**Scope** `routing.read` - **BIN generation availability**

Tells whether background BIN rule generation can run: `enabled` is true when background jobs are switched on for the server and the generation storage exists.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Required storage for BIN generation is unavailable. Complete the current database migrations.`
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- Cache-Control no-store.
- enabled false = background jobs are off: POST /v1/bin-profiles/:id/generation-jobs answers 503. The synchronous POST /v1/bin-profiles/:id/generate is retired (always 409); there is no other way to generate.

##### `GET /v1/bin-info`

**Scope** `reports.read` - **BIN Lists**

Paginated, server-filtered BIN intelligence referential (country / issuer / brand / level / prepaid / type) joined with how many transactions have been seen on each BIN, plus global enrichment counters. Backs the BIN Lists page.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer, 1..10000; default `50` | no | Page size. Out of range or non-numeric is a 400. |
| `offset` | integer >= 0; default `0` | no | Rows to skip. |
| `filter` | string, max 64 | no | Free-text search, trimmed and lowercased, matched as contains against bin, issuer, brand and country_code at once (OR). Empty means no filter. `%` and `_` act as wildcards. |
| `prefix` | string of 1..6 digits | no | Only BINs starting with these digits, most-seen first (the rule editor's suggestions). Combines with filter (AND). Anything else is a 400. |

**Response**

```json
{
  "rows": [
    {
      "bin": "411111",
      "country_code": "US",
      "currency": "USD",
      "is_prepaid": false,
      "type": "CREDIT",
      "issuer": "EXAMPLE BANK, N.A.",
      "issuer_key": "EXAMPLE BANK",
      "brand": "VISA",
      "level": "CLASSIC",
      "status": "ok",
      "attempts": 1,
      "fetched_at": "2026-11-14T02:11:47.006Z",
      "created_at": "2026-11-14T02:11:47.006Z",
      "seen_count": 182,
      "total": 1274,
      "canonical_issuer_key": "EXAMPLE BANK"
    }
  ],
  "total": 1274,
  "stats": {
    "total": 1503,
    "enriched": 1274,
    "errored": 229
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | array<object> | One page of bin_info rows (`SELECT b.*` plus two computed columns). Fixed order: seen_count DESC, then bin ASC. There is no sort parameter. |
| `rows[].bin` | string | 6-digit BIN, primary key. A STRING - leading zeros matter, never parse as integer. |
| `rows[].country_code` | string \| null | ISO 2-letter issuing country from the external BIN API. Null when unknown or when status='error'. |
| `rows[].currency` | string \| null | Issuing currency code. Nullable. |
| `rows[].is_prepaid` | boolean \| null | TRI-STATE: true / false / null. null means unknown, NOT false - do not coerce with a falsy check. |
| `rows[].type` | string \| null | Card funding type verbatim from the provider, typically uppercase: CREDIT / DEBIT / etc. Nullable. |
| `rows[].issuer` | string \| null | Issuing bank name verbatim from the provider. Free text, unnormalized, nullable. |
| `rows[].brand` | string \| null | Card network verbatim: VISA / MASTERCARD / etc. Nullable. |
| `rows[].level` | string \| null | Product level: CLASSIC / GOLD / PLATINUM / SIGNATURE / BUSINESS etc. This is the field the commercial_card_block filter keyword-matches against (migration 055). Nullable. |
| `rows[].status` | string | enum: ok\|error. 'ok' = successfully enriched. 'error' = the external lookup failed or returned nothing; the row is cached deliberately so the job does not re-hammer the API, and most other fields are null. |
| `rows[].attempts` | integer | Number of external BIN lookup attempts for this BIN (not a charge count). |
| `rows[].fetched_at` | string (ISO 8601) \| null | Last time the external lookup ran for this BIN. Null only for rows created without a lookup. |
| `rows[].created_at` | string (ISO 8601) | When the BIN row was first inserted. |
| `rows[].seen_count` | integer | Transactions of the caller's account whose masked card starts with this BIN (all time, not windowed); 0 when never seen. |
| `rows[].total` | integer | REDUNDANT per-row copy of the top-level `total` (`count(*) over()`). Same value on every row in the page. Ignore it; read the top-level `total`. |
| `total` | integer | Rows matching filter / prefix before paging, read from the first row: 0 when the page is empty (offset past the end or no match). |
| `stats` | object | Enrichment counters over the whole BIN referential; ignores filter and prefix. |
| `stats.total` | integer | Total rows in bin_info, ignoring `filter`. |
| `stats.enriched` | integer | Rows with status='ok', ignoring `filter`. |
| `stats.errored` | integer | Rows with status='error', ignoring `filter`. |
| `rows[].canonical_issuer_key` | string \| null | v3.9 section 5 - bin_info.issuer_key folded through bin_issuer_aliases: the key an ISSUER RULE matches on (null = not enriched, or an excluded programme). What the RuleEditor compares against the profile's issuer rules. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: limit outside 1..10000, negative offset, filter over 64 characters, prefix not 1-6 digits.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` The statement timed out (the request took too long and was cancelled).

**Gotchas**

- `total` IS READ FROM rows[0] (`page.rows[0]?.total ?? 0`). If the page is empty - offset past the end, or a filter that matches nothing - `total` comes back 0 even when thousands of rows match. Never use `total` to detect 'end of list' after over-paging; it will make a paginator jump back to page 1.
- `stats` IGNORES `filter` entirely. It is a second query with no WHERE clause over all of bin_info. So with a filter set, `total` (filtered) and `stats.total` (unfiltered) legitimately disagree - that is not a bug and stats will not tell you how many of your filtered results are enriched vs errored.
- `filter` is ONE search box across FOUR columns OR'd together (bin, issuer, brand, country_code). filter=us matches country US and every issuer containing 'us' (e.g. 'CHASE BANK USA'). You cannot say 'country = US' specifically. There is no per-field param.
- The filter string is interpolated into the LIKE pattern WITHOUT escaping `%` or `_`. A filter of `%` matches everything, `4_4720` treats `_` as a single-char wildcard. Not a SQL-injection risk (it is a bound parameter) but it silently changes match semantics. Escape them yourself if you need literals.
- filter='' or an all-whitespace filter is treated as NO FILTER (it is trimmed, then falsy), so the WHERE clause is dropped and you get the full unfiltered list - not zero results. To clear a filter, omit the param.
- `attempts` means external BIN lookup attempts, not charge attempts; use `seen_count` for traffic volume.
- The referential itself is shared (no tenant data); only seen_count is the caller's account's (its keys and wallet providers).
- status='error' rows are INCLUDED in `rows`, mixed in with enriched ones, and carry mostly nulls. There is no status query param - filter them out client-side on `status !== 'ok'`. (The Rebill-export lookup path does filter to status='ok', this list does not.)
- Sort is hard-coded to seen_count DESC, bin ASC. There is no sort/order param. The dashboard re-sorts only the current page in JS, which is a page-local sort, not a global one.
- Every row carries a duplicated `total` field from `count(*) over()`. If you diff or hash row objects, that field will change between pages for the same BIN even though nothing about the BIN changed.
- Population is asynchronous (the binInfoSync cron enriches the most-seen unknown BINs first, subject to an external API quota). A BIN with real traffic can be absent from this list entirely - absence means 'not looked up yet', not 'unknown BIN'.

##### `GET /v1/bin-issuers`

**Scope** `routing.read` - **Search issuer banks**

Autocomplete for an issuer bank value in BIN rules: the canonical issuers whose key, display name or any alias label contains q (case-insensitive), with the number of enriched BINs and aliases behind each, and the account's live orders on those BINs in the last 30 days. Excluded issuers (EBT programmes...) never appear.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string (0-120); default `""` | no | Case-insensitive substring of the issuer key, display name or any alias label. Empty lists the top issuers. |
| `limit` | integer (1-100); default `20` | no | Maximum rows returned. |

**Response**

```json
{
  "rows": [
    {
      "key": "EXAMPLE BANK",
      "display_name": "Example Bank",
      "bins": 103,
      "aliases": 4,
      "orders30d": 613
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].key` | string | The canonical issuer key — what an issuer rule's match_value stores. |
| `rows[].display_name` | string | Operator-facing name. |
| `rows[].bins` | integer | Enriched BINs whose issuer folds onto this key. |
| `rows[].aliases` | integer | Alias rows folded onto this key. |
| `rows[].orders30d` | integer | The account's live charges on those BINs in the last 30 days (v3.9 §1 live predicate). |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when q is longer than 120 characters or limit is not an integer from 1 to 100.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Customer reads are busy. Please retry shortly."}` when the bounded picker read queue is full.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the read passes its 25-second budget.

**Gotchas**

- Rows are ordered by bins descending, then display name; orders30d (live card transactions of the account, any status, last 30 days) does not drive the order.
- The issuer list is the global BIN referential; only orders30d is the account's own. For the account's own pick list ranked by its volume use GET /v1/bin-catalog.
- Sent with cache-control: private, no-store.

##### `GET /v1/bin-map`

**Scope** `reports.read` - **List mapping rules per target**

A mapping profile's redirect rules turned inside out: one group per target (MID, ATRI, processor or acquiring bank) listing the BIN and issuer rules that point at it. What fires is the BIN rule engine (bin_rules), not the legacy BIN-to-MID map.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `profile_id` | uuid | no | The mapping profile. Omitted: the account's default mapping profile (none gives an empty answer). |

**Response**

```json
{
  "profile": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "Example issuers",
    "kind": "mapping"
  },
  "targets": [
    {
      "target": {
        "type": "mid",
        "id": "22222222-2222-4222-8222-222222222222",
        "name": "Example MID 01"
      },
      "rules": [
        {
          "id": "33333333-3333-4333-8333-333333333333",
          "position": 1,
          "enabled": true,
          "match_type": "issuer",
          "match_value": "EXAMPLE BANK",
          "source": "manual",
          "note": null,
          "issuer_name": "Example Bank"
        }
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `profile` | object \| null | { id, name, kind } of the profile read, or null when the account has no default mapping profile (targets is then []). |
| `targets[].target` | object | { type: mid \| atri \| processor \| acquirer, id, name }. name is null when the MID or ATRI is not the account's (the rule is dead there). |
| `targets[].rules` | object[] | { id, position, enabled, match_type: bin \| issuer, match_value, source, note, issuer_name } in position order. issuer_name is the alias display name for issuer rules, null for BIN rules. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}` when profile_id is not a uuid.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module.
- `404` `Not found`: profile_id is not one of the account's mapping profiles (or is a profile of another kind).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Groups are ordered by rule count descending, then target name.
- Only targets whose id is a uuid are listed; a rule can appear under several targets.
- Disabled rules are listed too (enabled false).

##### `GET /v1/bin-profiles`

**Scope** `routing.read` - **List BIN profiles**

Lists the account's BIN Intelligence profiles of every kind (mapping = redirect rules, scrubbing = refusal rules, threeds = 3DS mode rules), ordered by kind then name, each with the ATRIs that select it and its rule counts. A profile owns an ordered list of rules (what fires on the charge path); its `criteria` are only the settings of its rule generator.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: mapping\|scrubbing\|threeds | no | Only profiles of this kind. Missing or any other value returns every kind (never an error). |

**Response**

```json
{
  "rows": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "owner_email": "owner@example.com",
      "kind": "threeds",
      "name": "Issuer 3DS",
      "description": "Challenge weak issuers",
      "criteria": {
        "window_days": 30,
        "min_attempts": 30,
        "min_lift_pts": 5,
        "auto_enforce": false,
        "auto_enabled": false
      },
      "enabled": true,
      "is_default": false,
      "created_by": "owner@example.com",
      "created_at": "2026-11-01T10:00:00.000Z",
      "updated_at": "2026-11-20T09:00:00.000Z",
      "used_by": [
        {
          "id": "44444444-4444-4444-8444-444444444444",
          "name": "Main"
        }
      ],
      "rule_count": 2,
      "enabled_rule_count": 2
    },
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "owner_email": "owner@example.com",
      "kind": "scrubbing",
      "name": "Refund scrub",
      "description": null,
      "criteria": {
        "window_days": 30,
        "min_attempts": 30,
        "min_approvals": 5,
        "ar_max_pct": 15,
        "refund_max_pct": 25,
        "min_net_loss_cents": 5000,
        "auto_enforce": false,
        "auto_enabled": false,
        "rb_sync": true
      },
      "enabled": true,
      "is_default": true,
      "created_by": "owner@example.com",
      "created_at": "2026-11-01T10:00:00.000Z",
      "updated_at": "2026-11-20T09:00:00.000Z",
      "used_by": [],
      "rule_count": 14,
      "enabled_rule_count": 12
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array<object> | Profiles ordered by kind, then name. |
| `rows[].kind` | enum: mapping\|scrubbing\|threeds | The rule kind of the profile (fixed at creation). |
| `rows[].description` | string \| null | Free text shown on the profile page. |
| `rows[].criteria` | object | Generator settings for the kind (see GET /v1/bin-profiles/defaults), never the live behaviour. |
| `rows[].enabled` | boolean | false = none of the profile's rules fire, even on ATRIs that select it. |
| `rows[].is_default` | boolean | The default of its kind, pre-selected on new ATRIs when it is also enabled. |
| `rows[].used_by` | array<{id,name}> | The ATRIs whose mapping, scrubbing or 3DS profile pointer is this profile. |
| `rows[].rule_count` | integer | Rules of the profile, enabled or not. |
| `rows[].enabled_rule_count` | integer | Rules that fire. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Nothing in a profile fires until an ATRI selects it (binMapProfileId, binScrubProfileId or binThreedsProfileId on POST /v1/trips or PATCH /v1/trips/:id).
- An empty account answers {"rows": []}.

##### `POST /v1/bin-profiles`

**Scope** `routing.write` - **Create a BIN profile**

Creates a profile of a kind with its generator criteria (validated for the kind, keys left out take their defaults). A NEW scrubbing profile inherits the account's current RB-synced BIN set as rb_sync refusal rules (PUT /v1/scrub-bins keeps replicating into it) unless its criteria say rb_sync: false. Names are unique per (account, kind).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: mapping\|scrubbing\|threeds | **yes** | The rule kind; it can never change afterwards. |
| `name` | string | **yes** | 1..80 characters after trimming; unique per (account, kind). |
| `description` | string \| null; default `null` | no | Up to 2000 characters after trimming; an empty string is stored as null. |
| `criteria` | object; default `{}` | no | Generator criteria for the kind (fields criteria.* below; defaults in GET /v1/bin-profiles/defaults). Keys left out take their defaults, unknown keys are dropped, an out-of-range value is 400 `Invalid criteria`. |
| `criteria.window_hours` | integer 1..8760; default `168` | no | mapping only: the attempts window, in hours. (A scrubbing profile still sent in the old shape converts window_hours to window_days.) Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_bin_attempts` | integer 1..100000; default `20` | no | mapping only: a BIN (or issuer) needs this many attempts on the ATRI before a redirect is proposed. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_mid_attempts` | integer 1..100000; default `5` | no | mapping only: a MID needs this many attempts on that BIN to qualify as a target. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_ar_pct` | integer 0..100; default `60` | no | mapping only: a target MID must clear this approval rate (MID-rejection AR, in percent) on the BIN. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.max_targets` | integer 1..10; default `1` | no | mapping only: the top N qualifying MIDs per ATRI become the redirect pool (1 = pin the single best MID). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.window_days` | integer 1..365; default `30` | no | scrubbing and threeds: the attempts window, in days. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_attempts` | integer 1..100000; default `30` | no | scrubbing: a BIN is judged once it has this many attempts on the ATRI. threeds: the minimum attempts of EACH arm (3DS applied and holdout). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_approvals` | integer 0..100000 \| null; default `5` | no | scrubbing only: the refund rule needs this many approvals on the BIN; null = no minimum. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.ar_max_pct` | number 0..100 \| null; default `15` | no | scrubbing only: AR rule, a BIN whose approvals / attempts is under this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.refund_max_pct` | number 0..100 \| null; default `25` | no | scrubbing only: refund rule, a BIN whose refunded / approved reaches this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_net_loss_cents` | integer 0..100000000 \| null; default `5000` | no | scrubbing only: money rule, a BIN whose net is below minus this amount (cents) is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.rb_sync` | boolean; default `true` | no | scrubbing only: false opts the profile out of the external rebill tool's list (PUT /v1/scrub-bins never writes into it, and a new profile does not copy the account's rb_sync rules). Use false on a profile scoped to straight traffic. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_lift_pts` | number 0..100; default `5` | no | threeds only: the approval-rate lift, in points, between charges with a 3DS cryptogram and the holdout arm: a lift of at least +X proposes challenge_requested, at most -X proposes no_3ds. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enabled` | boolean; default `false` | no | every kind: true lets the periodic generator run this profile. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enforce` | boolean; default `false` | no | every kind: rules the periodic generator creates are inserted enabled (true) or staged disabled for review (false). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `enabled` | boolean; default `true` | no | false = none of its rules fire. |
| `is_default` | boolean; default `false` | no | Make it the default of its kind (pre-selected on new ATRIs); the other profiles of the kind lose the flag. |

**Request body**

```json
{
  "kind": "threeds",
  "name": "Issuer 3DS",
  "description": "Challenge weak issuers",
  "criteria": {
    "min_lift_pts": 8
  }
}
```

**Response**

```json
{
  "profile": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "threeds",
    "name": "Issuer 3DS",
    "description": "Challenge weak issuers",
    "criteria": {
      "window_days": 30,
      "min_attempts": 30,
      "min_lift_pts": 8,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "enabled": true,
    "is_default": false,
    "created_by": "owner@example.com",
    "created_at": "2026-11-01T10:00:00.000Z",
    "updated_at": "2026-11-01T10:00:00.000Z",
    "used_by": [],
    "rule_count": 0,
    "enabled_rule_count": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The created profile (same shape as a list row). |

**Errors**

- `400` `Invalid` with `details` (kind, name, description or a field type), or `Invalid criteria` with `details`.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `409` `A profile with this name already exists for this kind`.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- 201 on success.
- A scrubbing profile is born with the account's rb_sync rules (one refusal rule per RB-synced BIN, enabled when enforced), so rule_count can be above 0 at once.
- Unknown top-level keys (the retired `flow` included) are ignored.

##### `GET /v1/bin-profiles/:id`

**Scope** `routing.read` - **Get one BIN profile**

One profile of the account (same shape as a list row: criteria, the ATRIs using it, rule counts) plus `assignments`: the attach ledger, every time the profile was attached to or detached from an ATRI, newest first. A database trigger fills the ledger for every writer of the ATRI pointers.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Response**

```json
{
  "profile": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "threeds",
    "name": "Issuer 3DS",
    "description": "Challenge weak issuers",
    "criteria": {
      "window_days": 30,
      "min_attempts": 30,
      "min_lift_pts": 5,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "enabled": true,
    "is_default": false,
    "created_by": "owner@example.com",
    "created_at": "2026-11-01T10:00:00.000Z",
    "updated_at": "2026-11-20T09:00:00.000Z",
    "used_by": [
      {
        "id": "44444444-4444-4444-8444-444444444444",
        "name": "Main"
      }
    ],
    "rule_count": 2,
    "enabled_rule_count": 2
  },
  "assignments": [
    {
      "trip_id": "44444444-4444-4444-8444-444444444444",
      "trip_name": "Main",
      "kind": "threeds",
      "attached_at": "2026-11-18T16:20:00.000Z",
      "detached_at": null,
      "changed_by": "owner@example.com"
    },
    {
      "trip_id": "44444444-4444-4444-8444-444444444444",
      "trip_name": "Main",
      "kind": "threeds",
      "attached_at": "2026-11-10T09:00:00.000Z",
      "detached_at": "2026-11-12T08:00:00.000Z",
      "changed_by": "owner@example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The profile: id, owner_email, kind, name, description, criteria, enabled, is_default, created_by, created_at, updated_at, used_by, rule_count, enabled_rule_count (same shape as a row of GET /v1/bin-profiles). |
| `assignments` | array<{trip_id, trip_name, kind, attached_at, detached_at, changed_by}> | Newest first. detached_at null = the ATRI selects the profile now. changed_by = the e-mail of the caller that wrote the ATRI pointer through POST /v1/trips or PATCH /v1/trips/:id (the account owner's e-mail for an API key), `script:<name>` or `migration:146` for backfilled rows, null for hand SQL. A detach records nobody: only the new open row is stamped. |

**Errors**

- `400` `bad id` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- `assignments` anchors the analytics: the latest open attach per ATRI decides where "approval rate without the profile" ends (GET /v1/bin-profiles/:id/analytics).

##### `PUT /v1/bin-profiles/:id`

**Scope** `routing.write` - **Update a BIN profile**

Renames, describes, replaces the generator criteria, enables or disables, or makes the profile default. Only the fields sent are written. Disabling a profile stops every rule it carries on the charge path.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | 1..80 characters after trimming; unique per (account, kind). |
| `description` | string \| null | no | Up to 2000 characters; null or an empty string clears it; omitted leaves it. |
| `criteria` | object | no | FULL replacement validated for the profile's kind: keys left out reset to their defaults (not to the current values); unknown keys are dropped. |
| `criteria.window_hours` | integer 1..8760; default `168` | no | mapping only: the attempts window, in hours. (A scrubbing profile still sent in the old shape converts window_hours to window_days.) Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_bin_attempts` | integer 1..100000; default `20` | no | mapping only: a BIN (or issuer) needs this many attempts on the ATRI before a redirect is proposed. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_mid_attempts` | integer 1..100000; default `5` | no | mapping only: a MID needs this many attempts on that BIN to qualify as a target. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_ar_pct` | integer 0..100; default `60` | no | mapping only: a target MID must clear this approval rate (MID-rejection AR, in percent) on the BIN. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.max_targets` | integer 1..10; default `1` | no | mapping only: the top N qualifying MIDs per ATRI become the redirect pool (1 = pin the single best MID). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.window_days` | integer 1..365; default `30` | no | scrubbing and threeds: the attempts window, in days. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_attempts` | integer 1..100000; default `30` | no | scrubbing: a BIN is judged once it has this many attempts on the ATRI. threeds: the minimum attempts of EACH arm (3DS applied and holdout). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_approvals` | integer 0..100000 \| null; default `5` | no | scrubbing only: the refund rule needs this many approvals on the BIN; null = no minimum. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.ar_max_pct` | number 0..100 \| null; default `15` | no | scrubbing only: AR rule, a BIN whose approvals / attempts is under this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.refund_max_pct` | number 0..100 \| null; default `25` | no | scrubbing only: refund rule, a BIN whose refunded / approved reaches this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_net_loss_cents` | integer 0..100000000 \| null; default `5000` | no | scrubbing only: money rule, a BIN whose net is below minus this amount (cents) is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.rb_sync` | boolean; default `true` | no | scrubbing only: false opts the profile out of the external rebill tool's list (PUT /v1/scrub-bins never writes into it, and a new profile does not copy the account's rb_sync rules). Use false on a profile scoped to straight traffic. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_lift_pts` | number 0..100; default `5` | no | threeds only: the approval-rate lift, in points, between charges with a 3DS cryptogram and the holdout arm: a lift of at least +X proposes challenge_requested, at most -X proposes no_3ds. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enabled` | boolean; default `false` | no | every kind: true lets the periodic generator run this profile. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enforce` | boolean; default `false` | no | every kind: rules the periodic generator creates are inserted enabled (true) or staged disabled for review (false). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `enabled` | boolean | no | false stops every rule of the profile. |
| `is_default` | boolean | no | true makes it the default of its kind (the others lose the flag); false clears the flag. |

**Request body**

```json
{
  "description": "Challenge weak issuers, measured weekly",
  "criteria": {
    "window_days": 60,
    "min_attempts": 30,
    "min_lift_pts": 5
  }
}
```

**Response**

```json
{
  "profile": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "threeds",
    "name": "Issuer 3DS",
    "description": "Challenge weak issuers, measured weekly",
    "criteria": {
      "window_days": 60,
      "min_attempts": 30,
      "min_lift_pts": 5,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "enabled": true,
    "is_default": false,
    "created_by": "owner@example.com",
    "created_at": "2026-11-01T10:00:00.000Z",
    "updated_at": "2026-11-20T09:00:00.000Z",
    "used_by": [
      {
        "id": "44444444-4444-4444-8444-444444444444",
        "name": "Main"
      }
    ],
    "rule_count": 2,
    "enabled_rule_count": 2
  }
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The updated profile (same shape as a list row). |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (a field of the wrong type or length) or `Invalid criteria` with `details`.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `409` `A profile with this name already exists for this kind`.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- `kind` cannot change (an unknown key such as kind is ignored).
- Send the whole criteria object you want: a partial object resets the other keys to their defaults.
- A rule change caused by enabling or disabling applies on every server within about a minute (rule sets are cached).
- Sending criteria replaces the whole object: every criteria.* key you leave out goes back to its default, not to its current value. Read the profile, change the keys, send them all.

##### `DELETE /v1/bin-profiles/:id`

**Scope** `routing.write` - **Delete a BIN profile**

Deletes one profile of the account. ATRIs that selected it are detached (their pointer becomes null, so that feature is off on them) and every rule of the profile is deleted with it. Its decision-log rows stay until the 60-day retention removes them. Returns {ok: true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the profile was deleted. |

**Errors**

- `400` `bad id` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- No usage guard: deleting a profile used by several ATRIs silently turns BIN mapping, scrubbing or 3DS rules off on all of them. Check `used_by` first.
- Not reversible: export the rules first (GET /v1/bin-profiles/:id/rules/export.csv) if you may need them.

##### `GET /v1/bin-profiles/:id/analytics`

**Scope** `routing.read` - **BIN profile analytics**

Per rule over a window: evaluations, matches and applied decisions from the decision log, the outcome of the charges the rule was APPLIED to, and two baselines: (a) `baseline_atri` = the rest of the same ATRIs in the same window (the orders no rule of the profile matched; context, never a counterfactual); (b) `baseline_before` = the same value on the same ATRIs in the window of the same length that ended at the rule's anchor (the later of its creation and the profile's attach time). Lifts are in points (approval rate applied minus baseline; null when a side has no orders). Scrubbing rules report `refused`; 3DS rules add the holdout arm. `headline` = the profile-level tiles: approval rate with the profile (routed) against the same values WITHOUT it (counterfactual, in the reference window before the anchor), lift, share gained, approvals and revenue gained, low_sample under 20 orders, the scrubbing money view, the 3DS holdout and status funnel, abandoned challenges.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 date-time, Z or offset); default `to minus 30 days` | no | Window start (inclusive). |
| `to` | string (ISO 8601 date-time, Z or offset); default `now` | no | Window end (exclusive). |
| `tz` | string; default `UTC` | no | Up to 64 characters; only echoed back (the computation uses UTC). |

**Response**

```json
{
  "profile_id": "11111111-1111-4111-8111-111111111111",
  "kind": "mapping",
  "from": "2026-11-17T00:00:00.000Z",
  "to": "2026-11-24T00:00:00.000Z",
  "tz": "UTC",
  "trips": [
    {
      "trip_id": "44444444-4444-4444-8444-444444444444",
      "trip_name": "Main"
    }
  ],
  "evaluations": 447,
  "no_match": 318,
  "baseline_atri": {
    "orders": 185,
    "approved": 120,
    "declined": 65,
    "ar": 64.9
  },
  "headline": {
    "anchor": {
      "at": "2026-11-17T06:20:12.305Z",
      "source": "assignment"
    },
    "reference": {
      "from": "2026-11-10T06:20:12.305Z",
      "to": "2026-11-17T06:20:12.305Z",
      "same_hours": false
    },
    "routed": {
      "orders": 65,
      "approved": 39,
      "declined": 26,
      "ar": 60.0
    },
    "counterfactual": {
      "orders": 232,
      "approved": 90,
      "declined": 142,
      "ar": 38.8,
      "refunded": 0,
      "refund_rate": 0,
      "approved_cents": 351240,
      "refund_cents": 0,
      "refund_fee_cents": 0
    },
    "unrouted_same_period": null,
    "rest_of_atri": {
      "orders": 185,
      "approved": 120,
      "declined": 65,
      "ar": 64.9
    },
    "holdout": null,
    "three_ds": null,
    "abandoned": 4,
    "lift_pts": 21.2,
    "lift_vs": "counterfactual",
    "gained_pct": 54.6,
    "approvals_gained": 13.8,
    "revenue_gained_cents": 53185,
    "avg_ticket_cents": 3854,
    "low_sample": false,
    "min_sample": 20,
    "refused": 0,
    "refused_cents": 0,
    "money": null
  },
  "rules": [
    {
      "rule_id": "22222222-2222-4222-8222-222222222222",
      "position": 1,
      "enabled": true,
      "source": "manual",
      "match_type": "issuer",
      "match_value": "CAPITAL ONE",
      "display_name": "Capital One",
      "actions": {
        "targets": [
          {
            "type": "mid",
            "id": "55555555-5555-4555-8555-555555555555"
          }
        ]
      },
      "created_at": "2026-11-17T06:18:12.000Z",
      "evaluations": 447,
      "matches": 101,
      "applied": 50,
      "not_applied": 51,
      "outcome": {
        "orders": 50,
        "approved": 30,
        "declined": 20,
        "ar": 60.0
      },
      "baseline_atri": {
        "orders": 185,
        "approved": 120,
        "declined": 65,
        "ar": 64.9
      },
      "baseline_before": {
        "orders": 71,
        "approved": 31,
        "declined": 40,
        "ar": 43.7,
        "refunded": 0,
        "refund_rate": 0
      },
      "before_anchor": "2026-11-17T06:20:12.305Z",
      "lift_atri_pts": -4.9,
      "lift_before_pts": 16.3,
      "refused": null,
      "holdout": null,
      "lift_holdout_pts": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `trips` | array<{trip_id,trip_name}> | The ATRIs the window looks at: those the profile evaluated in the window plus those selecting it now. |
| `evaluations` | integer | Orders the profile evaluated in the window (match or not). |
| `no_match` | integer | Evaluations no rule matched. |
| `baseline_atri` | object | Baseline (a): the rest of the ATRIs (= headline.rest_of_atri). Context only, shared by every rule. |
| `headline` | object | The profile-level tiles. Every arm = {orders, approved, declined, ar} over distinct orders, ar in percent. |
| `headline.anchor` | { at: string \| null, source: assignment \| first_decision \| profile_created \| null } | When the profile went live on the window's ATRIs: the attach ledger (latest attach per ATRI before `to`, earliest across ATRIs), else its first decision on them, else its creation. |
| `headline.reference` | { from, to, same_hours } | The counterfactual's window: [anchor minus max(window span, 7 days), anchor). same_hours = true when the window is shorter than a day: only the same UTC clock hours of each reference day count. |
| `headline.routed` | arm | mapping / threeds: the charges the profile's applied decisions stand for (distinct transactions). Empty for scrubbing (a refusal has no transaction). |
| `headline.counterfactual` | arm + { refunded, refund_rate, approved_cents, refund_cents, refund_fee_cents } | The same match values (of the rules that routed at least one order in the window) on the same ATRIs in the reference window, with their refunds (chargebacks included) and amounts in cents. |
| `headline.unrouted_same_period` | arm \| null | The same values, ATRIs and window, NOT routed by the profile. null when 0 orders. |
| `headline.rest_of_atri` | arm | = baseline_atri. Context only. |
| `headline.holdout` | arm \| null | threeds only: the holdout arm of the same values in the window; the lift's base when it has orders (lift_vs = holdout). |
| `headline.three_ds` | object \| null | threeds only: 3DS status counts of the routed arm. |
| `headline.abandoned` | integer | 3DS challenges never completed: the parked transaction expired and the order never came back with a live charge. |
| `headline.lift_pts` | number \| null | routed.ar minus the base ar (holdout for a 3DS profile with holdout orders, else the counterfactual: `lift_vs`). null unless both sides have orders; always null for scrubbing. |
| `headline.gained_pct` | number \| null | 100 x lift_pts / base.ar. |
| `headline.approvals_gained` | number \| null | routed.orders x lift_pts / 100 (one decimal). |
| `headline.revenue_gained_cents` | integer \| null | approvals_gained x avg_ticket_cents (the routed arm's average approved ticket). |
| `headline.low_sample` | boolean | true when routed (refused for scrubbing) or the lift's base has fewer than min_sample (20) orders: do not read the lift as a verdict. |
| `headline.refused` | integer | scrubbing: applied refusals (distinct orders); refused_cents = the refused amounts. |
| `headline.money` | object \| null | scrubbing: expected-value view from the counterfactual's rates: revenue_refused_cents, refunds_avoided_cents, refund_fees_avoided_cents, net_cents (negative = the rules cost more revenue than they save) and `formula`. null without approved orders in the counterfactual. |
| `rules[].display_name` | string \| null | The issuer's display name for an issuer rule, the country's English name for a GEO rule, null for a BIN rule. |
| `rules[].matches` | integer | Evaluations this rule won. |
| `rules[].applied` | integer | Matches that changed the charge (pool applied, refusal made, 3DS mode set); not_applied = matched but not applied. |
| `rules[].outcome` | arm | The charges the rule was applied to. |
| `rules[].baseline_before` | arm + { refunded, refund_rate } | Baseline (b), keyed per match type (a country rule = the same customer country on card rows; an issuer_country rule = the same issuing country). |
| `rules[].before_anchor` | string (ISO 8601) | Where baseline (b) ends: the later of the rule's creation and headline.anchor.at. |
| `rules[].lift_atri_pts` | number \| null | outcome.ar minus baseline_atri.ar. |
| `rules[].lift_before_pts` | number \| null | outcome.ar minus baseline_before.ar. |
| `rules[].refused` | integer \| null | scrubbing only: applied refusals. |
| `rules[].holdout` | arm \| null | threeds only: the holdout arm of the value in the window; lift_holdout_pts = outcome.ar minus holdout.ar. |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (from or to not an ISO 8601 date-time, tz over 64 characters).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Recompute rates from their components; never average them across rules.
- Decisions older than 60 days are purged, so a window further back is empty.
- Every figure counts ORDERS (distinct order ids): an order evaluated twice (a 3DS session then the charge) is never doubled.
- baseline_atri is the REST of the ATRI: for a mapping profile aimed at weak issuers it holds the strong ones, so lift_atri_pts reads negative on a profile that gains. Use headline.counterfactual for the verdict.

##### `GET /v1/bin-profiles/:id/decisions`

**Scope** `routing.read` - **BIN profile decision log**

The profile's decision log (one row per evaluation of the profile, match or not), newest first, server-paged and filterable. Each row carries the matched rule's current type and value and its OUTCOME: what happened to the charge (approved, declined, error, pending or unknown from the transaction; `rejected` when a pre-gateway refusal stands where the charge would be; `gone` when the transaction it points at no longer exists, an abandoned 3DS challenge), the final MID, whether it is the rule's chosen one, amount, attempts, 3DS status, rejection family. `from` / `to` bound the list only when given. `format=csv` returns the page as a CSV file.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 date-time, Z or offset) | no | Lower bound (inclusive). Omitted = no lower bound: every decision the 60-day retention keeps. |
| `to` | string (ISO 8601 date-time, Z or offset) | no | Upper bound (exclusive). Omitted = no upper bound. |
| `tz` | string | no | Up to 64 characters; accepted and ignored. |
| `rule_id` | uuid | no | Only this rule's decisions. |
| `outcome` | enum: match\|no_match\|applied\|not_applied | no | match = a rule matched; no_match = none did; applied = matched and changed the charge; not_applied = matched without changing it. |
| `result` | enum: approved\|declined\|error\|pending\|unknown\|rejected\|gone\|none | no | What happened to the charge (outcome.result); none = nothing to join. Independent of `outcome`. A filtered page joins the outcome before paging, so it is slower on a long period. |
| `flow` | enum: initial\|rebill | no | The charge flow of the evaluation (not a funnel flow id). |
| `bin` | string | no | Exactly 6 digits. |
| `country` | string (ISO 3166-1 alpha-2) | no | Only rows whose customer country equals it (case-insensitive, trimmed). |
| `limit` | integer; default `50` | no | 1..1000 rows per page. |
| `offset` | integer; default `0` | no | Rows to skip (0 or more). |
| `format` | enum: json\|csv; default `json` | no | csv = this page as a CSV file. |

**Response**

```json
{
  "rows": [
    {
      "id": "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
      "created_at": "2026-11-20T10:00:00.000Z",
      "owner_email": "owner@example.com",
      "trip_id": "44444444-4444-4444-8444-444444444444",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "kind": "mapping",
      "order_id": "ORD-1001",
      "transaction_id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
      "flow": "initial",
      "bin": "411111",
      "issuer_key": "CAPITAL ONE",
      "country": "US",
      "issuer_country": null,
      "rule_id": "22222222-2222-4222-8222-222222222222",
      "match_type": "issuer",
      "decision": {
        "action": "map",
        "applied": true,
        "chosen": "55555555-5555-4555-8555-555555555555",
        "pool": [
          "55555555-5555-4555-8555-555555555555"
        ],
        "pool_n": 1
      },
      "duration_us": 180,
      "run_id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
      "stage_duration_us": 66,
      "outcome": {
        "result": "declined",
        "via": "transaction",
        "transaction_id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
        "amount_cents": 4366,
        "final_mid": {
          "id": "55555555-5555-4555-8555-555555555555",
          "name": "Example MID 1"
        },
        "final_is_chosen": true,
        "attempts": 1,
        "three_ds": {
          "status": null,
          "applied": false,
          "flow": null
        },
        "rejection_family": null
      },
      "rule_match_type": "issuer",
      "rule_match_value": "CAPITAL ONE"
    }
  ],
  "total": 548,
  "limit": 50,
  "offset": 0,
  "from": null,
  "to": null
}
```

| response field | type | description |
|---|---|---|
| `rows[].decision` | object | {action, applied, pool?, pool_n?, chosen?, reason?}, bounded to 256 bytes (pool truncated first, pool_n keeps the true count). |
| `rows[].rule_id` | uuid \| null | null = no rule matched (still logged). |
| `rows[].rule_match_type` | string \| null | The matched rule's current match type, else the row's own match_type. |
| `rows[].rule_match_value` | string \| null | The matched rule's current value (null when no rule matched or the rule was deleted since). |
| `rows[].country` | string \| null | The customer's country the rules were matched on (ISO alpha-2); null when the order named no known country. |
| `rows[].issuer_country` | string \| null | The card's issuing country, set only when a loaded profile has an issuer_country rule that could match it. |
| `rows[].outcome` | object | The charge behind the decision: joined by transaction_id when the row has one; a 3DS session-start row and a no-match row are joined by order id on the account within [-1 h, +1 day); a mapping row without a transaction joins only its rejection. |
| `rows[].outcome.result` | enum \| null | approved \| declined \| error \| pending \| unknown (the transaction status), rejected (a pre-gateway refusal: rejection_family and amount_cents from it), gone (the transaction was removed: an abandoned 3DS challenge), null = nothing to join. |
| `rows[].outcome.via` | transaction \| order \| rejection \| null | How the outcome was found. |
| `rows[].outcome.final_mid` | { id, name } \| null | The MID the order ended on, cascade included. |
| `rows[].outcome.final_is_chosen` | boolean \| null | mapping: final_mid is the decision's chosen MID (false = the cascade moved on). null without a chosen MID or a charge. |
| `rows[].outcome.attempts` | integer \| null | Gateway attempts that reached a MID. |
| `rows[].outcome.three_ds` | { status, applied, flow } \| null | The charge's 3DS status, applied flag and flow. |
| `rows[].run_id` | uuid \| null | The sale pipeline run this evaluation belongs to (GET /v1/transactions/:id/details shows it in full); null before the pipeline and for a 3DS session-start row. |
| `rows[].stage_duration_us` | integer \| null | Duration of the pipeline stage that evaluated the profile, in microseconds; duration_us is the engine's own time. |
| `total` | integer | Rows matching the filters (paging denominator). |
| `from` | string \| null | The lower bound applied (null when omitted). |
| `to` | string \| null | The upper bound applied (null when omitted). |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (a bad outcome, result, flow, bin, country, rule_id, limit, offset, format or date).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- CSV columns: created_at, order_id, transaction_id, trip_id, flow, bin, issuer_key, country, issuer_country, rule_id, rule_match_type, rule_match_value, action, applied, reason, chosen, pool_n, duration_us, result, final_mid (name, else id), final_is_chosen, attempts, three_ds_status, rejection_family, amount (currency units, 2 decimals), run_id, stage_duration_us. One page (limit) per file; filename bin-decisions-<profile name slug>.csv; CRLF.
- A scrubbing refusal has transaction_id null (no transaction row); its outcome is the rejection (result rejected, family bin_scrub).
- No default window here, unlike the analytics: the response echoes from / to as sent (null when omitted).
- An order can have several rows for one profile (a 3DS session then the charge, a re-submitted challenge): count orders, not rows.
- `total` is 0 when offset is past the last row.

##### `PUT /v1/bin-profiles/:id/default`

**Scope** `routing.write` - **Make a BIN profile the default of its kind**

Flags the profile as the account's default for its kind (pre-selected on new ATRIs) and clears the flag on the other profiles of that kind, in one transaction. No body. Returns the updated profile.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Response**

```json
{
  "profile": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "threeds",
    "name": "Issuer 3DS",
    "description": "Challenge weak issuers",
    "criteria": {
      "window_days": 30,
      "min_attempts": 30,
      "min_lift_pts": 5,
      "auto_enforce": false,
      "auto_enabled": false
    },
    "enabled": true,
    "is_default": true,
    "created_by": "owner@example.com",
    "created_at": "2026-11-01T10:00:00.000Z",
    "updated_at": "2026-11-20T09:00:00.000Z",
    "used_by": [
      {
        "id": "44444444-4444-4444-8444-444444444444",
        "name": "Main"
      }
    ],
    "rule_count": 2,
    "enabled_rule_count": 2
  }
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The profile read again after the update (is_default true), same shape as GET /v1/bin-profiles/:id `profile`. |

**Errors**

- `400` `bad id` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Exactly one default per kind: the siblings lose the flag in the same transaction.
- A disabled profile can be made default, but new ATRIs only pre-select an ENABLED default: enable it too.
- Existing ATRIs are not changed; the default only applies when an ATRI is created.

##### `POST /v1/bin-profiles/:id/generate`

**Scope** `routing.write` - **Generate rules (retired)**

Retired synchronous generator. Always answers 409 without reading the body or the profile. Generate through a background job instead: POST /v1/bin-profiles/:id/generation-jobs, poll GET /v1/bin-generation-jobs/:id, read GET /v1/bin-generation-jobs/:id/result, then apply with POST /v1/bin-generation-jobs/:id/apply.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string | **yes** | Profile id; not read (the route always answers 409). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `dry_run` | boolean | no | Accepted and ignored: the route is retired and answers 409 before reading the body. Send it to POST /v1/bin-profiles/:id/generation-jobs instead. |
| `mode` | string | no | Accepted and ignored: the route is retired and answers 409 before reading the body. Send it to POST /v1/bin-profiles/:id/generation-jobs instead. |
| `criteria` | object | no | Accepted and ignored: the route is retired and answers 409 before reading the body. Send it to POST /v1/bin-profiles/:id/generation-jobs instead. |
| `replace_generated` | boolean | no | Accepted and ignored: the route is retired and answers 409 before reading the body. Send it to POST /v1/bin-profiles/:id/generation-jobs instead. |
| `enabled` | boolean | no | Accepted and ignored: the route is retired and answers 409 before reading the body. Send it to POST /v1/bin-profiles/:id/generation-jobs instead. |

**Response**

```json
{
  "error": "Use background generation. Reload the dashboard to continue."
}
```

| response field | type | description |
|---|---|---|
| `run` | string | Run id (UTC minute). |
| `source` | string | The source the applied rules carry. |
| `trips` | array<{trip_id,trip_name}> | The ATRIs evaluated (those whose profile pointer of this kind is the profile; none -> no proposals). |
| `proposed` | array<object> | Every proposal: match_type, match_value, display_name (issuer mode), actions, note, evidence. |
| `diff.new` | array<object> | Proposals with no rule of that value yet - what apply inserts. |
| `diff.kept` | array<object> | Proposals a rule already covers (rule_id, source, changed = the actions differ). Not inserted unless replace_generated and the existing rule is generated. |
| `diff.would_remove` | array<object> | Generated rules no proposal re-affirms (dropped by replace_generated). |
| `applied` | object \| null | null on a dry run; else { inserted, removed, errors }. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `409` `Use background generation. Reload the dashboard to continue.` on every call.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Nothing is generated or written by this route.

##### `GET /v1/bin-profiles/:id/generation-jobs`

**Scope** `routing.write` - **List the generation jobs of a profile**

Lists the generation jobs of one profile visible to the caller: active ones (queued, running, ready) first, then the newest, at most 20. Status and counters only, never proposals or evidence.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 404 `Profile not found`. A UUID of a profile that is not yours returns an empty list. |

**Response**

```json
{
  "jobs": [
    {
      "id": "66666666-6666-4666-8666-666666666666",
      "request_id": "77777777-7777-4777-8777-777777777777",
      "profileId": "11111111-1111-4111-8111-111111111111",
      "mode": "bin",
      "origin": "manual",
      "status": "ready",
      "processed": 2,
      "total": 2,
      "error": null,
      "cancel_requested": false,
      "expires_at": "2026-11-25T10:00:00.000Z"
    }
  ]
}
```

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`.
- `404` `Profile not found` when :id is not a UUID.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- `job` = {id, request_id, profileId, mode (bin|issuer), origin (manual|automatic), status (queued|running|ready|applied|failed|cancelled), processed, total, error (failure text or null), cancel_requested, expires_at}. total = the ATRIs to measure plus one final step that builds the proposals; processed counts finished steps.
- Visible jobs: those created by the same caller identity (same API key, or same member with the same role and ATRI grants), plus automatic jobs for admins without ATRI restrictions.
- Finished jobs leave the list once expired (24 hours after creation); queued and running ones always show.
- An empty list also when the generation storage is missing.

##### `POST /v1/bin-profiles/:id/generation-jobs`

**Scope** `routing.write` - **Start a BIN rule generation (preview job)**

Queues a background job that measures every active classic ATRI selecting the profile (one ATRI per step, evidence saved as it goes) and builds rule proposals with their evidence and a diff against the current rules. Always a preview: nothing is written until POST /v1/bin-generation-jobs/:id/apply. Generators: mapping = best MIDs per BIN or issuer by approval rate; scrubbing = approval, refund and net-loss checks; threeds = 3DS applied against holdout lift. Answers 202 with the job; poll GET /v1/bin-generation-jobs/:id.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400; a profile of another account: 404 `Profile not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Your idempotency key: the same requestId with the same profile, input and caller returns the existing job. |
| `mode` | enum: bin\|issuer; default `bin` | no | Propose rules per BIN or per canonical issuer. |
| `criteria` | object \| null | no | Overrides the profile's saved criteria for this run (fields criteria.* below; defaults in GET /v1/bin-profiles/defaults; keys left out take their defaults; not saved). null or omitted = the profile's criteria. |
| `criteria.window_hours` | integer 1..8760; default `168` | no | mapping only: the attempts window, in hours. (A scrubbing profile still sent in the old shape converts window_hours to window_days.) Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_bin_attempts` | integer 1..100000; default `20` | no | mapping only: a BIN (or issuer) needs this many attempts on the ATRI before a redirect is proposed. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_mid_attempts` | integer 1..100000; default `5` | no | mapping only: a MID needs this many attempts on that BIN to qualify as a target. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_ar_pct` | integer 0..100; default `60` | no | mapping only: a target MID must clear this approval rate (MID-rejection AR, in percent) on the BIN. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.max_targets` | integer 1..10; default `1` | no | mapping only: the top N qualifying MIDs per ATRI become the redirect pool (1 = pin the single best MID). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.window_days` | integer 1..365; default `30` | no | scrubbing and threeds: the attempts window, in days. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_attempts` | integer 1..100000; default `30` | no | scrubbing: a BIN is judged once it has this many attempts on the ATRI. threeds: the minimum attempts of EACH arm (3DS applied and holdout). Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_approvals` | integer 0..100000 \| null; default `5` | no | scrubbing only: the refund rule needs this many approvals on the BIN; null = no minimum. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.ar_max_pct` | number 0..100 \| null; default `15` | no | scrubbing only: AR rule, a BIN whose approvals / attempts is under this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.refund_max_pct` | number 0..100 \| null; default `25` | no | scrubbing only: refund rule, a BIN whose refunded / approved reaches this percent is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_net_loss_cents` | integer 0..100000000 \| null; default `5000` | no | scrubbing only: money rule, a BIN whose net is below minus this amount (cents) is scrubbed; null switches the rule off. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.rb_sync` | boolean; default `true` | no | scrubbing only: false opts the profile out of the external rebill tool's list (PUT /v1/scrub-bins never writes into it, and a new profile does not copy the account's rb_sync rules). Use false on a profile scoped to straight traffic. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.min_lift_pts` | number 0..100; default `5` | no | threeds only: the approval-rate lift, in points, between charges with a 3DS cryptogram and the holdout arm: a lift of at least +X proposes challenge_requested, at most -X proposes no_3ds. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enabled` | boolean; default `false` | no | every kind: true lets the periodic generator run this profile. Accepted for this run but without effect on it: the apply call decides whether the generated rules are enabled. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `criteria.auto_enforce` | boolean; default `false` | no | every kind: rules the periodic generator creates are inserted enabled (true) or staged disabled for review (false). Accepted for this run but without effect on it: the apply call decides whether the generated rules are enabled. Validated for the profile's kind; a key of another kind is dropped, an out-of-range value answers 400 Invalid criteria. |
| `replace_generated` | boolean; default `false` | no | At apply, first remove the profile's previous generated rules of the same mode that no proposal re-affirms. |
| `enabled` | boolean | no | Stored with the job; the apply call sets the final enabled flag of the inserted rules. |

**Request body**

```json
{
  "requestId": "77777777-7777-4777-8777-777777777777",
  "mode": "issuer",
  "criteria": {
    "min_lift_pts": 8
  },
  "replace_generated": true
}
```

**Response**

```json
{
  "job": {
    "id": "66666666-6666-4666-8666-666666666666",
    "request_id": "77777777-7777-4777-8777-777777777777",
    "profileId": "11111111-1111-4111-8111-111111111111",
    "mode": "issuer",
    "origin": "manual",
    "status": "queued",
    "processed": 0,
    "total": 2,
    "error": null,
    "cancel_requested": false,
    "expires_at": "2026-11-25T10:00:00.000Z"
  }
}
```

**Errors**

- `400` `Invalid generation parameters` (requestId missing or not a UUID, mode not bin or issuer, a wrong type, an unknown field: the body is strict; or :id not a UUID). `Invalid request` with `details.issues` (one {path, code, message} per problem) when `criteria` (or the profile's stored criteria) holds an out-of-range value for the profile kind.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `API key permissions changed` (a key restricted by scopes without `routing.write`, or the key's account changed), `Generation permissions changed`, `Generation grants changed`, `Signed-in account required`. Also `An attached ATRI is outside your grants`, `Profile includes a foreign ATRI`.
- `404` `Profile not found`.
- `409` `Request ID belongs to a different generation` (same requestId with another profile, input or caller); `A generation for this profile and mode is already active. Open it or cancel it.`; `Three generations are already active for this account`.
- `413` Request body over 64 KiB.
- `422` `At most 1000 ATRIs per generation`; `Generation configuration exceeds 10000 issuer definitions or MIDs`; `Profile exceeds 10000 rules; narrow the profile`; `Generation configuration exceeds 4 MB. Narrow the profile.`; `Profile, rules, ownership, fees or issuer definitions changed. Generate a fresh preview.`
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Background BIN generation is unavailable` (background jobs off) or `Required storage for BIN generation is unavailable. Complete the current database migrations.`
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- `job` = {id, request_id, profileId, mode (bin|issuer), origin (manual|automatic), status (queued|running|ready|applied|failed|cancelled), processed, total, error (failure text or null), cancel_requested, expires_at}. total = the ATRIs to measure plus one final step that builds the proposals; processed counts finished steps.
- At most one active (queued, running or ready) job per profile and mode, and three active jobs per account: cancel a ready job you will not apply.
- A profile no active classic ATRI selects finishes with no proposals.
- Transient failures retry up to three times (after about 5, 10 and 20 seconds); then status failed with `error`.
- The job and its result expire 24 hours after creation.

##### `GET /v1/bin-profiles/:id/rules`

**Scope** `routing.read` - **List the rules of a BIN profile**

Every rule of the profile in evaluation order (enabled or not), with the names the rules table needs: the redirect targets of a mapping profile (resolved within the account), the issuer banks behind the issuer keys, and the canonical issuer behind each BIN rule.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Response**

```json
{
  "rows": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 1,
      "enabled": true,
      "match_type": "issuer",
      "match_value": "CAPITAL ONE",
      "actions": {
        "mode": "challenge_requested"
      },
      "note": "issuer problem, not MID-fixable",
      "source": "manual",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    },
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 2,
      "enabled": true,
      "match_type": "country",
      "match_value": "FR",
      "actions": {
        "mode": "no_3ds"
      },
      "note": null,
      "source": "manual",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    }
  ],
  "total": 2,
  "enabled": 2,
  "targets": null,
  "issuers": {
    "CAPITAL ONE": "Capital One"
  },
  "bin_issuers": {}
}
```

| response field | type | description |
|---|---|---|
| `rows` | array<object> | Full rule rows (fields as in POST /v1/bin-profiles/:id/rules `rule`), by position then creation time. A GEO rule's match_value is the ISO alpha-2; no country names map is served. |
| `total` | integer | Rules. |
| `enabled` | integer | Rules that fire. |
| `targets` | object \| null | Mapping profiles only (null otherwise): {mid: {id: name}, atri: {id: name}, processor: {id: name}, acquirer: {id: name}, mcc: {mcc: mcc}} for every target the rules point at. A MID or ATRI of another account is absent (the rule is dead there); an MCC is present, named by itself, when one of the account's gateways carries it. |
| `issuers` | object | Issuer key to display name, for the issuer rules. |
| `bin_issuers` | object | {"<bin>": "<canonical issuer key>"} for every BIN rule whose BIN is enriched: lets a client warn when a BIN rule and an issuer rule overlap. |

**Errors**

- `400` `bad id` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Precedence at evaluation: a narrower match wins whatever the positions (bin, then issuer, then issuer_country, then country), then the lowest position among enabled rules of that type. One rule per profile per evaluation.

##### `POST /v1/bin-profiles/:id/rules`

**Scope** `routing.write` - **Create a rule**

Appends a rule (position = last + 1) to the profile. The body is validated for the profile's KIND: a scrubbing action on a 3DS profile is a 400. Every kind accepts the four match types. A mapping rule may only target the account's own MIDs and ATRIs, an MCC one of the account's gateways carries, or any listed processor or acquiring bank.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `match_type` | enum: bin\|issuer\|issuer_country\|country | **yes** | bin = the first 6 digits of the card number; issuer = the card's issuing bank (canonical key); issuer_country = the country that issued the card (from its BIN); country = the customer's country on the order (root country, else billing address country). Listed in precedence order. |
| `match_value` | string | **yes** | 1..160 characters, trimmed, normalised per match_type: bin = non-digits stripped, then exactly 6 digits; issuer = a bank label or key, stored as the canonical issuer key (upper-case words, punctuation and BANK / N.A. / NATIONAL ASSOCIATION / USA dropped, then folded through the issuer alias table; an excluded issuer programme is refused); issuer_country / country = an ISO alpha-2 code, an alpha-3 code or an English country name in any case, stored as the upper-case alpha-2 (an unknown country is refused). |
| `actions` | object | **yes** | The action, strict shape per profile kind (an unknown key is a 400): mapping {targets}, scrubbing {action, scope}, threeds {mode}. A shape of another kind is a 400. |
| `actions.targets` | array<object> | no | mapping only, required there: 1..50 targets forming the redirect pool. |
| `actions.targets[].type` | enum: mid\|processor\|acquirer\|atri\|mcc | no | mid = that MID; processor / acquirer = the ATRI's members behind that reference; mcc = the ATRI's active members whose gateway carries that MCC; atri = re-route the whole charge on that ATRI. |
| `actions.targets[].id` | string | no | A UUID for mid, processor, acquirer and atri; the 4-digit MCC for mcc. MIDs and ATRIs must belong to the account, an MCC must be carried by one of the account's gateways; processors and acquiring banks are global reference lists. |
| `actions.action` | literal "refuse" | no | scrubbing only, required there. |
| `actions.scope` | enum: initial\|rebill\|both | no | scrubbing only, required there: the flows on which the card is refused before any MID. |
| `actions.mode` | enum: challenge_requested\|challenge_mandated\|no_3ds | no | threeds only, required there: no_3ds = no inline authentication; challenge_requested / challenge_mandated = the challenge preference sent to the 3DS provider. |
| `enabled` | boolean; default `true` | no | false stages the rule without firing. |
| `note` | string \| null | no | Up to 500 characters after trimming. |
| `evidence` | object \| null | no | Free JSON object stored with the rule. |
| `source` | string | no | Accepted but ignored: a rule created here is always `manual`. |

**Request body**

```json
{
  "match_type": "issuer",
  "match_value": "Capital One, N.A.",
  "actions": {
    "mode": "challenge_requested"
  },
  "note": "issuer problem, not MID-fixable"
}
```

**Response**

```json
{
  "rule": {
    "id": "22222222-2222-4222-8222-222222222222",
    "profile_id": "11111111-1111-4111-8111-111111111111",
    "position": 3,
    "enabled": true,
    "match_type": "issuer",
    "match_value": "CAPITAL ONE",
    "actions": {
      "mode": "challenge_requested"
    },
    "note": "issuer problem, not MID-fixable",
    "source": "manual",
    "evidence": null,
    "created_by": "owner@example.com",
    "created_at": "2026-11-20T10:05:00.000Z",
    "updated_at": "2026-11-20T10:05:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `rule` | object | The rule row. |
| `rule.id` | uuid | Rule id. |
| `rule.profile_id` | uuid | Its profile. |
| `rule.position` | integer | Evaluation order within the profile (1 = first, gaps allowed). Changed with PUT /v1/bin-profiles/:id/rules/order. |
| `rule.enabled` | boolean | Only enabled rules fire. |
| `rule.match_type` | enum: bin\|issuer\|issuer_country\|country | What the rule matches on, listed in precedence order. |
| `rule.match_value` | string | bin: the 6 digits. issuer: the CANONICAL issuer key (upper-case words, folded through the issuer alias table). issuer_country / country: the ISO 3166-1 alpha-2 code, upper case. |
| `rule.actions` | object | Per kind: mapping {targets:[{type: mid\|processor\|acquirer\|atri\|mcc, id}]} (1..50 targets; id is a UUID, or the 4-digit MCC for type mcc); scrubbing {action: "refuse", scope: initial\|rebill\|both}; threeds {mode: challenge_requested\|challenge_mandated\|no_3ds}. |
| `rule.note` | string \| null | Operator note (up to 500 characters). |
| `rule.source` | string | manual, import, rb_sync (PUT /v1/scrub-bins replication), migration:<n> or generated:<run>. Generators only replace generated:* rules. |
| `rule.evidence` | object \| null | Generator metrics behind a generated rule; null otherwise. |
| `rule.created_by` | string \| null | E-mail of the caller that created it (the account owner's e-mail for an API key). |
| `rule.created_at` | string (ISO 8601) | Creation time. |
| `rule.updated_at` | string (ISO 8601) | Last change. |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (an unknown body field: the body is strict; an action shape of another kind; `a BIN is exactly 6 digits`; `an issuer key is upper-case words`; `issuer is excluded`; `unknown country`; a malformed mapping target such as a UUID for an mcc target), or a mapping target outside the account: `Unknown MID <id>`, `Unknown ATRI <id>`, `Unknown processor <id>`, `Unknown acquiring bank <id>`, `Unknown MCC <mcc>`.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- 201 on success.
- Two rules with the same value are allowed (the first by position wins); the API does not refuse the duplicate.
- The rule fires within about a minute on every server (rule sets are cached per profile and refreshed on write).
- An issuer value is stored canonical: "Capital One, N.A." and the autocomplete's key are the same rule.

##### `PUT /v1/bin-profiles/:id/rules/:rid`

**Scope** `routing.write` - **Update a rule**

Partial update of a rule. The merged rule is re-validated for the profile's kind (value normalised, actions checked, mapping targets checked within the account); only the fields sent are written, plus match_value when a match_type change renormalises it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |
| `rid` | uuid | **yes** | Rule id inside that profile. Not a UUID: 400 `bad id`; a rule of another profile: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `match_type` | enum: bin\|issuer\|issuer_country\|country | no | New match type; send match_value with it, the merged rule is re-validated for the new type. |
| `match_value` | string | no | 1..160 characters, trimmed, normalised per match_type: bin = non-digits stripped, then exactly 6 digits; issuer = a bank label or key, stored as the canonical issuer key (upper-case words, punctuation and BANK / N.A. / NATIONAL ASSOCIATION / USA dropped, then folded through the issuer alias table; an excluded issuer programme is refused); issuer_country / country = an ISO alpha-2 code, an alpha-3 code or an English country name in any case, stored as the upper-case alpha-2 (an unknown country is refused). |
| `actions` | object | no | Full replacement of the action, strict shape per profile kind (an unknown key is a 400): mapping {targets}, scrubbing {action, scope}, threeds {mode}. A shape of another kind is a 400. |
| `actions.targets` | array<object> | no | mapping only, required in the object: 1..50 targets forming the redirect pool. |
| `actions.targets[].type` | enum: mid\|processor\|acquirer\|atri\|mcc | no | mid = that MID; processor / acquirer = the ATRI's members behind that reference; mcc = the ATRI's active members whose gateway carries that MCC; atri = re-route the whole charge on that ATRI. |
| `actions.targets[].id` | string | no | A UUID for mid, processor, acquirer and atri; the 4-digit MCC for mcc. MIDs and ATRIs must belong to the account, an MCC must be carried by one of the account's gateways; processors and acquiring banks are global reference lists. |
| `actions.action` | literal "refuse" | no | scrubbing only, required in the object. |
| `actions.scope` | enum: initial\|rebill\|both | no | scrubbing only, required in the object: the flows on which the card is refused before any MID. |
| `actions.mode` | enum: challenge_requested\|challenge_mandated\|no_3ds | no | threeds only, required in the object: no_3ds = no inline authentication; challenge_requested / challenge_mandated = the challenge preference sent to the 3DS provider. |
| `enabled` | boolean | no | false stops the rule. |
| `note` | string \| null | no | Up to 500 characters; null clears it. |
| `evidence` | object \| null | no | Free JSON object; null clears it. |

**Request body**

```json
{
  "enabled": false,
  "note": "paused while measured"
}
```

**Response**

```json
{
  "rule": {
    "id": "22222222-2222-4222-8222-222222222222",
    "profile_id": "11111111-1111-4111-8111-111111111111",
    "position": 1,
    "enabled": false,
    "match_type": "issuer",
    "match_value": "CAPITAL ONE",
    "actions": {
      "mode": "challenge_requested"
    },
    "note": "paused while measured",
    "source": "manual",
    "evidence": null,
    "created_by": "owner@example.com",
    "created_at": "2026-11-20T10:05:00.000Z",
    "updated_at": "2026-11-21T08:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `rule` | object | The rule after the update (full rule row); unchanged when the body changes nothing. |

**Errors**

- `400` `bad id` when :id or :rid is not a UUID. Also `Invalid` with `details` (strict body: `position` or `source` is refused, use PUT /v1/bin-profiles/:id/rules/order; an action of another kind; a value invalid for the merged type: `a BIN is exactly 6 digits`, `an issuer key is upper-case words`, `issuer is excluded`, `unknown country`), or a mapping target outside the account (`Unknown MID <id>`, `Unknown ATRI <id>`, `Unknown processor <id>`, `Unknown acquiring bank <id>`, `Unknown MCC <mcc>`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account, or no such rule in it.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Changing match_type alone re-validates the CURRENT match_value for the new type (a BIN rule switched to country fails unless you send a country): send both.
- Concurrent edits to different fields both survive; two edits to the same field are last-write-wins.

##### `DELETE /v1/bin-profiles/:id/rules/:rid`

**Scope** `routing.write` - **Delete a rule**

Removes one rule. Its decision-log rows stay until the 60-day retention removes them.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |
| `rid` | uuid | **yes** | Rule id inside that profile. Not a UUID: 400 `bad id`; a rule of another profile: 404 `Not found`. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the rule was deleted. |

**Errors**

- `400` `bad id` when :id or :rid is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account, or no such rule in it.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Positions are NOT renumbered on delete (gaps are fine; order is relative).

##### `POST /v1/bin-profiles/:id/rules/:rid/duplicate`

**Scope** `routing.write` - **Duplicate a rule**

Inserts a copy RIGHT AFTER the original (the rules below shift down one). The copy keeps the match, actions and enabled flag; it is a manual rule (source manual, no evidence) whose note ends with "(copy)". No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |
| `rid` | uuid | **yes** | Rule id inside that profile. Not a UUID: 400 `bad id`; a rule of another profile: 404 `Not found`. |

**Response**

```json
{
  "rule": {
    "id": "33333333-3333-4333-8333-333333333333",
    "profile_id": "11111111-1111-4111-8111-111111111111",
    "position": 2,
    "enabled": true,
    "match_type": "issuer",
    "match_value": "CAPITAL ONE",
    "actions": {
      "mode": "challenge_requested"
    },
    "note": "issuer problem, not MID-fixable (copy)",
    "source": "manual",
    "evidence": null,
    "created_by": "owner@example.com",
    "created_at": "2026-11-20T10:05:00.000Z",
    "updated_at": "2026-11-20T10:05:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `rule` | object | The copy (full rule row). |

**Errors**

- `400` `bad id` when :id or :rid is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account, or no such rule in it.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- 201 on success.

##### `POST /v1/bin-profiles/:id/rules/bulk`

**Scope** `routing.write` - **Bulk enable, disable or delete rules**

Enables or disables a set of rules of the profile, or deletes them, in one call. Ids that are not rules of this profile are ignored.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | array<uuid> | **yes** | 1..5000 rule ids. |
| `enabled` | boolean | no | Set this enabled flag on every id. |
| `delete` | boolean | no | true deletes every id (wins over enabled). |

**Request body**

```json
{
  "ids": [
    "22222222-2222-4222-8222-222222222222"
  ],
  "enabled": false
}
```

**Response**

```json
{
  "updated": 1
}
```

| response field | type | description |
|---|---|---|
| `updated` | integer | With enabled: rules whose flag actually changed. |
| `deleted` | integer | With delete: rules removed. |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (ids missing, empty, over 5000 or not UUIDs; a flag that is not a boolean) or `Nothing to do: send enabled or delete` (neither enabled nor delete true).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Deleted rules do not come back; positions of the remaining rules are not renumbered.

##### `GET /v1/bin-profiles/:id/rules/export.csv`

**Scope** `routing.read` - **Export the rules of a profile (CSV)**

The profile's rules as a CSV file, one row per rule in evaluation order, columns order,input_type,input_value,action,targets,enabled,notes,names: `order` = the stored position; `input_type` = bin | issuer | issuer_country | country; `input_value` = the 6-digit BIN, the canonical issuer key or the ISO alpha-2; `action` = `map` (mapping), `refuse:initial` | `refuse:rebill` | `refuse:both` (scrubbing), `challenge_requested` | `challenge_mandated` | `no_3ds` (3DS); `targets` (mapping only) = `mid:<uuid>|processor:<uuid>|acquirer:<uuid>|atri:<uuid>|mcc:<4 digits>`; `enabled` = true | false; `notes`; `names` = for humans only (the issuer bank, the targets' names), ignored on import. The import reads the same columns, so export then import in replace mode reproduces the profile.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Response**

```json
order,input_type,input_value,action,targets,enabled,notes,names
1,issuer,CAPITAL ONE,challenge_requested,,true,"issuer problem, not MID-fixable",Capital One
2,issuer_country,VE,challenge_mandated,,true,,
3,country,FR,no_3ds,,false,paused,
```

**Errors**

- `400` `bad id` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Two exports are already running. Retry when one finishes.` (at most two CSV exports stream at once per server instance).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- Content-Type text/csv; Content-Disposition attachment; filename="bin-rules-<kind>-<profile name slug>.csv"; CRLF line ends, RFC 4180 quoting, no byte order mark.
- Mapping targets are ids (names can change or repeat); the `names` column carries their names, and the issuer's display name for issuer rules. GEO rows carry no name.
- `order` keeps gaps left by deleted rules; an import in replace mode renumbers 1..n.

##### `POST /v1/bin-profiles/:id/rules/import`

**Scope** `routing.write` - **Import rules from CSV: commit**

Step 2: writes the rules a preview validated, in ONE transaction under the profile lock, and records a durable outcome so a retry never writes twice. replace = the file becomes the profile (every current rule is removed first, the file's rules take positions 1..n); append = the file's rules follow the current ones. Imported rules carry source `import`.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | uuid | **yes** | The `token` of a preview of THIS profile, within its 15 minutes. |
| `mode` | enum: replace\|append | **yes** | replace = the file becomes the profile; append = the file's rules follow the current ones. |
| `version` | literal 3 | no | 3 = compact receipt {outcomeId, mode, inserted, removed} instead of the full answer with the inserted rules. Requires requestId. |
| `requestId` | uuid | no | Your idempotency key, required with version 3. Persist it before sending and reuse it only with the same token and mode. Omitted: the token is the identity. |

**Request body**

```json
{
  "token": "88888888-8888-4888-8888-888888888888",
  "mode": "replace",
  "version": 3,
  "requestId": "77777777-7777-4777-8777-777777777777"
}
```

**Response**

```json
{
  "mode": "replace",
  "inserted": 2,
  "removed": 1,
  "rules": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 1,
      "enabled": true,
      "match_type": "bin",
      "match_value": "411111",
      "actions": {
        "mode": "no_3ds"
      },
      "note": "prepaid",
      "source": "import",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    },
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 2,
      "enabled": true,
      "match_type": "issuer",
      "match_value": "CAPITAL ONE",
      "actions": {
        "mode": "challenge_requested"
      },
      "note": "example",
      "source": "import",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `mode` | enum: replace\|append | The mode applied. |
| `inserted` | integer | Rules written (the preview's `valid`). |
| `removed` | integer | replace: the rules deleted first; append: 0. |
| `rules` | array<object> | Without version 3 only: the inserted rule rows (source import, positions as written). |
| `outcomeId` | uuid | Version 3 only: the saved outcome's id. |

**Errors**

- `400` `Invalid` with `details` (:id not a UUID; token not a UUID; mode not replace or append; an unknown field: the body is strict; `Version 3 requires a request identity`); or `The { csv } / { rows } body is retired: POST .../rules/import/preview { csv } first, then send { token, mode }` (the message uses an ellipsis character) when the body carries csv or rows.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `Import permission required` (role other than admin, super_admin or user) and the access re-checks of the import (`A signed-in account is required`, `Import API key or account access changed`, `Import author no longer has access`, `Import account or role changed`, `Import account no longer has access`, `Import permissions changed`).
- `404` `Profile not found`; `Preview not found` or `Import result not found` when the token or requestId belongs to another caller identity.
- `409` `Preview unavailable, expired or already used. Check any uncertain request before creating another preview.`; `This preview was already consumed. Check its original saved result; do not preview and retry automatically.`; `Saved request identity belongs to another import` (same identity, other token or mode); `Preview has <n> blocking errors`; `A mapping target is no longer available in this account. Preview again.`; or the rules changed since the preview (message starts `Preview is stale: the rules changed since`). Nothing is written.
- `410` `The saved import result expired. This token remains consumed; do not repeat the import.` (a replay after the 30-day result retention).
- `413` With version 3 only: `This profile exceeds the recoverable import preview limit (200,000 rules / 64 MiB). No rules changed.`
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Required storage for BIN imports is unavailable. Complete the current database migrations.`
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- Exactly once: a retry with the same identity (requestId, or the token when requestId is omitted), the same token and the same mode returns the saved outcome without writing again. After an uncertain answer read GET /v1/bin-profiles/:id/rules/import/outcomes/:requestId; never preview and commit again blindly.
- replace also removes rb_sync rules (the next PUT /v1/scrub-bins re-inserts them) and generated rules (the next generation re-creates them); the preview's would_remove says how many.
- Mapping targets are re-checked at commit: a MID, ATRI or MCC that left the account since the preview stops the whole commit.
- Saved outcomes keep their payload for 30 days; the token stays consumed forever.

##### `GET /v1/bin-profiles/:id/rules/import/outcomes/:requestId`

**Scope** `routing.read` - **Read a saved BIN import result**

Reads the committed result of a BIN rule import by the requestId sent with POST /v1/bin-profiles/:id/rules/import, without writing anything. Use it when an import answer was lost (timeout, disconnect) instead of importing again.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | BIN profile id of the caller's account. |
| `requestId` | string (uuid) | **yes** | The requestId of the import; an import migrated from the older flow is found by its preview token. |

**Response**

```json
{
  "outcomeId": "8c4e2a10-6b3d-4f7a-9e25-1d0b7c3a5f62",
  "mode": "append",
  "inserted": 2,
  "removed": 0
}
```

| response field | type | description |
|---|---|---|
| `outcomeId` | string (uuid) | Id of the saved result. |
| `mode` | enum: append \| replace | Import mode that was applied. |
| `inserted` | integer | Rules written by the import. |
| `removed` | integer | Rules removed by the import (replace mode). |

**Errors**

- `400` {"error":"Invalid import request identity"} when id or requestId is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Import API key or account access changed"}; {"error":"Import permissions changed"} when the account's ATRI grants changed.
- `404` {"error":"Profile not found"}; {"error":"No confirmed import result was found. Keep the saved request identity; this is not permission to import again."}; {"error":"Saved import results are unavailable"} when the deployment has no result storage.
- `410` {"error":"The saved import result expired. This token remains consumed; do not repeat the import."}
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- A 404 means no confirmed result for this caller and requestId. Keep the requestId; a 404 is not permission to import again with a new identity.
- A saved result expires: 410 means the import happened but its result is no longer readable; the preview token stays consumed, so do not repeat the import.
- No automatic retry and no write: this read never applies rules.
- Previews and import results are bound to the caller that created them (the same API key, or the same login) and to the account's current ATRI grants: another key of the same account, or a caller whose grants changed, gets 404.

##### `POST /v1/bin-profiles/:id/rules/import/preview`

**Scope** `routing.read` - **Import rules from CSV: preview**

Step 1 of a CSV import into one profile: parses and validates the whole file (every row normalised and checked for the profile's kind, cross-checked against the file itself and the current rules), saves the full per-row report and the rule lists each mode would produce as a paged snapshot, and returns counts plus a `token`. Nothing is written to the rules. Read the report and the lists with GET /v1/bin-profiles/:id/rules/import/previews/:token, then commit with POST /v1/bin-profiles/:id/rules/import.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `csv` | string | **yes** | The CSV text: 1..5,000,000 characters and at most 10 MiB in UTF-8, a header row (order,input_type,input_value,action,targets,enabled,notes; a trailing names column and a leading profile column are read, names is ignored; the v1 column names still work) and 1..10,000 data rows. |
| `version` | literal 3 | no | Accepted for compatibility; the answer is the same compact summary with or without it. |

**Request body**

```json
{
  "csv": "order,input_type,input_value,action,targets,enabled,notes\n1,bin,411111,no_3ds,,true,prepaid\n2,issuer,\"Capital One, N.A.\",challenge_requested,,,example\n3,country,France,challenge_mandatedd,,true,\n"
}
```

**Response**

```json
{
  "version": 3,
  "token": "88888888-8888-4888-8888-888888888888",
  "expires_at": "2026-11-24T10:15:00.000Z",
  "total": 3,
  "valid": 2,
  "blocking": 1,
  "warnings": 1,
  "file_warnings": [],
  "would_remove": {
    "total": 1,
    "rb_sync": 0,
    "generated": 0
  },
  "replace_warnings": [
    "replace removes every current rule (1)"
  ],
  "counts": {
    "report": 3,
    "replace": 2,
    "append": 3
  }
}
```

| response field | type | description |
|---|---|---|
| `version` | 3 | Always 3. |
| `token` | uuid | The preview's token for the commit, issued even when blocking > 0 (the commit then answers 409). |
| `expires_at` | string (ISO 8601) | The token's expiry (15 minutes). |
| `total` | integer | Data rows in the file. |
| `valid` | integer | Rows the commit would write. |
| `blocking` | integer | Rows with at least one error. The commit answers 409 while it is above 0. |
| `warnings` | integer | Rows with at least one warning (a duplicate that never fires, a rule the profile already has, precedence shadowing, a BIN the account never saw, targets ignored on a non-mapping profile, a note clipped to 500 characters). |
| `file_warnings` | array<string> | File-level notes (a v1 header, ignored columns). |
| `would_remove` | { total, rb_sync, generated } | What REPLACE would remove: every current rule, with the two sources a sync or a generator would put back. |
| `replace_warnings` | array<string> | The replace-mode consequences in words, for example `replace removes every current rule (n)`. |
| `counts` | { report, replace, append } | Rows saved in each section of the snapshot (report = one row per file line; replace / append = the profile's rule list after each mode). |

**Errors**

- `400` `Invalid` with `details` (no csv, an empty one or over 5,000,000 characters, version other than 3, an unknown field: the body is strict; or :id not a UUID); `Choose between 1 and 10,000 CSV rows`; a CSV format error (`Missing columns: ...`, `Unclosed quote opened on line <n>: ...`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account. Also `Import permission required` (role other than admin, super_admin or user) and the access re-checks of the import (`A signed-in account is required`, `Import API key or account access changed`, `Import author no longer has access`, `Import account or role changed`, `Import account no longer has access`, `Import permissions changed`).
- `404` `Profile not found`: no such profile in this account.
- `413` `CSV exceeds the preview limit` (over 10 MiB UTF-8); `Preview exceeds 64 MiB. No token was published and no rules changed.`; `This profile exceeds the recoverable import preview limit (200,000 rules / 64 MiB). No rules changed.`; or a request body over 10 MiB, refused before the route runs.
- `429` `Another preview is being prepared. Retry the preview shortly; no rules changed.` (one preview is prepared at a time on the platform); `Too many saved previews. Wait for older previews to expire.` (10 saved previews per account, 500 overall, until older ones expire and are cleaned); or the per-IP rate limit (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Paged import previews are unavailable` (storage missing) or `Preview deadline exceeded. No preview was published.` (20-second overall budget).
- `504` The request's time budget ran out before it finished (message starts `The request took too long and was cancelled`). Nothing was committed by this request; read the state again before retrying.

**Gotchas**

- The answer never carries the per-row report or the rule lists: page them with GET /v1/bin-profiles/:id/rules/import/previews/:token?section=report|append|replace&offset=&limit= (limit up to 250).
- The token expires after 15 minutes and is spent by one commit.
- Row format: input_type bin | issuer | issuer_country | country; action `map` (mapping, with targets like `mid:<uuid>|processor:<uuid>|acquirer:<uuid>|atri:<uuid>|mcc:<4 digits>`), `refuse:initial` | `refuse:rebill` | `refuse:both` (scrubbing), `challenge_requested` | `challenge_mandated` | `no_3ds` (3DS); enabled true or false (blank = true); notes up to 500 characters; a blank order goes last in file order.
- Every problem of a row is reported at once (wrong value shape, an action of another tool, an unknown or foreign target, a profile cell naming another profile, a contradiction with an earlier line); a BIN the account never saw is only a warning.

##### `GET /v1/bin-profiles/:id/rules/import/previews/:token`

**Scope** `routing.read` - **Read a BIN import preview page**

Reads one page of a saved BIN rule import preview: the per-line report of the CSV, or the rules that an append or a replace import would leave on the profile, in file and evaluation order, with the preview summary. The preview is created by POST /v1/bin-profiles/:id/rules/import (dry run); nothing is written by this read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | BIN profile id of the caller's account. |
| `token` | string (uuid) | **yes** | Preview token returned by the import dry run (summary.token). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `section` | enum: report \| append \| replace; default `report` | no | report = one row per CSV line with its validation result; append = the rules after an append import (current rules plus the file); replace = the rules after a replace import (the file only). |
| `offset` | integer; default `0` | no | Rows to skip, 0 to 210000. |
| `limit` | integer; default `100` | no | Rows per page, 1 to 250. |

**Response**

```json
{
  "rows": [
    {
      "line": 2,
      "ok": true,
      "errors": [],
      "warnings": [],
      "rule": {
        "order": 1,
        "input_type": "bin",
        "input_value": "411111",
        "action": "block",
        "targets": "",
        "enabled": true,
        "notes": "Example rule"
      }
    }
  ],
  "total": 1,
  "offset": 0,
  "limit": 100,
  "summary": {
    "version": 3,
    "token": "5d0c7a2e-1f4b-4c8e-9a61-2b7f3e9d4c10",
    "expires_at": "2026-11-20T15:30:00.000Z",
    "total": 1,
    "valid": 1,
    "blocking": 0,
    "warnings": 0,
    "file_warnings": [],
    "would_remove": {
      "total": 0,
      "rb_sync": 0,
      "generated": 0
    },
    "replace_warnings": [],
    "counts": {
      "report": 1,
      "replace": 1,
      "append": 1
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | The requested slice of the section, in file and evaluation order. section=report: {line, ok, errors[], warnings[], rule: {order, input_type, input_value, action, targets, enabled, notes} \| null} per CSV line. section=append or replace: {position, id (null for a rule from the file), line (null for an existing rule), match_type, match_value, actions, enabled, note, source} per resulting rule. |
| `total` | integer | Number of rows in the section (summary.counts[section]). |
| `offset` | integer | Echo of offset. |
| `limit` | integer | Echo of limit. |
| `summary` | object | The preview summary: version (3), token, expires_at, total, valid, blocking (lines that block the import), warnings, file_warnings, would_remove {total, rb_sync, generated} (rules a replace would remove), replace_warnings (sentences), counts {report, replace, append}. |

**Errors**

- `400` {"error":"Invalid preview page"} when id or token is not a uuid, section is not report, append or replace, or offset / limit is out of range.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Import API key or account access changed"} when the key was deactivated, its owner banned or the account changed; {"error":"Import permissions changed"} when the account's ATRI grants changed since the request scope was resolved.
- `404` {"error":"Profile not found"} when the profile is not one of the account's; {"error":"Preview not found"} for an unknown token or a token created by another caller; {"error":"Saved previews are unavailable"} when the deployment has no preview storage.
- `410` {"error":"Preview expired or consumed. Check saved import progress."}
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- A preview expires (summary.expires_at) and is consumed by its import: an expired or consumed token answers 410. Check the saved import result instead of importing again.
- Page through with offset and limit (max 250 per page); rows keep the file order.
- Previews and import results are bound to the caller that created them (the same API key, or the same login) and to the account's current ATRI grants: another key of the same account, or a caller whose grants changed, gets 404.

##### `PUT /v1/bin-profiles/:id/rules/order`

**Scope** `routing.write` - **Reorder the rules of a profile**

Renumbers the profile's rules 1..n in one statement: the listed ids take the listed order, the rules left out follow in their previous relative order, ids that are not in the profile are ignored, a repeated id counts once at its first place.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id. Not a UUID: 400 `bad id`; a profile of another account: 404 `Not found`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | array<uuid> | **yes** | 1..5000 rule ids, in the wanted order. |

**Request body**

```json
{
  "ids": [
    "33333333-3333-4333-8333-333333333333",
    "22222222-2222-4222-8222-222222222222"
  ]
}
```

**Response**

```json
{
  "rows": [
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 1,
      "enabled": true,
      "match_type": "country",
      "match_value": "FR",
      "actions": {
        "mode": "no_3ds"
      },
      "note": null,
      "source": "manual",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    },
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "profile_id": "11111111-1111-4111-8111-111111111111",
      "position": 2,
      "enabled": true,
      "match_type": "issuer",
      "match_value": "CAPITAL ONE",
      "actions": {
        "mode": "challenge_requested"
      },
      "note": "issuer problem, not MID-fixable",
      "source": "manual",
      "evidence": null,
      "created_by": "owner@example.com",
      "created_at": "2026-11-20T10:05:00.000Z",
      "updated_at": "2026-11-20T10:05:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array<object> | The whole rule list in its new order (full rule rows). |

**Errors**

- `400` `bad id` when :id is not a UUID. Also `Invalid` with `details` (ids missing, empty, over 5000, or not UUIDs).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `404` `Not found`: no such profile in this account (another account's profile answers the same).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Send the FULL list after a drag: a partial list moves the named rules to the top.

##### `GET /v1/bin-profiles/csv-template`

**Scope** `routing.read` - **CSV template for a rules import**

A downloadable template for the tool: the CSV header and FOUR example rows, one per input type (bin, issuer, issuer_country, country), covering the actions of the kind: mapping `map` on every row (targets mid, processor + mcc, atri, mid); scrubbing `refuse:both`, `refuse:rebill`, `refuse:initial` twice; 3DS `no_3ds`, `challenge_requested`, `challenge_mandated`, `challenge_requested`; one row disabled to show `enabled`. The mapping rows carry placeholder ids of the right shape (UUID or 4-digit MCC): replace them with the account's own ids before importing; the `names` column says which.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: mapping\|scrubbing\|threeds | **yes** | The tool: mapping (redirect rules), scrubbing (refusal rules) or threeds (3DS mode rules). Missing or any other value: 400. |

**Response**

```json
order,input_type,input_value,action,targets,enabled,notes,names
1,bin,411111,no_3ds,,true,example: never authenticate this BIN inline,
2,issuer,CAPITAL ONE,challenge_requested,,true,example: ask the bank for a challenge,Capital One
3,issuer_country,VE,challenge_mandated,,true,example: force the challenge on cards issued in Venezuela,Venezuela
4,country,FR,challenge_requested,,false,example: request a challenge for customers in France (disabled),France
```

**Errors**

- `400` `kind is required: mapping | scrubbing | threeds` when kind is missing or unknown.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Content-Disposition attachment; filename="bin-rules-<kind>-template.csv". Static content: the same file for every account; no account data is read.
- Some mapping notes and names cells contain non-ASCII characters (a guillemet and an arrow); keep the file UTF-8.

##### `GET /v1/bin-profiles/defaults`

**Scope** `routing.read` - **BIN profile criteria defaults**

The code defaults of the three rule generators' criteria: what a new profile of each kind starts with, and the value any key left out of `criteria` takes on create, on update (criteria is a full replacement) and in a generation job.

*No parameters.*

**Response**

```json
{
  "mapping": {
    "window_hours": 168,
    "min_bin_attempts": 20,
    "min_mid_attempts": 5,
    "min_ar_pct": 60,
    "max_targets": 1,
    "auto_enforce": false,
    "auto_enabled": false
  },
  "scrubbing": {
    "window_days": 30,
    "min_attempts": 30,
    "min_approvals": 5,
    "ar_max_pct": 15,
    "refund_max_pct": 25,
    "min_net_loss_cents": 5000,
    "auto_enforce": false,
    "auto_enabled": false,
    "rb_sync": true
  },
  "threeds": {
    "window_days": 30,
    "min_attempts": 30,
    "min_lift_pts": 5,
    "auto_enforce": false,
    "auto_enabled": false
  }
}
```

| response field | type | description |
|---|---|---|
| `mapping` | object | window_hours (integer 1..8760, attempts window); min_bin_attempts (1..100000, attempts a BIN or issuer needs on the ATRI); min_mid_attempts (1..100000, attempts a MID needs on it to qualify); min_ar_pct (integer 0..100, approval rate a target MID must clear); max_targets (1..10, top qualifying MIDs per ATRI forming the redirect pool; 1 = a single best MID); auto_enforce; auto_enabled. |
| `scrubbing` | object | window_days (1..365); min_attempts (1..100000); min_approvals (0..100000 or null); ar_max_pct (0..100 or null: refuse when approvals / attempts is below it); refund_max_pct (0..100 or null: refuse when refunded / approved reaches it); min_net_loss_cents (0..100000000 or null: refuse when the net loss exceeds it); auto_enforce; auto_enabled; rb_sync (default true; false keeps the profile out of the PUT /v1/scrub-bins replication: created without the RB-synced set and never written by the sync). A null check is off. A legacy window_hours is converted to window_days. |
| `threeds` | object | window_days (1..365); min_attempts (1..100000, per arm: 3DS applied and holdout); min_lift_pts (0..100: a lift of at least +min_lift_pts proposes challenge_requested, at most -min_lift_pts proposes no_3ds); auto_enforce; auto_enabled. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- auto_enabled = the periodic generator runs the profile at all; auto_enforce = its generated rules are inserted enabled (else staged disabled). A manual generation job ignores both and uses its own `enabled`.
- Static content: the same answer for every account.

##### `GET /v1/bin-profiles/export.csv`

**Scope** `routing.read` - **Export every profile of a kind (CSV)**

Every rule of every profile of one kind on the account in ONE CSV file: the columns of GET /v1/bin-profiles/:id/rules/export.csv behind a leading `profile` column (the profile's name, unique per kind), profiles in name order, rules in evaluation order. A backup or review file: imports are per profile, and a row whose `profile` names another profile is a blocking error there, so filter the file before importing it into one profile.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: mapping\|scrubbing\|threeds | **yes** | The tool: mapping (redirect rules), scrubbing (refusal rules) or threeds (3DS mode rules). Missing or any other value: 400. |

**Response**

```json
profile,order,input_type,input_value,action,targets,enabled,notes,names
Issuer 3DS,1,bin,411111,no_3ds,,true,,
Issuer 3DS,2,issuer,CAPITAL ONE,challenge_requested,,false,,Capital One
Second,1,country,FR,challenge_mandated,,true,,France
```

**Errors**

- `400` `kind is required: mapping | scrubbing | threeds` when kind is missing or unknown.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module; `No account` when the caller has no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). Also `Two exports are already running. Retry when one finishes.` (at most two CSV exports stream at once per server instance).

**Gotchas**

- Content-Type text/csv; Content-Disposition attachment; filename="bin-rules-<kind>-all-<YYYY-MM-DD>.csv" (UTC date). CRLF line ends, RFC 4180 quoting, no byte order mark.
- Profiles without rules contribute no line; an account without rules of that kind gets the header line only.

##### `GET /v1/bin-profiles/import-capabilities`

**Scope** `routing.read` - **BIN import capability**

Says whether the paged BIN rule import (version 3 previews and saved import results) is available on this deployment. Call it before POST /v1/bin-profiles/:id/rules/import when you want the paged preview and a saved, re-readable import result.

*No parameters.*

**Response**

```json
{
  "outcomes": true
}
```

| response field | type | description |
|---|---|---|
| `outcomes` | boolean | True when the storage for paged previews and saved import results exists, so GET /v1/bin-profiles/:id/rules/import/previews/:token and /outcomes/:requestId can answer. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database read exceeds its budget.

**Gotchas**

- Read-only and cheap (5-second budget). A false answer means the paged preview and the saved-result read answer 404 on this deployment.

##### `GET /v1/bin-scrub-enabled`

**Scope** `routing.read` - **Read the BIN scrubbing master switch**

Reads the account's BIN scrubbing master switch (account_settings.bin_scrub_enabled, default true). When false, the scrubbing profile of every ATRI of the account is still evaluated and logged but never applied (the decision log shows applied:false, reason "master switch off").

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | The persisted master switch. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Read through a 30-second per-instance settings cache shared with the charge path: it can lag a change made through another API instance by up to 30 seconds.
- An account with no settings row reads the default (true).

##### `PUT /v1/bin-scrub-enabled`

**Scope** `routing.write` - **Toggle BIN scrubbing globally**

Switches BIN scrubbing on or off for the caller's account at runtime (account_settings.bin_scrub_enabled). When off, the scrubbing profile of every ATRI of the account is still evaluated and logged (decision log) but never applied: no charge is refused by a scrubbing rule.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | **yes** | true = BIN scrubbing active, false = gate skipped globally. Must be a real JSON boolean; "true" as a string is rejected with 400. |

**Request body**

```json
{
  "enabled": false
}
```

**Response**

```json
{
  "ok": true,
  "enabled": false
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true when the update ran. |
| `enabled` | boolean | Echo of the value that was persisted. |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): enabled missing or not a JSON boolean ("true" as a string is refused).
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"} when the key's scopes lack routing.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- A kill switch for the whole feature on this account, not for one rule: setting false stops every scrubbing rule from refusing, and nothing in the rules list shows it.
- The account's settings row is created when missing, then updated (updated_by = the caller). The calling instance's cache is refreshed at once; other API instances follow within 30 seconds.
- Profiles and rules are managed under /v1/bin-profiles; this switch only gates whether they apply.

##### `GET /v1/bin-scrub-hits`

**Scope** `routing.read` - **List legacy BIN scrub hits**

Legacy log, read-only: the BIN scrub hits of the caller's account recorded before profiles replaced the legacy rules (bin_scrub_hits), newest first. Nothing writes it any more: every evaluation of a scrubbing profile is in the decision log (GET /v1/bin-profiles/:id/decisions). Use it only for history.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer 1..10000; default `50` | no | Page size, 1..10000. Coerced from a string; outside the range is a 400 (no clamp). |
| `offset` | integer >= 0; default `0` | no | Row offset, min 0. Coerced from string. |

**Response**

```json
{
  "rows": [
    {
      "id": "9f1c1c2e-1a3b-4c55-8d90-2b7e6f0a1c34",
      "created_at": "2026-08-26T13:41:22.108Z",
      "bin": "400344",
      "scope": "initial",
      "flow": "initial",
      "source": "auto:initial-loss",
      "order_id": "ORD-88421",
      "transaction_id": "6d2a54b1-0f77-42d0-9d0f-6a1c2f4e8b90",
      "total": 2
    },
    {
      "id": "1b7d0f44-2c88-4a1e-bb31-77c5a9e2d4f1",
      "created_at": "2026-08-26T12:03:57.882Z",
      "bin": "517805",
      "scope": "both",
      "flow": "rebill",
      "source": "rb-seed-2026-01",
      "order_id": null,
      "transaction_id": null,
      "total": 2
    }
  ],
  "total": 2
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Hits ordered by created_at DESC (newest first). |
| `rows[].id` | string (uuid) | Hit id. |
| `rows[].created_at` | string (ISO8601 timestamptz) | When the block happened. |
| `rows[].bin` | string | The 6-digit BIN that matched. |
| `rows[].scope` | enum: initial\|rebill\|both | The MATCHED RULE's scope at block time (a historical snapshot - the rule may have changed or been deleted since). |
| `rows[].flow` | enum: initial\|rebill | The flow of the charge that was actually blocked. Differs from scope when the rule was 'both'. |
| `rows[].source` | string\|null | The matched rule's source tag at block time. |
| `rows[].order_id` | string\|null | Merchant order id, when the blocked charge carried one. |
| `rows[].transaction_id` | string (uuid)\|null | Linked transaction, when one existed at block time. |
| `rows[].total` | integer | LEAK from count(*) over() - same value as top-level total, present on every row. Not a hit field. |
| `total` | integer | Total hits in the table across all pages. |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): limit outside 1..10000, a negative or non-integer offset.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.read"} when the key's scopes lack routing.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- No new rows: the decision log (GET /v1/bin-profiles/:id/decisions) is the live equivalent.
- No filters (no BIN, flow, date or source): page through the whole log, newest first.
- total comes from a window count over the returned page: an offset past the end gives rows:[] and total:0 even when the log has rows.
- Every row also carries total (the same window count). The stored IP address is never returned.
- scope and source are copies taken at block time: they do not follow later edits of the rule.

##### `POST /v1/bin-scrub-rules/import`

**Scope** `routing.write` - **Import legacy scrub CSV into a scrubbing profile**

Bulk-imports the RB-Scheduler CSV (bin,scope,enforced,reason,source) or a parsed rules array into a scrubbing profile of the caller's account: the account's default scrubbing profile, or the one profile_id names. Each row becomes a BIN rule {action: refuse, scope}, enabled = enforced, note = reason plus the source tag in brackets, source "import", appended after the profile's rules. An existing "import" rule of the profile with the same BIN is replaced, never duplicated. Valid rows are written in one transaction; invalid rows are reported by index and skipped.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `csv` | string <= 5,000,000 chars | no | Raw CSV text, columns bin,scope,enforced,reason,source. Blank lines, lines starting with # and a header line starting with "bin," are skipped; a line without bin or scope is skipped. scope is lower-cased; enforced matches true\|1\|yes (case-insensitive), empty = true; the last field is the source tag (so a reason cannot contain a comma). When present and non-empty it wins and rules is ignored. The whole request body is limited to 1 MB, so the practical CSV limit is about 1 MB (413 beyond). |
| `rules` | object[] <= 20000 | no | Pre-parsed rows {bin, scope, enforced?, reason?, source?}, used only when csv is absent or empty. |
| `rules[].bin` | string | **yes** | The BIN. Non-digits are stripped, then it must be exactly 6 digits; otherwise the row is reported in errors[] ("a BIN is exactly 6 digits") and not inserted. |
| `rules[].scope` | enum: initial\|rebill\|both | **yes** | The flows the rule refuses (a rule's actions.scope). |
| `rules[].enforced` | boolean; default `true` | no | Becomes the rule's enabled flag. |
| `rules[].reason` | string\|null; default `null` | no | Becomes the rule's note (with the source tag appended in brackets), cut to 500 characters. |
| `rules[].source` | string\|null; default `null` | no | Legacy batch tag; kept in the note only - the rule's source is always 'import'. |
| `profile_id` | string (uuid) | no | A scrubbing profile of the account to import into instead of the default one (404 when foreign / unknown, 400 when not a scrubbing profile). |

**Request body**

```json
{
  "csv": "# RB scrub export 2026-01\nbin,scope,enforced,reason,source\n400344,initial,true,Bad AR,rb-seed-2026-01\n517805,both,false,,rb-seed-2026-01\n"
}
```

**Response** `201`

```json
{
  "imported": 2,
  "replaced": 0,
  "received": 2,
  "errors": [],
  "profile": { "id": "6f1c7e93-2d4a-4b1e-9c0f-3a5b7d9e1f24", "name": "Legacy default" }
}
```

| response field | type | description |
|---|---|---|
| `imported` | integer | Rules inserted into the profile. |
| `received` | integer | Rows parsed from the input. imported < received means rows were rejected - see errors. |
| `errors` | object[] | [{row (1-based), error}] - the rejected rows and why (bad bin, bad scope). |
| `profile` | object | {id, name} - the scrubbing profile the rules landed in. |
| `replaced` | integer | Existing `import` rules of the profile with the same BIN that this import replaced (idempotent like the legacy upsert keyed on bin). |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): csv not a string or too long, rules over 20000 entries or a row with a bad shape (bin not a string, scope not initial|rebill|both, enforced not a boolean), profile_id not a uuid. Also {"error":"No valid rules to import"} (nothing parsed), {"error":"No default scrubbing profile - create one under BIN Intelligence > Scrubbing first"} (no profile_id and no default scrubbing profile; the code message uses an em dash and a chevron), {"error":"Not a scrubbing profile"}.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"routing.write"} when the key's scopes lack routing.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin; {"error":"No account"} when the caller has no account.
- `404` {"error":"Not found"}: profile_id is not a profile of the caller's account.
- `413` The request body is larger than 1 MB (global body limit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers 201 even when every row was refused: check imported and errors.
- Idempotent per BIN: re-importing replaces the profile's "import" rules with the same BIN (counted in replaced) instead of duplicating them. Rules from other sources with the same BIN are kept.
- An imported rule fires only on the ATRIs that select this profile, and only while the account master switch (PUT /v1/bin-scrub-enabled) is on.
- Nothing is written to the legacy bin_scrub_rules table any more.

##### `GET /v1/scrub-bins`

**Scope** `customers.read` - **Read the BIN scrub list synced by the external rebill tool**

Reads the BIN scrub list the external rebill tool publishes (rules tagged rb_sync, enforced on POST /v1/charge); the subscription engine's own scrub BINs are another list (GET /v1/subscription/scrub-bins). Read back the currently stored RB-synced BIN scrub list so the publisher can verify that a PUT landed and detect drift. Returns only the rules tagged with source `rb_sync`.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Response**

```json
{
 "bins": [
  { "bin": "411111", "scope": "rebill" },
  { "bin": "486236", "scope": "both" },
  { "bin": "553912", "scope": "rebill" }
 ],
 "count": 3,
 "updatedAt": "2026-08-30T07:00:04.118Z"
}
```

| response field | type | description |
|---|---|---|
| `bins` | array of { bin: string, scope: string } | Every `rb_sync` rule, ordered by `bin` ascending. `scope` is one of `initial` \| `rebill` \| `both`. Only these two keys are returned per entry. |
| `count` | integer | `bins.length` - the number of synced rules stored. Directly comparable with the `stored` value returned by the last PUT. |
| `updatedAt` | string (ISO 8601) \| null | The MAXIMUM `updated_at` across the synced rows, serialized as an ISO 8601 UTC timestamp (e.g. `2026-08-30T07:00:04.118Z`). `null` when the list is empty. This is the DATABASE write time, not the `updatedAt` string you sent to PUT. |

**Errors**

- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `customers.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `500` `{ "error": "Internal Server Error", "requestId": "..." }` if the query fails.
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- The only parameter is clientId; there is no filtering or paging, the whole list is returned.
- IT ONLY SHOWS `rb_sync` RULES. BIN scrub rules added by hand or imported under a different source tag are enforced at charge time but are INVISIBLE here. A BIN missing from this response is not proof it isn't being blocked.
- The per-entry object is `{ bin, scope }` only. `enforced`, `reason`, `source`, `created_at` and `updated_at` exist on the rows but are dropped from the response - you cannot tell from here whether a rule is actually enforcing (all `rb_sync` rows are written enforced, so in practice they are).
- `updatedAt` is the max DB `updated_at`, so a no-op republish of an identical list still moves it forward (conflicting rows get `updated_at = now()`). Don't use it as a content hash; compare `count` plus the `bins` array to detect real drift.
- `updatedAt` is null - not an empty string and not omitted - when the list is empty.
- This reads the DATABASE directly, not the charge hot path's 60s in-memory cache. Right after a PUT this endpoint can report the new list while other cluster workers are still enforcing the old one.
- The response is not wrapped in a `data` envelope and there is no `error` key on success; it is the raw db-layer object.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- With an account key the list read or replaced is always the key owner's (clientId may be omitted; naming another account answers 403). Only the shared X-Refund-Key path uses clientId, and without it the platform owner's list.

##### `PUT /v1/scrub-bins`

**Scope** `customers.write` - **Replace the BIN scrub list synced by the external rebill tool**

Replaces the whole BIN scrub list the external rebill tool publishes (rules tagged rb_sync, enforced on POST /v1/charge); the subscription engine's scrub BINs (POST /v1/subscription/scrub-bins) are a separate list. Full-replace the RB-published BIN scrub blocklist that cocoapi enforces on /v1/charge. The RB app owns and edits this list; this endpoint publishes the whole current set in one call. Every published BIN is stored enforced (blocking immediately) and tagged with source `rb_sync`; manually-added rules from any other source are left untouched.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `bins` | array of { bin, scope } | **yes** | REQUIRED (no default - omitting it is a 400). The COMPLETE list to publish; maximum 20000 entries. An empty array `[]` is valid and DELETES the entire synced list. Anything already stored under source `rb_sync` and not present here is removed. |
| `bins[].bin` | string | **yes** | REQUIRED. Card BIN, exactly 6 ASCII digits (`^\d{6}$`). Send it as a STRING - a JSON number is rejected, and a leading-zero BIN like `012345` would lose its zero as a number anyway. |
| `bins[].scope` | string (enum); default `"rebill"` | no | Which charge flow this BIN blocks. Allowed values ONLY: `rebill` (block rebills), `initial` (block initial sales), `both`. Defaults to `rebill` when omitted from an entry - the RB list is a rebill scrub list by default. An out-of-enum value fails the WHOLE request with 400, not just that entry. |
| `updatedAt` | string | no | Optional free-form string. ACCEPTED BUT NEVER STORED OR USED: it is a plain `z.string()` (no datetime validation, so `"banana"` passes) and the handler only echoes it back verbatim in the response. It has no effect on the stored data, and the `updatedAt` returned by GET /v1/scrub-bins is derived from the database, not from this value. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "updatedAt": "2026-08-30T07:00:00.000Z",
 "bins": [
  { "bin": "411111", "scope": "rebill" },
  { "bin": "486236", "scope": "both" },
  { "bin": "553912" }
 ]
}
```

**Response**

```json
{
 "stored": 3,
 "received": 3,
 "updatedAt": "2026-08-30T07:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `stored` | integer | Number of BIN rules now held under source `rb_sync` (the count actually written by the replace). |
| `received` | integer | `bins.length` from the validated request body. |
| `updatedAt` | string \| null | Verbatim echo of the `updatedAt` you sent, or `null` if you omitted it. Purely a round-trip value - nothing is persisted from it. |

**Errors**

- `400` `{ "error": "Invalid request", "details": <zod flatten()> }` - `bins` missing or not an array, more than 20000 entries, any `bin` not exactly 6 digits (or sent as a number), or any `scope` outside rebill|initial|both. It is all-or-nothing: one bad entry rejects the entire publish and the stored list is left completely unchanged.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `customers.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `413` Request body exceeds the server's 1 MB body limit. A full 20000-BIN payload is roughly 800 KB of JSON - near the ceiling. Trim whitespace and omit `scope` where the `rebill` default applies.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `500` `{ "error": "Internal Server Error", "requestId": "..." }` - the replace runs in a single transaction, so a failure rolls back and the previous list survives intact.
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- THIS IS A FULL REPLACE, NOT AN UPSERT. Every row with source `rb_sync` is deleted first, then your list is inserted. Publishing a partial list silently un-blocks every BIN you left out. Always send the complete set.
- PUBLISHING `bins: []` WIPES THE WHOLE SYNCED BLOCKLIST. There is no confirmation flag and it returns a cheerful 200 `{"stored":0,"received":0}`.
- It TAKES OVER colliding manual rules: the insert has `on conflict (bin) do update set ... source = 'rb_sync'`, so if a BIN in your list already exists as a hand-added rule, that rule is converted to `rb_sync`, its `reason` is overwritten, and `enforced` is forced to true. The next publish that omits that BIN will then DELETE the formerly-manual rule. Manual rules are only safe while their BINs are absent from your list.
- `reason` is not settable here - every synced row is stored with the hardcoded reason `RB refund-audit rebill scrub`, regardless of scope. Use the admin BIN-scrub CRUD if you need per-rule reasons.
- Everything published is stored with `enforced = true`, so there is no staged/observe-only mode through this endpoint - BINs block as soon as the change propagates.
- PUBLISHING DOES NOT TURN SCRUBBING ON. Enforcement at charge time additionally requires the build-time gate (config.binScrubRules.enabled) AND the global runtime master switch operators flip in the dashboard. With either off, your list is stored but nothing is blocked.
- v3.9.1 - a scrubbing profile whose criteria say `rb_sync: false` is OUTSIDE this replication: it is created without your set and a publish never locks, clears or fills it (a scrub scoped to straight sales). The count you get back covers the profiles that take part.
- PROPAGATION IS NOT INSTANT ACROSS WORKERS. The charge hot path reads a per-process in-memory cache with a 60s TTL. The publish invalidates only the cache of the worker that handled the request; other cluster workers keep serving the old list for up to 60 seconds. Do not assert enforcement immediately after publishing.
- `stored` and `received` are ALWAYS equal - the db layer re-applies the same 6-digit/scope filter zod already enforced, so nothing can be dropped between them. A mismatch is not a partial-success signal to check for.
- Duplicate BINs within one payload are accepted by zod (no uniqueness check) and collapse via the `on conflict` clause, but `stored` still counts the raw array length, so a payload with duplicates reports a `stored` higher than the number of rows that actually exist. Send each BIN once.
- The method is PUT, not POST. POST /v1/scrub-bins is not registered and returns the generic 404 `{ "error": "Not Found" }`.
- Idempotent: publishing the same list twice leaves the same rows (though `updated_at` is refreshed on conflicting rows, which moves the timestamp GET reports).
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- With an account key the list read or replaced is always the key owner's (clientId may be omitted; naming another account answers 403). Only the shared X-Refund-Key path uses clientId, and without it the platform owner's list.

#### MID scrubbing

The MIDs that MID scrubbing disabled, and a scrubbing pass on demand.

- The export (grouped by ATRI) is built in the browser from `GET /v1/bin-scrub`. A scrubbed MID is switched back on with `PUT /v1/trips/:id/accounts` (member `enabled`).

##### `GET /v1/bin-scrub`

**Scope** `routing.read` - **List MIDs auto-disabled by MID scrubbing**

Lists the ATRI memberships (MIDs) that MID scrubbing auto-disabled: these rows are MIDs in ATRIs, not BINs (BIN rules live under /v1/bin-profiles). List every ATRI membership of the account currently flagged auto-disabled (a MID an automated guard pulled out of one of the account's ATRIs), with the reason and timestamp. Backs the MID Scrubbing page.

*No parameters.*

**Response**

```json
{
  "scrubbed": [
    {
      "trip_id": "9b1c4e2a-7f10-4d5b-8a33-2c9e1f6b04d7",
      "trip_name": "US Classic",
      "trip_type": "classic",
      "nmi_account_id": "7d40b2c9-5e18-42aa-b6f1-9c3d84e07a21",
      "account_name": "MID-19 Bluewater",
      "auto_disabled_reason": "BIN scrub: MID-rejection AR 12.4% over 68 winnable (24h manual, classic floor 20%)",
      "auto_disabled_at": "2026-08-25T21:14:02.551Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `scrubbed` | array<object> | Every auto-disabled membership of the account's ATRIs, ordered by auto_disabled_at descending (nulls last), then ATRI name, then MID name. Empty array when nothing is flagged. |
| `scrubbed[].trip_id` | string (uuid) | ATRI the MID was pulled from. Scrubbing is per (trip, MID) - the same MID can be fine in another ATRI and will not appear for it. |
| `scrubbed[].trip_name` | string | trips.name, joined in. The dashboard groups the list by this. |
| `scrubbed[].trip_type` | string | enum: classic\|cascade. Present because rows for cascade ATRIs DO appear here even though the BIN-scrub job itself only ever evaluates classic ATRIs. |
| `scrubbed[].nmi_account_id` | string (uuid) | The disabled MID (nmi_accounts.id). |
| `scrubbed[].account_name` | string | nmi_accounts.name for that MID. |
| `scrubbed[].auto_disabled_reason` | string \| null | Free-text human reason written by whichever guard fired. Three distinct producers, three different formats - see gotchas. Null for rows auto-disabled before migration 034 added the column. |
| `scrubbed[].auto_disabled_at` | string (ISO 8601 timestamptz) \| null | When the flag was set. Null for pre-migration-034 rows; those sort last. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Takes no parameter: no pagination, filter or window; every flagged row of the account is returned.
- THE NAME LIES: this is NOT 'MIDs rejected by BIN scrubbing'. The query filters ONLY on `ta.auto_disabled = true` and joins nothing about the cause. THREE independent guards set that flag: (1) runBinScrub - reason starts 'BIN scrub: MID-rejection AR ...'; (2) the deadMidSync job - reason starts 'Dead MID: 0 approvals over ...'; (3) the max-consecutive-declines guard on the charge path in db/repo.ts - reason 'Max consecutive MID-attributable declines (n>=threshold)'. Never assume the 'BIN scrub:' prefix; match on it if you need to distinguish causes.
- That is also why cascade ATRIs appear (trip_type='cascade') even though runBinScrub explicitly excludes cascade pools: those rows came from deadMidSync or the max-decline guard, which are not cascade-aware.
- The query does not check the membership `active` flag: a row proves auto_disabled is set, not that the MID is inactive now. Cross-check the membership via GET /v1/trips.
- NO NUMBERS ARE RETURNED. There is no ar, sample, winnable, approved or attempts field - the approval rate and sample size exist only embedded inside the `auto_disabled_reason` string. If you need them programmatically you must regex the free text (format: 'BIN scrub: MID-rejection AR <ar>% over <n> winnable (<label>, classic floor <t>%)'), and that string is not a stable API contract.
- Scoped to the ATRIs the account owns (by owner e-mail).
- auto_disabled_reason and auto_disabled_at are BOTH nullable and null together for rows disabled before migration 034. Null timestamps sort last (NULLS LAST) - do not assume the array is fully chronologically ordered.
- This is a point-in-time snapshot, not a log. When a membership is re-saved the flag resets to false (migration 021) and the row simply vanishes - there is no history here of past scrubs. Check the audit log for that.
- Both joins (trips, nmi_accounts) are INNER JOINs, so a flagged membership whose ATRI or MID row is gone silently drops out of the list.
- To put a scrubbed MID back into its ATRI, switch its membership on again with PUT /v1/trips/:id/accounts.

##### `POST /v1/bin-scrub/run`

**Scope** `routing.write` - **Run a MID scrubbing pass now**

Runs a MID scrubbing pass now: it disables ATRI memberships (MIDs), never BIN rules or BIN scrub lists. Manually trigger a BIN scrubbing pass over the account's classic ATRIs: every active (ATRI, MID) membership whose MID-rejection approval rate over the trailing window is below the account's BIN scrub AR threshold is DISABLED. A write, not a report: it sets the membership inactive and auto-disabled, and returns what it just disabled.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `windowHours` | integer, 1..720 (numeric strings coerced); default `24` | no | Trailing lookback in hours for the attempt sample; also written into the reason (`<windowHours>h manual`). |
| `minSample` | integer, 1..10000 (numeric strings coerced); default `15` | no | Minimum WINNABLE attempts an (ATRI, MID) pair needs in the window to be judged; smaller samples are skipped, never disabled. |

**Request body**

```json
{ "windowHours": 72, "minSample": 30 }
```

**Response**

```json
{
  "rejected": [
    {
      "trip_id": "6b1f0d9a-4c2e-4f77-9a10-2b83f0c5e441",
      "trip_name": "US Classic Main",
      "nmi_account_id": "c93a77e2-05bd-4a19-8e6d-71f4bb2c0aa8",
      "account_name": "MID-07 Acquirer EU",
      "ar": 12.5,
      "sample": 48,
      "reason": "BIN scrub: MID-rejection AR 12.5% over 48 winnable (72h manual, classic floor 20%)"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rejected` | array<object> | One entry per (ATRI, MID) membership this run just disabled. Empty array = nothing new crossed the floor in this window. It is NOT the full list of currently-scrubbed MIDs - use GET /v1/bin-scrub for that. |
| `rejected[].trip_id` | string (uuid) | The ATRI (routing pool, trips.id) the MID was rejected FROM. The same MID can stay active in other ATRIs; scrubbing is per (trip, MID), never global. |
| `rejected[].trip_name` | string | Human name of the ATRI (trips.name). |
| `rejected[].nmi_account_id` | string (uuid) | The MID / gateway account that was disabled (nmi_accounts.id). |
| `rejected[].account_name` | string | Human name of the MID (nmi_accounts.name). |
| `rejected[].ar` | number (PERCENT 0..100, one decimal) | MID-rejection approval rate that triggered the rejection = 100 * approved / winnable, rounded to 1 decimal. THIS IS A PERCENTAGE, NOT A 0..1 RATIO - 12.5 means 12.5%. Comes from SQL round(numeric,1); the code coerces it with Number() so you get a JSON number, not a string. |
| `rejected[].sample` | integer | The WINNABLE attempt count (the denominator of `ar`), i.e. approved + MID-attributable declines/errors. Unwinnable cardholder declines are excluded, so this is usually far smaller than the MID's total attempt count in the window. |
| `rejected[].reason` | string | The exact string stored as the membership's auto-disabled reason: `BIN scrub: MID-rejection AR <ar>% over <sample> winnable (<windowHours>h manual, classic floor <threshold>%)`. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: windowHours outside 1..720, minSample outside 1..10000, a non-integer or a non-numeric value. An empty body with Content-Type application/json is refused by the parser (send `{}`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `payments`) when the plan lacks the payments module.
- `423` `BIN scrubbing is OFF for this account` when the account's BIN scrub switch is off (account settings).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- NOT A DRY RUN: each qualifying membership is written at once (inactive, auto-disabled, reason, timestamp) and receives no new traffic. Re-enabling is manual, per membership.
- Scoped to the account: only its own classic ATRIs are evaluated.
- The AR threshold is the account's BIN scrub AR threshold (account settings), not a parameter; only windowHours and minSample are callable knobs.
- `ar` is a PERCENT 0..100 with one decimal (12.5 = 12.5%), not a 0..1 ratio.
- `sample` is the WINNABLE attempt count: approved plus MID-attributable declines, errors and timeouts, excluding unwinnable cardholder texts (fraud, insufficient funds, expired card, CVV, AVS, ...). A MID with many attempts can have a small sample and be skipped.
- Cascade is excluded: only classic-pass attempts on classic ATRIs are counted and judged.
- Already-inactive memberships are never selected: `rejected: []` means nothing NEW crossed the floor, not that everything is healthy. GET /v1/bin-scrub lists the current auto-disabled set.
- windowHours and minSample are read from the JSON body only; query parameters are ignored.
- Synchronous: one scan plus one update per rejection inside the request; a wide window on a busy account can take a while. A failure mid-loop can leave some memberships already disabled.
- Not recorded on the Jobs page; recorded in the account's action log.

### Commerce

The Commerce menu: stores, products, themes, checkouts, pages, flows, standalone and embedded checkouts, affiliates, domains, pixels, discounts, cart recovery and the messaging senders.

#### Stores

The stores (shops) of the account: create, configure, connect Shopify or Medusa, site content, payment routing and payment methods, the setup wizard.

##### `GET /v1/checkouts`

**Scope** `checkouts.read` - **List the stores of the account**

List every store of the account with its public store fields, owner, payment routing, a signed homepage preview link and a setup score. Use rows[].shop.id as shopId in the other store routes.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "shop": {
        "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
        "internal_name": "Example US",
        "shop_name": "Example Store",
        "domain": "shop.example.com",
        "admin_url": null,
        "cms": "product",
        "is_active": true,
        "payment_provider_id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
        "canary_payment_provider_id": null,
        "canary_percent": 0,
        "render_domain_id": "cdm-example0001",
        "dns_record_type": "CNAME",
        "dns_record_target": "storefront-example.onrender.com",
        "domain_verification_status": "verified",
        "domain_verified_at": "2026-09-10T08:12:44.000Z",
        "user_id": null,
        "updated_at": "2026-09-18T16:03:21.115Z",
        "created_at": "2026-06-02T09:41:03.220Z",
        "unified_tool_mode": "external",
        "recovery_sink_mode": "external",
        "sms_recovery_enabled": true,
        "email_recovery_enabled": false,
        "shopify_app_client_id": null,
        "theme_id": "market",
        "shopify_app_secret_set": false,
        "whop_tracking_enabled": false,
        "shopify_api_key_set": false
      },
      "owner": {
        "providerId": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
        "providerName": "Kontrol - Example Store",
        "owner": "ops@example.com",
        "keyName": "example-store",
        "keyId": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
        "defaultTripId": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
      },
      "routing": {
        "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
        "owner_email": "ops@example.com",
        "atri_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
        "crm": "nmi",
        "api_key_id": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
        "three_ds_integration_key": null,
        "apple_pay": true,
        "google_pay": false,
        "settings": {},
        "ab_test_id": null,
        "flow_id": null,
        "active": true,
        "served_by": "storefront",
        "checkout_id": "6d1e9b40-2c7a-4f3e-8b15-9a0c4e7d2f61",
        "checkout_name": "Example Store - 5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
        "updated_by": "jane@example.com",
        "created_at": "2026-09-16T10:00:00.000Z",
        "updated_at": "2026-09-18T15:59:02.410Z",
        "domain": "shop.example.com",
        "atri_name": "US Primary Pool",
        "api_key_name": "example-store",
        "api_key_prefix": "ck_live_ab12",
        "atri_default_mid": "NMI - Example US 01",
        "atri_default_mid_id": "0e5f7a21-6c3d-4b8e-a9f0-1d2c3b4a5e6f",
        "api_key_set": true
      },
      "preview": "https://storefront-internal.example.com/preview/home/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11?exp=1789830000&sig=9f2c0000example",
      "setup": {
        "done": 8,
        "total": 10,
        "missing": [
          "Homepage copy",
          "Pixels"
        ]
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].shop` | object | List columns of the store: id, internal_name, shop_name, domain, admin_url, cms, is_active, payment_provider_id, canary_payment_provider_id, canary_percent, render_domain_id, dns_record_type, dns_record_target, domain_verification_status, domain_verified_at, user_id, updated_at, created_at, unified_tool_mode, recovery_sink_mode, sms_recovery_enabled, email_recovery_enabled, shopify_app_client_id, theme_id, plus shopify_api_key_set, shopify_app_secret_set and whop_tracking_enabled. GET /v1/checkouts/:shopId returns every column. |
| `rows[].owner` | object | providerId and providerName (legacy payment provider, may be null), owner (account e-mail), keyName / keyId (the key that provider carries, null when none), defaultTripId (that key's default ATRI). |
| `rows[].routing` | object\|null | The store's resolved payment route (same fields as GET /v1/checkouts/:shopId/routing/details), null when the account has no route for the store. |
| `rows[].preview` | string\|null | Signed homepage preview URL, valid one hour; null when previews are not configured. |
| `rows[].setup` | object | done / total over the scored checklist items, and missing = labels of the items not done. Same rules as the checklist of GET /v1/checkouts/:shopId/overview, computed from the list data only: the Homepage blocks and Products listed items are not part of it. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- Sorted by internal_name ascending. No pagination and no filter.
- routing is the account's own route row; a store whose route is stamped with another account shows routing: null.
- No storefront content in this list: read GET /v1/checkouts/:shopId/storefront.
- The shop view carries shopify_api_key_set instead of the Shopify Admin API access token. The token and the app secret are only readable through GET /v1/checkouts/:shopId/secrets, which refuses every API key.
- A store belongs to the account of its payment route (checkout routing owner) or, for older stores, to the account whose key its legacy payment provider carries. Another account's store answers 404, never 403.
- Preview links are signed for one hour and are null when the storefront preview host or its signing secret is not configured. Fetch them again instead of storing them.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `POST /v1/checkouts`

**Scope** `checkouts.write` - **Create a store**

Create a store of the account (cms product for an in-house storefront, shopify or medusa for an external platform). The server records the account's payment route for the store (served by Kontrol's storefront, inactive until its payment setup is saved), registers the domain on the hosting provider unless register_domain is false, and starts uptime monitoring of the domain. Returns 201 with the new store view; keep shop.id for the following calls.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `internal_name` | string | **yes** | Trimmed, 1 to 120 characters. Internal label shown in the dashboard, never to customers. |
| `shop_name` | string | **yes** | Trimmed, 1 to 120 characters. Customer-facing store name (checkout header, e-mails). |
| `domain` | string (hostname) | **yes** | Trimmed and lower-cased, 3 to 253 characters, a bare hostname with at least one dot (letters, digits, hyphens; no scheme, port, path or space), otherwise 400 'hostname expected'. Must be unique across all stores (409). Registered on the hosting provider after the insert unless register_domain is false. |
| `admin_url` | string\|null | no | Trimmed and lower-cased, 3 to 253 characters, or null. The platform admin host the checkout resolves the store by: the myshopify host of a Shopify store, the backend host of a Medusa store (normally set through the Medusa connection). Unique across all stores (409). In-house stores leave it null. |
| `cms` | enum: product\|shopify\|medusa; default `product` | no | Commerce platform. product = in-house catalogue and pages served by Kontrol; shopify = Shopify keeps its pages and Kontrol serves the checkout; medusa = Medusa store (403 'Medusa integration is not enabled for this account' when the integration is off). |
| `is_active` | boolean | no | Inactive stores refuse new checkouts. The value is also written to Kontrol's own copy of the store row, which payment admission reads. |
| `shopify_api_key` | string\|null | no | Trimmed, max 255. Shopify Admin API access token (shpat_...). null clears it. Never returned by reads (shopify_api_key_set instead). |
| `shopify_app_client_id` | string\|null | no | Trimmed, max 255. Client ID of the Shopify app used for the OAuth connection. null clears it. |
| `shopify_app_secret` | string\|null | no | Max 512, plain text in; stored encrypted. Omitted, null or empty = no secret stored. Reads only expose shopify_app_secret_set. |
| `support_email` | string (email)\|null | no | Trimmed, valid e-mail, max 255. Support address shown to buyers. |
| `support_phone` | string\|null | no | Trimmed, max 64. |
| `logo_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. |
| `logo_height_override` | integer\|null | no | Logo height in pixels, 8 to 400. null = theme default. |
| `favicon_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. |
| `primary_color` | string; default `#0f172a` | no | Hex colour #rrggbb (exactly 6 hex digits). Defaults to #0f172a. |
| `language_mode` | enum: auto\|forced | no | auto follows the buyer's browser language; forced uses forced_locale. Saving auto also sets forced_locale to null. |
| `forced_locale` | enum: en\|fr\|it\|es\|pt\|pl\|null | no | Locale used when language_mode is forced (en, fr, it, es, pt, pl). |
| `shipping_protection_mode` | enum: off\|on\|forced | no | on = optional shipping-protection line the buyer can tick, forced = always added, off = never shown. |
| `shipping_protection_price_cents` | integer | no | Integer cents, >= 0. Price of the shipping-protection line. |
| `shipping_protection_label` | string\|null | no | Trimmed, max 120. |
| `shipping_protection_description` | string\|null | no | Trimmed, max 500. |
| `allowed_countries` | string[] | no | ISO 3166-1 alpha-2 codes, each trimmed and upper-cased, exactly 2 characters. An empty list means no country restriction. |
| `affiliate_id` | string\|null | no | Trimmed, max 120. Default affiliate ID stamped on the store's orders. |
| `countdown_enabled` | boolean | no | Checkout block toggle: countdown timer. |
| `trustpilot_header_enabled` | boolean | no | Checkout block toggle: Trustpilot header. |
| `sales_points_header_enabled` | boolean | no | Checkout block toggle: sales points header. |
| `cta_subtext_enabled` | boolean | no | Checkout block toggle: text under the pay button. |
| `reassurance_secure_enabled` | boolean | no | Checkout block toggle: secure-payment reassurance. |
| `reassurance_refund_enabled` | boolean | no | Checkout block toggle: refund reassurance. |
| `reassurance_tracking_enabled` | boolean | no | Checkout block toggle: order-tracking reassurance. |
| `support_help_enabled` | boolean | no | Checkout block toggle: help link. |
| `support_chat_enabled` | boolean | no | Checkout block toggle: chat link. |
| `language_selector_enabled` | boolean | no | Checkout block toggle: language selector. |
| `cta_custom_image_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. Custom image shown with the pay button. |
| `cta_custom_image_width` | enum: full\|cta | no | Width of the custom pay-button image: full width or the button's width. |
| `checkout_tags` | object[] | no | At most 20 tags shown on the checkout. |
| `checkout_tags[].label` | string | no | Trimmed, 1 to 120 characters. |
| `sms_recovery_enabled` | boolean | no | Abandoned-cart SMS recovery on or off. |
| `sms_recovery_delay_minutes` | integer | no | 5 to 180. Minutes after abandonment before the first SMS. |
| `sms_recovery_discount_kind` | enum: percent\|amount | no | Unit of sms_recovery_discount_value (amount = integer cents). |
| `sms_recovery_discount_value` | integer | no | >= 0. Discount offered in the recovery message. |
| `sms_recovery_link_valid_minutes` | integer | no | 5 to 1440. Lifetime of the recovery link. |
| `sms_recovery_min_cart_cents` | integer | no | >= 0. Carts below this amount get no SMS. |
| `sms_recovery_test_mode_pct` | integer | no | 0 to 100. Share of eligible carts that actually receive the SMS (the rest is a holdout). |
| `sms_recovery_quiet_hours_enabled` | boolean | no | Suppress SMS sends at night in sms_recovery_tz. |
| `sms_recovery_tz` | string | no | Trimmed, 1 to 64 characters, IANA time zone (for example America/New_York). |
| `email_recovery_enabled` | boolean | no | Abandoned-cart e-mail recovery on or off. |
| `email_recovery_delay_minutes` | integer | no | 5 to 180. Minutes after abandonment before the first e-mail. |
| `email_recovery_discount_kind` | enum: percent\|amount | no | Unit of email_recovery_discount_value (amount = integer cents). |
| `email_recovery_discount_value` | integer | no | >= 0. Discount offered in the recovery message. |
| `email_recovery_link_valid_minutes` | integer | no | 5 to 1440. Lifetime of the recovery link. |
| `email_recovery_min_cart_cents` | integer | no | >= 0. Carts below this amount get no e-mail. |
| `email_recovery_test_mode_pct` | integer | no | 0 to 100. Share of eligible carts that actually receive the e-mail (the rest is a holdout). |
| `email_recovery_quiet_hours_enabled` | boolean | no | Suppress e-mail sends at night in email_recovery_tz. |
| `email_recovery_tz` | string | no | Trimmed, 1 to 64 characters, IANA time zone (for example America/New_York). |
| `email_recovery_touch_delays_minutes` | string | no | Trimmed, max 120. Comma-separated minute offsets of the follow-up e-mails (for example 60,1440). |
| `unified_tool_mode` | enum: local\|shadow\|external; default `external` | no | Who fires the pixel and conversion-API pipeline: local = the legacy checkout, shadow = both run and are compared, external = Kontrol's unified tool. Defaults to external. |
| `recovery_sink_mode` | enum: local\|shadow\|external; default `external` | no | Same three modes for the abandoned-cart recovery sink. Defaults to external. |
| `whop_tracking_enabled` | boolean | no | Not a column: written to storefront.whopTracking.enabled; the rest of the storefront content is untouched. Defaults to false. |
| `theme_id` | enum | no | Built-in product-page theme, one of: legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery. Only in-house (cms product) stores render a theme. An account-owned custom theme slug is applied through PUT /v1/checkouts/:shopId/theme, not here. |
| `theme_settings` | object | no | Overrides of the compiled theme: tokens, fonts and per-section enabled/settings keyed by section instance ID. Validated against the theme being saved (theme_id, else legacy); a refused value answers 400 'theme settings refused: ...' with details.errors listing every refused value. |
| `payment_provider_id` | uuid\|null | no | Legacy checkout payment provider of the caller's account (see GET /v1/checkouts/providers). Omitted: the account's single provider is used when exactly one resolves, else none. A provider of another account, or one that resolves to no account, answers 403 'Provider belongs to another account'. A store without a provider is still created and owned through its payment route. |
| `register_domain` | boolean; default `true` | no | false skips the domain registration on the hosting provider (useful for an inactive draft store built before DNS exists). Not stored on the store. |

**Request body**

```json
{
  "internal_name": "Agent sandbox",
  "shop_name": "Agent Sandbox",
  "domain": "agent-sandbox.example.com",
  "cms": "product",
  "is_active": false,
  "register_domain": false
}
```

**Response** `201`

```json
{
  "shop": {
    "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "internal_name": "Agent sandbox",
    "shop_name": "Agent Sandbox",
    "domain": "agent-sandbox.example.com",
    "admin_url": null,
    "cms": "product",
    "is_active": false,
    "payment_provider_id": null,
    "canary_payment_provider_id": null,
    "canary_percent": 0,
    "render_domain_id": null,
    "dns_record_type": null,
    "dns_record_target": null,
    "domain_verification_status": null,
    "domain_verified_at": null,
    "user_id": null,
    "updated_at": "2026-11-24T09:00:00.000Z",
    "created_at": "2026-11-24T09:00:00.000Z",
    "unified_tool_mode": "external",
    "recovery_sink_mode": "external",
    "sms_recovery_enabled": false,
    "email_recovery_enabled": false,
    "shopify_app_client_id": null,
    "theme_id": "legacy",
    "shopify_app_secret_set": false,
    "whop_tracking_enabled": false,
    "shopify_api_key_set": false,
    "support_email": null,
    "support_phone": null,
    "logo_url": null,
    "logo_height_override": null,
    "favicon_url": null,
    "primary_color": "#0f172a",
    "language_mode": "auto",
    "forced_locale": null,
    "shipping_protection_mode": "on",
    "shipping_protection_price_cents": 299,
    "shipping_protection_label": null,
    "shipping_protection_description": null,
    "allowed_countries": [
      "US",
      "CA"
    ],
    "affiliate_id": null,
    "checkout_tags": [],
    "theme_settings": {}
  },
  "owner": {
    "providerId": null,
    "providerName": null,
    "owner": "ops@example.com",
    "keyName": null,
    "keyId": null,
    "defaultTripId": null
  },
  "storefrontLite": {}
}
```

| response field | type | description |
|---|---|---|
| `shop` | object | Every column of the new store except the encrypted app secret, the Shopify access token and the storefront content, plus shopify_api_key_set, shopify_app_secret_set and whop_tracking_enabled. domain_verification_status, dns_record_type and dns_record_target describe the domain registration. |
| `owner` | object | Owner of the store: the legacy provider and its key when one is attached, else owner = the account recorded on the payment route. |
| `storefrontLite` | object | Light storefront facts (brandKit, homeIntro, homeStory, homeFaq, homeTestimonials, theme); empty on a new store. |
| `domainWarning` | string (optional) | Present when the store was saved but the domain registration was not confirmed. Absent when registration succeeded or register_domain was false. |

**Errors**

- `400` {"error":"invalid payload","details":<flattened validation errors>}: missing internal_name, shop_name or domain, 'hostname expected', bad enum, colour not #rrggbb, out-of-range integer, invalid e-mail or URL; 'theme settings refused: ...' with details.errors.
- `402` The account has reached its store allowance. (plan store quota); A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Medusa integration is not enabled for this account (cms medusa); An account is required to add a Medusa store; Provider belongs to another account (payment_provider_id of another account or of no account); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `409` domain already used by another checkout; admin_url already used by another checkout.
- `413` Request body larger than 1 MB.
- `500` Create failed (the insert returned no row), or Internal Server Error with a requestId.

**Gotchas**

- 201, not 200, on success.
- A create can succeed with domainWarning: do not retry by creating the store again. Check the domain from GET /v1/checkouts/:shopId and POST /v1/checkouts/:shopId/domain/check.
- register_domain defaults to true. Set it to false (with is_active false) to assemble and preview a store before its DNS exists; it is not stored.
- Server defaults: cms product, primary_color #0f172a, unified_tool_mode and recovery_sink_mode external, storefront content { whopTracking: { enabled } }. Other columns keep their database defaults.
- The payment route created here is inactive and carries no ATRI and no key: save PUT /v1/checkouts/:shopId/routing (or assign a checkout with POST /v1/checkouts/:shopId/checkout) before taking payments.
- Unknown body keys are ignored, not refused.
- To archive a test store use DELETE /v1/checkouts/:shopId.
- The ten built-in theme IDs are legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery. A plain slug such as circuit is an account-owned custom theme, never an alias of builtin:circuit.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).
- The shop view carries shopify_api_key_set instead of the Shopify Admin API access token. The token and the app secret are only readable through GET /v1/checkouts/:shopId/secrets, which refuses every API key.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `GET /v1/checkouts/:shopId`

**Scope** `checkouts.read` - **Read one store**

Returns one store with every column, its owner, light storefront facts, its resolved payment route, all its pixels (server tokens masked), a signed homepage preview link and its setup-wizard progress. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Response**

```json
{
  "shop": {
    "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "internal_name": "Example US",
    "shop_name": "Example Store",
    "domain": "shop.example.com",
    "admin_url": null,
    "cms": "product",
    "is_active": true,
    "payment_provider_id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
    "canary_payment_provider_id": null,
    "canary_percent": 0,
    "render_domain_id": "cdm-example0001",
    "dns_record_type": "CNAME",
    "dns_record_target": "storefront-example.onrender.com",
    "domain_verification_status": "verified",
    "domain_verified_at": "2026-09-10T08:12:44.000Z",
    "user_id": null,
    "updated_at": "2026-09-18T16:03:21.115Z",
    "created_at": "2026-06-02T09:41:03.220Z",
    "unified_tool_mode": "external",
    "recovery_sink_mode": "external",
    "sms_recovery_enabled": true,
    "email_recovery_enabled": false,
    "shopify_app_client_id": null,
    "theme_id": "market",
    "shopify_app_secret_set": false,
    "whop_tracking_enabled": false,
    "shopify_api_key_set": false,
    "support_email": "support@example.com",
    "support_phone": null,
    "logo_url": null,
    "logo_height_override": null,
    "favicon_url": null,
    "primary_color": "#0f172a",
    "language_mode": "auto",
    "forced_locale": null,
    "shipping_protection_mode": "on",
    "shipping_protection_price_cents": 299,
    "shipping_protection_label": null,
    "shipping_protection_description": null,
    "allowed_countries": [
      "US",
      "CA"
    ],
    "affiliate_id": null,
    "checkout_tags": [],
    "theme_settings": {}
  },
  "owner": {
    "providerId": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
    "providerName": "Kontrol - Example Store",
    "owner": "ops@example.com",
    "keyName": "example-store",
    "keyId": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
    "defaultTripId": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
  },
  "storefrontLite": {
    "brandKit": "editorial",
    "homeIntro": "Designed for long days at the desk.",
    "homeStory": "We started in 2021.",
    "homeFaq": [
      {
        "q": "How fast is shipping?",
        "a": "3-5 business days."
      }
    ],
    "homeTestimonials": []
  },
  "routing": {
    "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "owner_email": "ops@example.com",
    "atri_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "crm": "nmi",
    "api_key_id": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
    "three_ds_integration_key": null,
    "apple_pay": true,
    "google_pay": false,
    "settings": {},
    "ab_test_id": null,
    "flow_id": null,
    "active": true,
    "served_by": "storefront",
    "checkout_id": "6d1e9b40-2c7a-4f3e-8b15-9a0c4e7d2f61",
    "checkout_name": "Example Store - 5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "updated_by": "jane@example.com",
    "created_at": "2026-09-16T10:00:00.000Z",
    "updated_at": "2026-09-18T15:59:02.410Z",
    "domain": "shop.example.com",
    "atri_name": "US Primary Pool",
    "api_key_name": "example-store",
    "api_key_prefix": "ck_live_ab12",
    "atri_default_mid": "NMI - Example US 01",
    "atri_default_mid_id": "0e5f7a21-6c3d-4b8e-a9f0-1d2c3b4a5e6f",
    "api_key_set": true
  },
  "pixels": [
    {
      "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Meta main",
      "supplier": "facebook",
      "pixel_front": "1234567890123",
      "pixel_back": "EAABsb...Zx2Q",
      "product_id": null,
      "created_at": "2026-07-01T10:00:00.000Z",
      "updated_at": "2026-07-01T10:00:00.000Z",
      "product_title": null
    }
  ],
  "preview": "https://storefront-internal.example.com/preview/home/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11?exp=1789830000&sig=9f2c0000example",
  "setup": {
    "done": 4,
    "total": 5,
    "steps": [
      {
        "n": 1,
        "key": "store",
        "label": "Store",
        "done": true
      },
      {
        "n": 2,
        "key": "domain",
        "label": "Domain",
        "done": true
      },
      {
        "n": 5,
        "key": "catalog",
        "label": "Catalogue",
        "done": true
      },
      {
        "n": 7,
        "key": "pixels",
        "label": "Tracking",
        "done": true
      },
      {
        "n": 8,
        "key": "payment",
        "label": "Payment & test",
        "done": false
      }
    ],
    "next": 8,
    "blocking": []
  }
}
```

| response field | type | description |
|---|---|---|
| `shop` | object | Every column of the store except the encrypted app secret, the Shopify access token and the storefront content, plus shopify_api_key_set, shopify_app_secret_set and whop_tracking_enabled. |
| `owner` | object | providerId, providerName, owner (account e-mail), keyName, keyId, defaultTripId (see GET /v1/checkouts). |
| `storefrontLite` | object\|null | brandKit, homeIntro, homeStory (strings) and homeFaq, homeTestimonials (arrays) read from the storefront content. |
| `routing` | object\|null | The resolved payment route, any owner: shop_id, owner_email, atri_id, crm, api_key_id, three_ds_integration_key, apple_pay, google_pay, settings, ab_test_id, flow_id, active, served_by (checkout or storefront), checkout_id, checkout_name, updated_by, created_at, updated_at, domain, atri_name, api_key_name, api_key_prefix, atri_default_mid, atri_default_mid_id and api_key_set. The key material itself is never returned. null when the store has no route. |
| `pixels[]` | object[] | Same rows as GET /v1/checkouts/:shopId/pixels: pixel_back masked to its first 6 and last 4 characters, product_title set for product-level pixels. |
| `preview` | string\|null | Signed homepage preview URL valid one hour; null when previews are not configured. |
| `setup` | object\|null | Setup wizard progress: done, total, steps[] ({ n, key, label, done } for the steps this store has: store, domain, app, connect, catalog, theme, pixels, payment; app, connect and theme only for Shopify and Medusa stores), next (first unfinished step number or null) and blocking (labels that block going live). null when it could not be computed. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- Pass a UUID: a malformed shopId can answer 500 instead of 404.
- pixel_back (the server-side conversion token) is masked here and in every list; GET /v1/checkouts/:shopId/pixels/:id/secrets reveals it but refuses every API key.
- The shop view carries shopify_api_key_set instead of the Shopify Admin API access token. The token and the app secret are only readable through GET /v1/checkouts/:shopId/secrets, which refuses every API key.
- A store belongs to the account of its payment route (checkout routing owner) or, for older stores, to the account whose key its legacy payment provider carries. Another account's store answers 404, never 403.
- Preview links are signed for one hour and are null when the storefront preview host or its signing secret is not configured. Fetch them again instead of storing them.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `PUT /v1/checkouts/:shopId`

**Scope** `checkouts.write` - **Update a store**

Partially update a store: only the fields present in the body are written. A changed domain is reserved, saved, re-registered on the hosting provider and moved onto the store's payment route. Returns the saved store view with the cache refresh outcome and the domain outcome.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `internal_name` | string | no | Trimmed, 1 to 120 characters. Internal label shown in the dashboard, never to customers. Omit to keep. |
| `shop_name` | string | no | Trimmed, 1 to 120 characters. Customer-facing store name (checkout header, e-mails). Omit to keep. |
| `domain` | string (hostname) | no | Trimmed and lower-cased, 3 to 253 characters, a bare hostname with at least one dot (letters, digits, hyphens; no scheme, port, path or space), otherwise 400 'hostname expected'. Must be unique across all stores (409). A changed value re-registers the custom domain on the hosting provider and moves the payment route's host to it. |
| `admin_url` | string\|null | no | Trimmed and lower-cased, 3 to 253 characters, or null. The platform admin host the checkout resolves the store by: the myshopify host of a Shopify store, the backend host of a Medusa store (normally set through the Medusa connection). Unique across all stores (409). In-house stores leave it null. Omit to keep. |
| `cms` | enum: product\|shopify\|medusa | no | Commerce platform. Switching to or from medusa is refused (400 'Add a separate store to change its commerce platform to or from Medusa'). Omit to keep. |
| `is_active` | boolean | no | Inactive stores refuse new checkouts. The value is also written to Kontrol's own copy of the store row, which payment admission reads. Omit to keep. |
| `shopify_api_key` | string\|null | no | Trimmed, max 255. Shopify Admin API access token (shpat_...). null clears it. Never returned by reads (shopify_api_key_set instead). Omit to keep. |
| `shopify_app_client_id` | string\|null | no | Trimmed, max 255. Client ID of the Shopify app used for the OAuth connection. null clears it. Omit to keep. |
| `shopify_app_secret` | string\|null | no | Max 512, plain text in; stored encrypted. Omitted = keep the stored secret, null or empty string = clear it, a value = replace it. Reads only expose shopify_app_secret_set. |
| `support_email` | string (email)\|null | no | Trimmed, valid e-mail, max 255. Support address shown to buyers. Omit to keep. |
| `support_phone` | string\|null | no | Trimmed, max 64. Omit to keep. |
| `logo_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. Omit to keep. |
| `logo_height_override` | integer\|null | no | Logo height in pixels, 8 to 400. null = theme default. Omit to keep. |
| `favicon_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. Omit to keep. |
| `primary_color` | string | no | Hex colour #rrggbb (exactly 6 hex digits). Omit to keep. |
| `language_mode` | enum: auto\|forced | no | auto follows the buyer's browser language; forced uses forced_locale. Saving auto also sets forced_locale to null. Omit to keep. |
| `forced_locale` | enum: en\|fr\|it\|es\|pt\|pl\|null | no | Locale used when language_mode is forced (en, fr, it, es, pt, pl). Omit to keep. |
| `shipping_protection_mode` | enum: off\|on\|forced | no | on = optional shipping-protection line the buyer can tick, forced = always added, off = never shown. Omit to keep. |
| `shipping_protection_price_cents` | integer | no | Integer cents, >= 0. Price of the shipping-protection line. Omit to keep. |
| `shipping_protection_label` | string\|null | no | Trimmed, max 120. Omit to keep. |
| `shipping_protection_description` | string\|null | no | Trimmed, max 500. Omit to keep. |
| `allowed_countries` | string[] | no | ISO 3166-1 alpha-2 codes, each trimmed and upper-cased, exactly 2 characters. An empty list means no country restriction. Omit to keep. |
| `affiliate_id` | string\|null | no | Trimmed, max 120. Default affiliate ID stamped on the store's orders. Omit to keep. |
| `countdown_enabled` | boolean | no | Checkout block toggle: countdown timer. Omit to keep. |
| `trustpilot_header_enabled` | boolean | no | Checkout block toggle: Trustpilot header. Omit to keep. |
| `sales_points_header_enabled` | boolean | no | Checkout block toggle: sales points header. Omit to keep. |
| `cta_subtext_enabled` | boolean | no | Checkout block toggle: text under the pay button. Omit to keep. |
| `reassurance_secure_enabled` | boolean | no | Checkout block toggle: secure-payment reassurance. Omit to keep. |
| `reassurance_refund_enabled` | boolean | no | Checkout block toggle: refund reassurance. Omit to keep. |
| `reassurance_tracking_enabled` | boolean | no | Checkout block toggle: order-tracking reassurance. Omit to keep. |
| `support_help_enabled` | boolean | no | Checkout block toggle: help link. Omit to keep. |
| `support_chat_enabled` | boolean | no | Checkout block toggle: chat link. Omit to keep. |
| `language_selector_enabled` | boolean | no | Checkout block toggle: language selector. Omit to keep. |
| `cta_custom_image_url` | string (url)\|null | no | Trimmed absolute URL, max 2048. Custom image shown with the pay button. Omit to keep. |
| `cta_custom_image_width` | enum: full\|cta | no | Width of the custom pay-button image: full width or the button's width. Omit to keep. |
| `checkout_tags` | object[] | no | At most 20 tags shown on the checkout. Replaces the whole list. |
| `checkout_tags[].label` | string | no | Trimmed, 1 to 120 characters. |
| `sms_recovery_enabled` | boolean | no | Abandoned-cart SMS recovery on or off. Omit to keep. |
| `sms_recovery_delay_minutes` | integer | no | 5 to 180. Minutes after abandonment before the first SMS. Omit to keep. |
| `sms_recovery_discount_kind` | enum: percent\|amount | no | Unit of sms_recovery_discount_value (amount = integer cents). Omit to keep. |
| `sms_recovery_discount_value` | integer | no | >= 0. Discount offered in the recovery message. Omit to keep. |
| `sms_recovery_link_valid_minutes` | integer | no | 5 to 1440. Lifetime of the recovery link. Omit to keep. |
| `sms_recovery_min_cart_cents` | integer | no | >= 0. Carts below this amount get no SMS. Omit to keep. |
| `sms_recovery_test_mode_pct` | integer | no | 0 to 100. Share of eligible carts that actually receive the SMS (the rest is a holdout). Omit to keep. |
| `sms_recovery_quiet_hours_enabled` | boolean | no | Suppress SMS sends at night in sms_recovery_tz. Omit to keep. |
| `sms_recovery_tz` | string | no | Trimmed, 1 to 64 characters, IANA time zone (for example America/New_York). Omit to keep. |
| `email_recovery_enabled` | boolean | no | Abandoned-cart e-mail recovery on or off. Omit to keep. |
| `email_recovery_delay_minutes` | integer | no | 5 to 180. Minutes after abandonment before the first e-mail. Omit to keep. |
| `email_recovery_discount_kind` | enum: percent\|amount | no | Unit of email_recovery_discount_value (amount = integer cents). Omit to keep. |
| `email_recovery_discount_value` | integer | no | >= 0. Discount offered in the recovery message. Omit to keep. |
| `email_recovery_link_valid_minutes` | integer | no | 5 to 1440. Lifetime of the recovery link. Omit to keep. |
| `email_recovery_min_cart_cents` | integer | no | >= 0. Carts below this amount get no e-mail. Omit to keep. |
| `email_recovery_test_mode_pct` | integer | no | 0 to 100. Share of eligible carts that actually receive the e-mail (the rest is a holdout). Omit to keep. |
| `email_recovery_quiet_hours_enabled` | boolean | no | Suppress e-mail sends at night in email_recovery_tz. Omit to keep. |
| `email_recovery_tz` | string | no | Trimmed, 1 to 64 characters, IANA time zone (for example America/New_York). Omit to keep. |
| `email_recovery_touch_delays_minutes` | string | no | Trimmed, max 120. Comma-separated minute offsets of the follow-up e-mails (for example 60,1440). Omit to keep. |
| `unified_tool_mode` | enum: local\|shadow\|external | no | Who fires the pixel and conversion-API pipeline: local = the legacy checkout, shadow = both run and are compared, external = Kontrol's unified tool. Omit to keep. |
| `recovery_sink_mode` | enum: local\|shadow\|external | no | Same three modes for the abandoned-cart recovery sink. Omit to keep. |
| `whop_tracking_enabled` | boolean | no | Not a column: written to storefront.whopTracking.enabled; the rest of the storefront content is untouched. Omit to keep. |
| `theme_id` | enum | no | Built-in product-page theme, one of: legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery. Only in-house (cms product) stores render a theme; on a Shopify or Medusa store a theme change is refused (400). An account-owned custom theme slug is applied through PUT /v1/checkouts/:shopId/theme, not here. Choosing a visual builtin: theme on a store currently on market or on a custom theme keeps the store's composition in a private copy of the theme, and the response's theme_id is then that copy's slug. |
| `theme_settings` | object | no | Overrides of the compiled theme: tokens, fonts and per-section enabled/settings keyed by section instance ID. Validated against the theme being saved (theme_id of this body, else the stored theme); a refused value answers 400 'theme settings refused: ...' with details.errors listing every refused value. Replaces the stored overrides. |
| `theme_settings.tokens` | object<string, string> | no | Token overrides by token name (for example accent): only the tokens of the theme being saved (listed with their defaults by GET /v1/checkouts/themes) are accepted. |
| `theme_settings.fonts.body` | string | no | Body font family; one of the fonts GET /v1/checkouts/themes lists. |
| `theme_settings.fonts.heading` | string | no | Heading font family; one of the fonts GET /v1/checkouts/themes lists. |
| `theme_settings.sections.<sectionId>.enabled` | boolean | no | Switches one section instance of the product page on or off (section ids per theme in GET /v1/checkouts/themes). |
| `theme_settings.sections.<sectionId>.settings` | object | no | Settings of that section instance, validated against the section's settings in the theme manifest. |

**Request body**

```json
{
  "shop_name": "Example Store",
  "is_active": true,
  "language_mode": "forced",
  "forced_locale": "fr",
  "sms_recovery_enabled": true,
  "sms_recovery_delay_minutes": 30,
  "shopify_app_secret": null
}
```

**Response**

```json
{
  "view": {
    "shop": {
      "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "internal_name": "Example US",
      "shop_name": "Example Store",
      "domain": "shop.example.com",
      "admin_url": null,
      "cms": "product",
      "is_active": true,
      "payment_provider_id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
      "canary_payment_provider_id": null,
      "canary_percent": 0,
      "render_domain_id": "cdm-example0001",
      "dns_record_type": "CNAME",
      "dns_record_target": "storefront-example.onrender.com",
      "domain_verification_status": "verified",
      "domain_verified_at": "2026-09-10T08:12:44.000Z",
      "user_id": null,
      "updated_at": "2026-09-18T16:03:21.115Z",
      "created_at": "2026-06-02T09:41:03.220Z",
      "unified_tool_mode": "external",
      "recovery_sink_mode": "external",
      "sms_recovery_enabled": true,
      "email_recovery_enabled": false,
      "shopify_app_client_id": null,
      "theme_id": "market",
      "shopify_app_secret_set": false,
      "whop_tracking_enabled": false,
      "shopify_api_key_set": false,
      "support_email": "support@example.com",
      "support_phone": null,
      "logo_url": null,
      "logo_height_override": null,
      "favicon_url": null,
      "primary_color": "#0f172a",
      "language_mode": "forced",
      "forced_locale": "fr",
      "shipping_protection_mode": "on",
      "shipping_protection_price_cents": 299,
      "shipping_protection_label": null,
      "shipping_protection_description": null,
      "allowed_countries": [
        "US",
        "CA"
      ],
      "affiliate_id": null,
      "checkout_tags": [],
      "theme_settings": {}
    },
    "owner": {
      "providerId": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
      "providerName": "Kontrol - Example Store",
      "owner": "ops@example.com",
      "keyName": "example-store",
      "keyId": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
      "defaultTripId": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
    },
    "storefrontLite": {}
  },
  "cache": {
    "ok": true,
    "status": 200
  },
  "domain": null
}
```

| response field | type | description |
|---|---|---|
| `view.shop` | object | Every column of the saved store except the encrypted app secret, the Shopify access token and the storefront content, plus shopify_api_key_set, shopify_app_secret_set and whop_tracking_enabled. |
| `view.owner` | object | Owner info (unchanged by this call). |
| `view.storefrontLite` | object\|null | Light storefront facts. |
| `cache` | object | Storefront cache refresh outcome: { ok: true, status } or { ok: false, error, status } ({ ok: false, error: 'not_configured', status: null } when no front is configured). |
| `domain` | object\|null | null when the domain did not change; otherwise { ok: true, dns: { type, target }, status: verified\|pending } or { ok: false, error, retryAfterMs }. |

**Errors**

- `400` {"error":"invalid payload","details":<flattened validation errors>}; Add a separate store to change its commerce platform to or from Medusa; This store is served by Shopify|Medusa: it has no product page here, so it has no theme; theme settings refused: ... (details.errors lists every refused value); This store needs an account before its theme can be copied.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `409` domain already used by another checkout; admin_url already used by another checkout (only checked when the value changes); The store domain changed. Reload it before saving.; Domain work already exists; open its saved progress before changing this host; A domain operation or unresolved remote write already holds this host; Domain reservation was lost; no further changes are allowed; The store changed while its theme was being prepared. Reload it and retry.; This store was saved from somewhere else while this change was being written. Nothing was changed - open it again and retry.
- `413` Request body larger than 1 MB.
- `500` Write failed (the update returned no row), or Internal Server Error with a requestId.
- `503` Domain jobs migration is unavailable (domain change only).

**Gotchas**

- shopify_app_secret has three states: omitted = keep, null or empty = clear, a value = replace. The response only says shopify_app_secret_set.
- language_mode auto sets forced_locale to null even when the same body sends a locale.
- A domain change saves the row first, then registers the new host (releasing the previous registration only when the new one is not already registered). A registration error is returned in domain.error and sets domain_verification_status to failed; the row stays saved.
- whop_tracking_enabled rewrites the storefront content with only whopTracking.enabled changed, guarded by the row version: a concurrent storefront save is retried once, then refused with 409.
- payment_provider_id, canary_* and the storefront content cannot be changed here (ignored). Use PUT /v1/checkouts/:shopId/storefront for the storefront content and PUT /v1/checkouts/:shopId/routing for payments.
- Switching away from builtin:bikery without theme_settings keeps only the stored overrides the target theme accepts.
- An empty body is a valid no-op that still updates updated_at and refreshes the cache.
- Unknown body keys are ignored, not refused.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).
- The shop view carries shopify_api_key_set instead of the Shopify Admin API access token. The token and the app secret are only readable through GET /v1/checkouts/:shopId/secrets, which refuses every API key.
- A store belongs to the account of its payment route (checkout routing owner) or, for older stores, to the account whose key its legacy payment provider carries. Another account's store answers 404, never 403.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `DELETE /v1/checkouts/:shopId`

**Scope** `checkouts.write` - **Archive a store**

Archives the store: it leaves the store list and every store read, is deactivated with SMS and e-mail recovery switched off, its payment route is deactivated and detached from its checkout, flow and AB test, and its uptime monitor is paused. Orders, subscriptions and financial history are kept. The domain registration on the hosting provider is kept; remove it first with POST /v1/checkouts/:shopId/domain/remove if needed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID of a store of the caller's account. Must be a UUID (400 otherwise). |

**Response**

```json
{
  "deleted": true,
  "archived": true
}
```

| response field | type | description |
|---|---|---|
| `deleted` | boolean | Always true on success: the store left the catalogue. |
| `archived` | boolean | Always true: the store row and its history are kept, archived. |

**Errors**

- `400` Invalid store id (not a UUID).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store not found (unknown, already archived, or of another account); Checkout not found (the store exists in neither database copy).
- `409` This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- There is no restore endpoint: an archived store cannot be read or edited through the API afterwards.
- No request body. Bulk callers call this endpoint once per store and handle each answer.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).

##### `POST /v1/checkouts/:shopId/assets`

**Scope** `checkouts.write` - **Upload a storefront asset**

Upload an image (SVG included) or a video for the store site into the public media bucket under storefront/<shopId>/<prefix>-<timestamp>-<random>.<ext> (immutable, 1-year cache) and return its public URL to put into a site content field. Two transports: the raw file (Content-Type: application/octet-stream, type and prefix in the query) or JSON with base64 bytes.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `content_type` | string | no | Raw mode only, required there: the file MIME type (cut to 64 characters): image/png, image/jpeg, image/webp, image/gif, image/avif, image/svg+xml (sanitised), video/mp4, video/webm. Anything else is 415. |
| `prefix` | string; default `img` | no | Raw mode only: file name prefix, cut to 20 characters, sanitised to [a-z0-9-]. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `content_type` | string | **yes** | JSON mode: the MIME type, max 64, same list as above. |
| `data_base64` | string | **yes** | JSON mode: base64 of the bytes (no data: prefix). Invalid characters are silently dropped by the decoder. |
| `prefix` | string; default `img` | no | JSON mode: max 20 characters (longer is a 400), sanitised to [a-z0-9-]. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Content-Type` | string | **yes** | application/octet-stream: the body is the file itself (preferred: a third smaller, no base64). application/json: the body is the JSON object below. |

**Request body**

```json
{
  "content_type": "image/webp",
  "data_base64": "UklGRlYAAABXRUJQVlA4IEoAAADQAQCdASoBAAEAAkA4JaQAA3AA/v3AgAA=",
  "prefix": "hero"
}
```

**Response**

```json
{
  "url": "https://shop.example.com/storage/v1/object/public/shop-assets/storefront/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11/hero-1789820000000-9f3c2a1b.webp",
  "path": "storefront/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11/hero-1789820000000-9f3c2a1b.webp"
}
```

| response field | type | description |
|---|---|---|
| `url` | string | Public, permanent URL (bucket is public). |
| `path` | string | Object key inside the shop-assets bucket. |

**Errors**

- `400` {"error":"content_type query parameter is required when the body is the file itself"}; {"error":"the body is empty"}; {"error":"invalid payload"} (JSON mode: missing field or prefix over 20 characters)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `413` {"error":"file too large (max 20971520 bytes)"} after decoding; a request body over about 29.4 MB is refused before parsing
- `415` {"error":"unsupported content type <type>"}
- `422` An MP4 whose index (moov) is at the end: re-encode with ffmpeg -i in.mp4 -c copy -movflags +faststart out.mp4
- `500` Internal Server Error with a requestId (unexpected server or storage failure).
- `502` {"error":"storage upload failed: <status> <start of the storage answer>","requestId":"<id>"}: the media storage refused the file; nothing was saved.

**Gotchas**

- Base64 inflates size by ~33 %: a 20 MiB file is ~27 MB of JSON, just under the route body limit.
- data_base64 is not validated: invalid characters are silently dropped by the decoder, producing a corrupt file with a 200.
- Nothing links the asset to the storefront: you must PUT the returned url into a storefront field yourself. Assets are never deleted by the API.
- Files are immutable (x-upsert false, unique names); re-uploading creates a new object.
- An SVG is sanitised before storage.

##### `POST /v1/checkouts/:shopId/checkout`

**Scope** `checkouts.write` - **Assign a checkout or published flow to a store**

Choose the customer journey of a store: a direct checkout profile (its payment settings then drive the store), null to return to the store's own route, or a published flow whose AB Test and Conditions nodes select and pin the checkout per cart. Existing carts keep their checkout and flow version.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid\|null | no | Checkout profile of the account to assign directly, or null to return to the store's own route (its inline checkout). Required when flowId is absent; must be absent when flowId is sent. |
| `flowId` | uuid | no | Published, non-archived flow of the account. Every checkout node must name an active store-type checkout of the account that carries a key. Mutually exclusive with checkoutId. |

**Request body**

```json
{
  "flowId": "8b3c5d70-1e2f-4a6b-9c8d-7e6f5a4b3c21"
}
```

**Response**

```json
{
  "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "checkout_id": "6d1e9b40-2c7a-4f3e-8b15-9a0c4e7d2f61",
  "flow_id": "8b3c5d70-1e2f-4a6b-9c8d-7e6f5a4b3c21"
}
```

| response field | type | description |
|---|---|---|
| `shop_id` | string | Store the assignment applies to. |
| `checkout_id` | uuid\|null | Direct checkout, the store's inline checkout (checkoutId null), or the first checkout of the flow used as a bootstrap credential. With a flow, the actual checkout is chosen per cart: do not use this value as attribution. |
| `flow_id` | uuid | Present only for a flow assignment. |

**Errors**

- `400` {"error":"Invalid","details":...}: send exactly one of checkoutId and flowId; any other key (such as the retired abTestId) is refused.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Invalid account owner; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account; Checkout not found for this account; This store has no route yet - save its payment route first; Published flow not found in this account.
- `409` Restore this archived checkout before assigning it.; Save a Kontrol storefront payment route before applying a flow. (the store has no route or is served by the legacy checkout); Flow owner is unavailable.; Checkout owner is unavailable.; Landing owner is unavailable.; The checkout, flow and entry landing must have the same affiliate owner.; with checkoutId null, the inline-checkout refusals of PUT /v1/checkouts/:shopId/routing (for example An active store route requires an API key).
- `422` This store belongs to no account yet - save its payment route first; Publish a valid flow before assigning it to a store.; Choose a checkout in every payment path of the flow.; Every checkout in this store flow must be active, chargeable and belong to this account.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- Changing the target applies to new carts only; existing cart assignments and flow versions stay pinned.
- Assigning a checkout or a flow clears any legacy AB test on the route; legacy AB test writes answer 410.
- Flow weights and condition facts are resolved on the server, never taken from the buyer. Store GEO uses the serving request country; an unknown country never satisfies a negative rule. Store AOV is the average approved order in the same currency over the previous 30 days.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).

##### `POST /v1/checkouts/:shopId/duplicate`

**Scope** `checkouts.write` - **Duplicate a store**

Clones a store into a new one: every column is copied (storefront content, colours, checkout blocks, recovery settings, modes, legacy provider, theme) except IDs, timestamps and the domain registration fields; canary is reset, SMS and e-mail recovery are switched off, Shopify credentials are dropped unless copy_shopify is true, and the source's store-level pixels are cloned. A payment route is recorded for the new store (served by Kontrol's storefront, inactive), then the new domain is registered on the hosting provider. Returns 201 with the new store view.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Source store ID, a store of the caller's account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `internal_name` | string | **yes** | Trimmed, 1 to 120 characters. |
| `shop_name` | string | **yes** | Trimmed, 1 to 120 characters. |
| `domain` | string | **yes** | Trimmed, 4 to 253 characters, lower-cased, and must be a bare hostname: a scheme, a path, a port, a space, a non-hostname or a numeric last label is refused with 400 and a sentence naming the problem. Unique across all stores (409). |
| `admin_url` | string\|null; default `null` | no | Trimmed, max 253, lower-cased. Platform admin host of the copy (Shopify or Medusa stores). Unique across all stores (409). Leave null for in-house stores. |
| `copy_shopify` | boolean; default `false` | no | true keeps the source's Shopify access token, app client ID and encrypted app secret; false clears all three. |

**Request body**

```json
{
  "internal_name": "Example UK",
  "shop_name": "Example Store",
  "domain": "uk.example.com",
  "admin_url": null,
  "copy_shopify": false
}
```

**Response** `201`

```json
{
  "shop": {
    "id": "8c4e2a10-5d7f-4b3e-a1c9-6e2d0f8b7a55",
    "internal_name": "Example UK",
    "shop_name": "Example Store",
    "domain": "uk.example.com",
    "admin_url": null,
    "cms": "product",
    "is_active": true,
    "payment_provider_id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
    "canary_payment_provider_id": null,
    "canary_percent": 0,
    "render_domain_id": "cdm-example0002",
    "dns_record_type": "CNAME",
    "dns_record_target": "storefront-example.onrender.com",
    "domain_verification_status": "pending",
    "domain_verified_at": null,
    "user_id": null,
    "updated_at": "2026-11-24T09:00:00.000Z",
    "created_at": "2026-11-24T09:00:00.000Z",
    "unified_tool_mode": "external",
    "recovery_sink_mode": "external",
    "sms_recovery_enabled": false,
    "email_recovery_enabled": false,
    "shopify_app_client_id": null,
    "theme_id": "market",
    "shopify_app_secret_set": false,
    "whop_tracking_enabled": false,
    "shopify_api_key_set": false,
    "support_email": "support@example.com",
    "support_phone": null,
    "logo_url": null,
    "logo_height_override": null,
    "favicon_url": null,
    "primary_color": "#0f172a",
    "language_mode": "auto",
    "forced_locale": null,
    "shipping_protection_mode": "on",
    "shipping_protection_price_cents": 299,
    "shipping_protection_label": null,
    "shipping_protection_description": null,
    "allowed_countries": [
      "US",
      "CA"
    ],
    "affiliate_id": null,
    "checkout_tags": [],
    "theme_settings": {}
  },
  "owner": {
    "providerId": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
    "providerName": "Kontrol - Example Store",
    "owner": "ops@example.com",
    "keyName": "example-store",
    "keyId": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
    "defaultTripId": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa"
  },
  "storefrontLite": {
    "brandKit": "editorial"
  }
}
```

| response field | type | description |
|---|---|---|
| `shop` | object | Every column of the new store except the encrypted app secret, the Shopify access token and the storefront content, plus shopify_api_key_set, shopify_app_secret_set and whop_tracking_enabled. |
| `owner` | object | Same owner as the source. |
| `storefrontLite` | object\|null | Copied storefront facts. |
| `domainWarning` | string (optional) | Present when the copy was saved but its domain could not be registered; the copy exists and does not answer on that domain until registration succeeds. |

**Errors**

- `400` {"error":"invalid payload","details":<flattened validation errors>}; a domain sentence such as "<value>" carries a scheme - give the hostname alone (pay.example.com) / carries a path / carries a port / contains a space / is not a hostname / ends in a numeric suffix.
- `401` Missing bearer token, or invalid API key.
- `402` The account has reached its store allowance. (plan store quota); A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); An account is required to duplicate a store; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: source unknown, archived or of another account.
- `409` domain already used by another checkout; admin_url already used by another checkout.
- `500` Duplicate failed (the insert returned no row), or Internal Server Error with a requestId.

**Gotchas**

- 201 on success.
- Only store-level pixels (no product) are cloned. Products, listings, Google Ads tags and the source's payment configuration are not copied: the new route has no ATRI, no key and is inactive.
- The storefront content is copied verbatim; review it after cloning.
- A registration failure does not undo the copy: read domainWarning, then fix the domain with the domain routes instead of duplicating again.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).
- The shop view carries shopify_api_key_set instead of the Shopify Admin API access token. The token and the app secret are only readable through GET /v1/checkouts/:shopId/secrets, which refuses every API key.

##### `PUT /v1/checkouts/:shopId/medusa/connection`

**Scope** `checkouts.write` - **Save Medusa connection**

Save deployment type (self_hosted or cloud), the explicit public HTTPS storefront/backend origins, encrypted write-only keys and region/channel selection.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `backend_url` | string | no | Trimmed, 3 to 300: the Medusa backend host or URL; its host becomes the store admin URL. Changing it requires a new secret_key in the same body. |
| `hosting` | string | no | self_hosted or cloud. |
| `storefront_url` | string\|null | no | Trimmed, max 300: the public storefront origin (https), distinct from the backend and the checkout domain. |
| `secret_key` | string\|null | no | Trimmed, max 500, write-only (encrypted). Absent keeps the stored key; "" or null removes it. |
| `publishable_key` | string\|null | no | Trimmed, max 500. Absent keeps it; null or "" removes it. |
| `region_id` | string\|null | no | Trimmed, max 100. |
| `sales_channel_id` | string\|null | no | Trimmed, max 100. |

**Request body**

```json
{
 "backend_url": "https://api.shop.example.com",
 "secret_key": "sk_example",
 "publishable_key": "pk_example",
 "region_id": "reg_example",
 "sales_channel_id": "sc_example",
 "hosting": "cloud",
 "storefront_url": "https://shop.example.com"
}
```

**Response**

```json
{
 "connection": {
  "backendUrl": "https://api.shop.example.com",
  "hosting": "cloud",
  "storefrontUrl": "https://shop.example.com",
  "secretKeySet": true,
  "publishableKey": "pk_example",
  "regionId": "reg_example",
  "salesChannelId": "sc_example",
  "currencyCode": null,
  "pluginVersion": null,
  "storeName": null,
  "connectedAt": null,
  "lastPingAt": null,
  "lastError": null
 }
}
```

| response field | type | description |
|---|---|---|
| `connection` | object | { backendUrl, hosting, storefrontUrl, secretKeySet, publishableKey, regionId, salesChannelId, currencyCode, pluginVersion, storeName, connectedAt, lastPingAt, lastError }. The secret key is never returned. |

**Errors**

- `400` {"error":"<first validation message>"} (strict body: unknown keys refused); {"error":"The Medusa backend URL is not a hostname (e.g. api.store.example.com)"}; {"error":"Provide a new secret key when changing the Medusa backend"}; {"error":"Not a Medusa store"}; an invalid storefront origin
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled for this account"}; {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Absent keys retain the stored value; null/empty removes it. Changing backend requires a new secret key and invalidates verification.
- Storefront URL is an explicit public HTTPS origin, never inferred from the checkout or Cloud backend URL. Changing the effective configuration invalidates verification. Hosting defaults to self_hosted for older connections.

##### `POST /v1/checkouts/:shopId/medusa/installations`

**Scope** `checkouts.write` - **Create Medusa installation session**

Create a 60-minute installation session bound to the store's saved Medusa connection and storefront URL, and return the one-time install command (with its private code) once. Earlier pending sessions of the store are cancelled. Answers 201 with Cache-Control no-store.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response** `201`

```json
{
 "id": "00000000-0000-4000-8000-000000000001",
 "status": "pending",
 "expiresAt": "2026-10-16T01:00:00.000Z",
 "createdAt": "2026-10-16T00:00:00.000Z",
 "completedAt": null,
 "lastError": null,
 "code": "<one-time code>",
 "command": "npx --yes https://api.example.com/v1/medusa/kontrol-installer-1.0.0.tgz --api https://api.example.com --installation 00000000-0000-4000-8000-000000000001 --code <one-time code> --apply"
}
```

**Errors**

- `400` {"error":"Not a Medusa store"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled for this account"}; {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; Installation unavailable, expired or changed. Generate a new command from the dashboard.
- `409` Installation unavailable, expired or changed. Generate a new command from the dashboard. (no saved connection or storefront URL, or no account routes the store)
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` {"error":"Installation busy. Check its saved status before retrying.","requestId":"<id>"} (Retry-After: 1): eight installation controls are already running; retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the installation deadline (25 s, 5 s per control statement) ran out; check the saved status before retrying.

**Gotchas**

- The command includes a private short-lived code. Do not persist it in source control or logs. Manifest authorization and public pairing proof have different purposes.

##### `GET /v1/checkouts/:shopId/medusa/installations/latest`

**Scope** `checkouts.read` - **Read latest Medusa installation status**

The latest installation session of the store: status pending, completed, cancelled, expired or stale (the saved connection changed since it was created), or null when none. Never returns the code or any key.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
 "id": "00000000-0000-4000-8000-000000000001",
 "status": "pending",
 "expiresAt": "2026-10-16T01:00:00.000Z",
 "createdAt": "2026-10-16T00:00:00.000Z",
 "completedAt": null,
 "lastError": null
}
```

**Errors**

- `400` {"error":"Not a Medusa store"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled for this account"}; {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` {"error":"Installation busy. Check its saved status before retrying.","requestId":"<id>"} (Retry-After: 1): eight installation controls are already running; retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the installation deadline (25 s, 5 s per control statement) ran out; check the saved status before retrying.

**Gotchas**

- The command includes a private short-lived code. Do not persist it in source control or logs. Manifest authorization and public pairing proof have different purposes.

##### `POST /v1/checkouts/:shopId/medusa/orders/retry`

**Scope** `checkouts.write` - **Retry a failed Medusa order export**

Queue an explicit retry of an approved store order rejected by the Medusa HTTP endpoint. The worker sends the original saved payload to the original backend using the same order identity. This never charges the customer.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | uuid | **yes** | Approved order of this store whose last export failed with an HTTP answer from Medusa. Strict body: no other key. |

**Request body**

```json
{"orderId":"11111111-1111-4111-8111-111111111111"}
```

**Response** `202`

```json
{"queued":true}
```

| response field | type | description |
|---|---|---|
| `queued` | boolean | True when the worker may retry the saved export; HTTP 202. |

**Errors**

- `400` {"error":"Invalid order"}; {"error":"Not a Medusa store"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled for this account"}; {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` {"error":"Order is not eligible for export retry"}: absent, another store's, not approved, already exported, retried less than 5 minutes ago, or failed for a reason other than an HTTP answer
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The backend and saved payload are never rewritten. Correct merchant configuration before retrying. Schema-invalid saved payloads still require separate investigation.
- Test-card exclusions and backend/currency mismatch holds cannot be cleared through this endpoint. Historical errors are not automatically replayed.

##### `POST /v1/checkouts/:shopId/medusa/ping`

**Scope** `checkouts.write` - **Test Medusa readiness**

Validate Medusa 2.21.2, plugin readiness, shared locking/persistent workflow and the actual publishable-key region/channel access. Verifies exact HTTPS checkout and saved storefront origins against the plugin configuration; Cloud guidance uses managed Redis on Launch/Scale/Enterprise.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 400 {"error":"A value has an invalid format."} (the store is read from the API database), not 404. |

**Response**

```json
{
  "ok": true,
  "status": 200,
  "warnings": []
}
```

**Errors**

- `400` {"error":"A value has an invalid format."}: shopId is not a UUID (checked after the integration check).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled"}; {"error":"Medusa store not found"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `502` {"error":"Unable to verify the Medusa connection - please try again"}

**Gotchas**

- A backend that does not answer correctly is NOT an HTTP error: the answer is 200 with ok false, status = the HTTP status Medusa gave (0 when unreachable) and an error sentence (unreachable or disallowed backend, secret key refused, plugin missing with pluginMissing true, an invalid status response, no secret key stored). The sentence is also stored as the last error of the connection.
- Store ownership is read from the checkout routing of the store (its owner e-mail) only. A store that still carries a legacy payment_provider_id no longer fails here (before 2026-10-31 it answered 500 because that table no longer exists).

##### `GET /v1/checkouts/:shopId/onboarding`

**Scope** `checkouts.read` - **Read the setup-wizard state of a store**

Everything the store setup wizard renders: the stored cursor (step reached and manual acknowledgements), the store facts it keys off (admin URL, checkout domain, derived storefront host, whether a Shopify token is stored and how), the Shopify OAuth callback URL and scopes to register on the Shopify app, the dashboard URL, a reusable Shopify app of another store, and for a Medusa store the plugin install instructions. Observable progress is never stored here: it is recomputed by GET /v1/checkouts/:shopId/overview.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "state": {
    "shopId": "b3f...",
    "platform": "shopify",
    "step": 4,
    "ack": {
      "app_created": true
    },
    "updatedAt": "2026-09-23T14:02:11.000Z"
  },
  "shop": {
    "id": "b3f...",
    "adminUrl": "example-store.myshopify.com",
    "domain": "shop.example.com",
    "cms": "shopify",
    "isActive": false,
    "storefront": "shop.example.com",
    "shopifyConnected": true,
    "shopifyAppClientId": null,
    "connectedBy": "manual token"
  },
  "callbackUrl": "https://api.kontrolcheckout.com/v1/shopify/oauth/callback"
}
```

| response field | type | description |
|---|---|---|
| `state` | object | { shopId, platform (shopify, product, medusa), step (1 to 8), ack (flags), updatedAt }. A store never opened in the wizard gets step 1, ack {}, updatedAt null and its own platform. |
| `shop` | object | { id, adminUrl, domain, cms, isActive, storefront, shopifyConnected, shopifyAppClientId, connectedBy (oauth, manual token or null) }. |
| `medusa` | object\|null | Medusa stores only: { connection, plugin { name, version, tarball, install { npm, yarn, pnpm } \| null, storefrontRequired, storefrontHint, config }, storefront }. |
| `callbackUrl` | string | The Shopify OAuth redirect URL to register on the app ("" when unknown). |
| `shopifyScopes[]` | object[] | { scope, reason } for read_products, read_orders, write_orders, read_themes. |
| `dashboardUrl` | string\|null | The App URL to register on the Shopify app. |
| `reusableApp` | object\|null | { shopName, clientId } of another store already connected through a Shopify app, so the same app can be reused. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- A store that has never been opened in the wizard has no row: the endpoint answers with a synthetic step-1 state rather than 404, so the wizard always has something to render.
- connectedBy is 'manual token' for stores connected by pasting a shpat_ token (no app client id). The wizard must say so instead of showing an empty Client ID field.
- callbackUrl is <API public URL>/v1/shopify/oauth/callback, or "" when the API public URL is not configured. dashboardUrl is the first configured dashboard origin, or null.
- shop.storefront is the checkout domain minus its pay. prefix (Shopify and in-house stores) or the host of the saved Medusa storefront URL.

##### `PUT /v1/checkouts/:shopId/onboarding`

**Scope** `checkouts.write` - **Move the setup-wizard cursor**

Upsert the wizard cursor: the step the operator is on, and the manual acknowledgements. `ack` is MERGED into the stored object, never replaced, so one screen can never clear another's flag. Writing here has no effect on the store itself - it is a bookmark, not a state machine.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `platform` | string | no | shopify, product or medusa. Absent = the store's own platform (from its cms); only a body naming a platform overrides it. |
| `step` | integer | no | 1 to 8: the step the operator is on. Absent keeps the stored step (1 on first write). |
| `ack` | object | no | Flat object of booleans, merged into the stored flags (never replaced). Meaningful keys: app_created, theme_verified. |

**Request body**

```json
{
  "step": 6,
  "ack": {
    "theme_verified": true
  }
}
```

**Response**

```json
{
  "shopId": "b3f...",
  "platform": "shopify",
  "step": 6,
  "ack": {
    "app_created": true,
    "theme_verified": true
  },
  "updatedAt": "2026-09-23T14:20:02.000Z"
}
```

**Errors**

- `400` {"error":"invalid payload","details":...}: step outside 1 to 8, unknown platform, or ack not an object of booleans
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- Only two ack keys are meaningful: app_created (step 3) and theme_verified (step 6). The theme one is a fallback - a published storefront is checked for real by POST /v1/checkouts/:shopId/theme-check.

##### `DELETE /v1/checkouts/:shopId/onboarding`

**Scope** `checkouts.write` - **Clear the setup-wizard cursor**

Drop the wizard row so the store starts the wizard from step 1 again. Changes nothing about the store.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- Idempotent: deleting a cursor that does not exist still answers ok.

##### `GET /v1/checkouts/:shopId/overview`

**Scope** `checkouts.read` - **Read the store setup checklist**

The 'where are we' view of one store: a checklist of what it needs to sell (identity, owning account, domain registration, payment route ATRI, route API key, pixels, recovery, active flag, Shopify connection for Shopify stores, Medusa connection for Medusa stores, theme and brand, homepage copy, homepage blocks, products listed), a done/total score, pixel and product counts, and preview links for the homepage and the first sellable product. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Response**

```json
{
  "checklist": [
    {
      "key": "identity",
      "label": "Identity",
      "status": "done",
      "detail": "Example Store - shop.example.com",
      "tab": "identity"
    },
    {
      "key": "account",
      "label": "Kontrol account (ck_ key)",
      "status": "done",
      "detail": "ops@example.com - key example-store",
      "tab": "payment"
    },
    {
      "key": "domain",
      "label": "Domain on Render - cocoapi storefront",
      "status": "done",
      "detail": "verified - CNAME record - value on the Domain tab",
      "tab": "domain"
    },
    {
      "key": "routing",
      "label": "Payment route (ATRI)",
      "status": "done",
      "detail": "US Primary Pool",
      "tab": "payment"
    },
    {
      "key": "pixels",
      "label": "Pixels",
      "status": "done",
      "detail": "2 pixels",
      "tab": "pixels"
    },
    {
      "key": "recovery",
      "label": "Abandoned-cart relances",
      "status": "done",
      "detail": "SMS",
      "tab": "recovery"
    },
    {
      "key": "active",
      "label": "Store active",
      "status": "done",
      "detail": "yes",
      "tab": "identity"
    },
    {
      "key": "brand",
      "label": "Theme & brand",
      "status": "done",
      "detail": "editorial - header light",
      "tab": "theme"
    },
    {
      "key": "homepage",
      "label": "Homepage copy",
      "status": "warn",
      "detail": "2/4 - intro, story, testimonials, FAQ (Generate fills them)",
      "tab": "home"
    },
    {
      "key": "blocks",
      "label": "Homepage blocks",
      "status": "todo",
      "detail": "0 blocks enabled",
      "tab": "pdp"
    },
    {
      "key": "products",
      "label": "Products listed",
      "status": "done",
      "detail": "4 listed - 5 active - 6 total",
      "href": "/ecommerce/stores/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11/products"
    }
  ],
  "score": {
    "done": 10,
    "total": 12
  },
  "counts": {
    "pixels": 2,
    "products": {
      "total": 6,
      "active": 5,
      "listed": 4
    }
  },
  "preview": {
    "home": "https://storefront-internal.example.com/preview/home/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11?exp=1789830000&sig=9f2c0000example",
    "product": "https://storefront-internal.example.com/preview/product/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13?exp=1789830000&sig=1b7d0000example",
    "productTitle": "Posture Corrector Pro"
  }
}
```

| response field | type | description |
|---|---|---|
| `checklist[].key` | string | identity, account, domain, routing, charge_key (an API key is set on the payment route), pixels, recovery, active, shopify (Shopify stores only), medusa (Medusa stores only), brand, homepage, blocks, products, in that order. The example shows a subset (the charge_key item is left out); score counts every item. |
| `checklist[].status` | enum: done\|todo\|warn\|na | na items (recovery when both SMS and e-mail are off) are excluded from the score. |
| `checklist[].label / detail` | string | Human labels; the domain label names the hosting service serving the store. The values are display text, not stable identifiers: rely on key and status. |
| `checklist[].tab / href` | string | Where the dashboard fixes the item (a tab of the store page, or a dashboard link). |
| `score` | object | done / total over the scored items. |
| `counts.products` | object | total = owned plus listed products; active = status active; listed = active and actively listed on this store. Read from the database that serves the store. |
| `preview.product` | string\|null | Signed preview of the first listed active product (fallback: first active, then any); null when the store has no product. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- routing is warn, never todo, when the route has no ATRI. charge_key is todo when the route carries no API key: such a store cannot take a payment.
- The domain item reports the registration status only; the DNS record to create is computed live by POST /v1/checkouts/:shopId/domain/check, never from dns_record_target.
- The route is read with the caller's account as owner filter.
- Preview links are signed for one hour and are null when the storefront preview host or its signing secret is not configured. Fetch them again instead of storing them.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `GET /v1/checkouts/:shopId/payment-methods`

**Scope** `checkouts.read` - **Read a store's payment methods (card, wallet, wire sources)**

Reads a store's payment methods (which card, wallet and wire source serves the store); the store's payment routing (ATRI, 3DS, wallet switches) is GET /v1/checkouts/:shopId/routing. Reads how a store accepts card, wallet and wire payments: for each method, whether it is on and which single source or ATRI serves it, with inherited account defaults marked.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string (uuid) | **yes** | Store id (GET /v1/checkouts). |

**Response**

```json
{
  "card": {
    "enabled": true,
    "sourceType": "atri",
    "sourceId": "00000000-0000-4000-8000-000000000401",
    "inherited": true
  },
  "wallet": {
    "enabled": true,
    "sourceType": "atri",
    "sourceId": "00000000-0000-4000-8000-000000000101",
    "inherited": true
  },
  "wire": {
    "enabled": false,
    "sourceType": "atri",
    "sourceId": null,
    "inherited": true
  }
}
```

| response field | type | description |
|---|---|---|
| `card` | object | {enabled, sourceType (single \| atri), sourceId, inherited}. |
| `wallet` | object | Same shape. |
| `wire` | object | Same shape. |
| `*.inherited` | boolean | True when the store has no saved setting for the method and the value comes from the account: card = the store's resolved card ATRI (enabled), wallet = the active default wallet ATRI (enabled only when one exists), wire = the active default wire ATRI (never enabled by inheritance). |

**Errors**

- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: shopId is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"Store not found"}: unknown shopId, or a store not routed to this account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

##### `PUT /v1/checkouts/:shopId/payment-methods`

**Scope** `checkouts.write` - **Set a store's payment methods (card, wallet, wire sources)**

Sets a store's payment methods (card, wallet and wire sources); the store's payment routing row is written with PUT /v1/checkouts/:shopId/routing. Saves the card, wallet and wire settings sent for a store in one transaction and returns all three. A single card gateway becomes a one-member card ATRI of the store (named "Store card gateway <first 8 characters of shopId>", created once, copying the BIN routing, scrub and 3DS profiles of the store's current card ATRI), so it keeps the same rules, 3DS and dispatch pipeline.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string (uuid) | **yes** | Store id (GET /v1/checkouts). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `card` | object | no | Setting of the card method. Omitted: unchanged. |
| `card.enabled` | boolean | **yes** | Turns the method on or off for the store. |
| `card.sourceType` | string | **yes** | single or atri. |
| `card.sourceId` | string (uuid) \| null | **yes** | single: a gateway (MID) id of GET /v1/accounts; atri: a card ATRI id of GET /v1/trips. Must belong to this account. Required when enabled is true ("Select a payment source"). |
| `wallet` | object | no | Setting of the wallet method. Omitted: unchanged. |
| `wallet.enabled` | boolean | **yes** | Turns the method on or off for the store. |
| `wallet.sourceType` | string | **yes** | single or atri. |
| `wallet.sourceId` | string (uuid) \| null | **yes** | single: a wallet provider id of GET /v1/wallet-providers; atri: a wallet ATRI id of GET /v1/payment-atris. Must belong to this account. Required when enabled is true ("Select a payment source"). |
| `wire` | object | no | Setting of the wire method. Omitted: unchanged. |
| `wire.enabled` | boolean | **yes** | Turns the method on or off for the store. |
| `wire.sourceType` | string | **yes** | single or atri. |
| `wire.sourceId` | string (uuid) \| null | **yes** | single: a bank account id of GET /v1/bank-accounts; atri: a wire ATRI id of GET /v1/payment-atris. Must belong to this account. Required when enabled is true ("Select a payment source"). |

**Request body**

```json
{
  "wire": {
    "enabled": true,
    "sourceType": "single",
    "sourceId": "00000000-0000-4000-8000-000000000501"
  },
  "card": {
    "enabled": true,
    "sourceType": "atri",
    "sourceId": "00000000-0000-4000-8000-000000000401"
  }
}
```

**Response**

```json
{
  "card": {
    "enabled": true,
    "sourceType": "atri",
    "sourceId": "00000000-0000-4000-8000-000000000401",
    "inherited": false
  },
  "wallet": {
    "enabled": true,
    "sourceType": "atri",
    "sourceId": "00000000-0000-4000-8000-000000000101",
    "inherited": true
  },
  "wire": {
    "enabled": true,
    "sourceType": "single",
    "sourceId": "00000000-0000-4000-8000-000000000501",
    "inherited": false
  }
}
```

| response field | type | description |
|---|---|---|
| `card` | object | {enabled, sourceType (single \| atri), sourceId, inherited}. |
| `wallet` | object | Same shape. |
| `wire` | object | Same shape. |
| `*.inherited` | boolean | True when the store has no saved setting for the method and the value comes from the account: card = the store's resolved card ATRI (enabled), wallet = the active default wallet ATRI (enabled only when one exists), wire = the active default wire ATRI (never enabled by inheritance). |

**Errors**

- `400` {"error":"Invalid payment methods","details":<zod flatten>}: an invalid setting, an unknown key, enabled true without sourceId.
- `400` {"error":"Choose payment sources from this account"}: a single source of another account or of the wrong kind; {"error":"Choose an ATRI from this account and payment method"}: an ATRI of another account or method.
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: shopId is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"Account required"}: the caller has no account.
- `404` {"error":"Store not found"}: unknown shopId, or a store not routed to this account.
- `409` {"error":"KontrolPay gateway is not active yet"}: a KontrolPay gateway that the platform has not activated cannot be the single enabled card gateway.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Only the methods sent change; the answer always carries all three.
- Turning a method off (enabled false) is always accepted, with or without a sourceId.
- Saving clears the routing caches: the next checkout uses the new setting.

##### `GET /v1/checkouts/:shopId/routing`

**Scope** `checkouts.read` - **Read a store's effective payment routing (checkout side: ATRI, wallets, 3DS)**

The checkout-side answer for one store's routing (ATRI, CRM, Apple Pay combined with the account switch, Google Pay, 3DS key; 404 when the store has no route); the full stored row (key, checkout template, flow, default MID) is GET /v1/checkouts/:shopId/routing/details. The payment routing a checkout applies for one store: active flag, ATRI, CRM, Apple Pay (the store switch AND the account switch), Google Pay and 3DS integration key. The account version of the same row is GET /v1/checkouts/:shopId/routing/details (snake_case); writes go through PUT /v1/checkouts/:shopId/routing.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string | **yes** | Store (checkout shop) id. |

**Response**

```json
{
  "shopId": "11111111-1111-4111-8111-111111111111",
  "active": true,
  "atri": "22222222-2222-4222-8222-222222222222",
  "atriName": "US Primary Pool",
  "crm": "nmi",
  "applePay": false,
  "applePayGlobal": false,
  "googlePay": true,
  "threeDs": null,
  "updatedAt": "2026-11-18T15:59:02.410Z"
}
```

| response field | type | description |
|---|---|---|
| `shopId` | string | Store id. |
| `active` | boolean | false: ignore the row and use the key default ATRI. |
| `atri / atriName` | uuid \| null / string \| null | ATRI the store charges through and its name. |
| `crm` | string | CRM of the routing row (nmi). |
| `applePay` | boolean | Show Apple Pay: the store switch AND the account-wide switch. |
| `applePayGlobal` | boolean | The account-wide Apple Pay switch (false: off for every store). |
| `googlePay` | boolean | The store's Google Pay switch. |
| `threeDs` | string \| null | 3DS integration key of the store. |
| `updatedAt` | string (ISO 8601) | Last routing change. |

**Errors**

- `401` Missing API key; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the key owner account has no paid or granted platform subscription.
- `403` Banned (the key owner is banned); or API key scope denied (code insufficient_scope).
- `404` no routing for this checkout (no row, or another account); or Store unavailable (the store is inactive or archived).
- `503` Service temporarily unavailable (detail: authentication backend error).

**Gotchas**

- The account settings are cached up to 30 seconds, so a just-flipped Apple Pay account switch can lag.

##### `PUT /v1/checkouts/:shopId/routing`

**Scope** `checkouts.write` - **Set a store's payment routing**

Creates or updates the store's own payment route: only the keys present in the body change (first-save defaults: crm nmi, wallets off, active true). The route is stamped with the store's account and the caller. api_key_id names the account API key the storefront charges with; it is stored encrypted for the storefront. When the route is active and the store uses neither a flow nor a shared checkout profile, the configuration is also copied into the store's own inline checkout, which becomes the store's checkout. Returns the resolved route, never the key.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `atri_id` | uuid\|null | no | Classic ATRI of the store's account (active or not), otherwise 400 'ATRI not found for this account'. null clears it (the key's default ATRI is used). Omit to keep. |
| `crm` | enum: nmi; default `nmi` | no | Gateway family. Omit to keep. |
| `three_ds_integration_key` | string\|null | no | Max 64. Key of a 3DS integration configured on the account (see GET /v1/checkouts/profiles/3ds-options), otherwise 400. null or empty clears it. Omit to keep. |
| `apple_pay` | boolean; default `false` | no | Offer Apple Pay. Omit to keep. |
| `google_pay` | boolean; default `false` | no | Offer Google Pay. Omit to keep. |
| `active` | boolean; default `true` | no | Whether the route is applied. Omit to keep (a new store's route starts inactive). |
| `api_key_id` | uuid\|null | no | An active API key of the store's account, allowed to charge (POST /v1/charge within its scopes). null clears it, and the store can no longer take a payment. Omitted: keeps the current key; when the route has none, the key carried by the store's legacy provider is used, else one is derived only when unambiguous (the account's single eligible key with stored material, or the one whose default ATRI is the route's ATRI; the keys that were the account's checkout keys before keys had a single type come first, and any other active key is considered only when the account has none of them). |

**Request body**

```json
{
  "atri_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
  "api_key_id": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
  "apple_pay": true,
  "google_pay": false,
  "active": true
}
```

**Response**

```json
{
  "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "owner_email": "ops@example.com",
  "atri_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
  "crm": "nmi",
  "api_key_id": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
  "three_ds_integration_key": null,
  "apple_pay": true,
  "google_pay": false,
  "settings": {},
  "ab_test_id": null,
  "flow_id": null,
  "active": true,
  "served_by": "storefront",
  "checkout_id": "6d1e9b40-2c7a-4f3e-8b15-9a0c4e7d2f61",
  "checkout_name": "Example Store - 5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "updated_by": "jane@example.com",
  "created_at": "2026-09-16T10:00:00.000Z",
  "updated_at": "2026-09-18T15:59:02.410Z",
  "domain": "shop.example.com",
  "atri_name": "US Primary Pool",
  "api_key_name": "example-store",
  "api_key_prefix": "ck_live_ab12",
  "atri_default_mid": "NMI - Example US 01",
  "atri_default_mid_id": "0e5f7a21-6c3d-4b8e-a9f0-1d2c3b4a5e6f",
  "api_key_set": true
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | Same shape as GET /v1/checkouts/:shopId/routing/details, read again after the save. |

**Errors**

- `400` {"error":"invalid payload","details":<flattened validation errors>}; This checkout carries no Kontrol key: attach a provider before routing it; Choose a configured 3DS integration from this account; ATRI not found for this account; That API key does not belong to this store's account; That API key is revoked - pick an active one; That key predates secure reveal, so cocoapi cannot read it back. Create a new API key and pick that one.
- `401` Missing bearer token, or invalid API key.
- `402` The account has reached its store allowance. (plan store quota); A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `409` When the route is active without a flow: An active store route requires an API key; the route's key is unusable (inactive, of another account, or its scopes do not allow POST /v1/charge); the stored key material does not match the key; Store ATRI is unavailable for this account; Store unavailable for checkout configuration; Store route belongs to another account; Inline checkout belongs to another account; The store inline checkout is unavailable.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).
- `503` CHECKOUT_ENCRYPTION_KEY is not set on the API, so the key cannot be stored for the storefront.

**Gotchas**

- Presence semantics: {"atri_id": null} clears the ATRI, omitting atri_id keeps it; the same for three_ds_integration_key and api_key_id. Booleans and crm: omitted = keep.
- Saving active true requires a key on the route (given, kept or derived), or the save is refused with 409 and nothing is changed.
- owner_email is always the store's account, never chosen by the caller.
- When a shared checkout profile is assigned to the store (POST /v1/checkouts/:shopId/checkout), the response shows that checkout's payment values; the values saved here are the store's own route, used again when the store returns to it (checkoutId null).
- An inactive ATRI is accepted here and only fails at charge time.
- Revoking a key does not clear the route; pick another key here.
- Every successful write is recorded in the account's action log (page Checkouts, object type checkout).

##### `GET /v1/checkouts/:shopId/routing/details`

**Scope** `checkouts.read` - **Read a store's full payment-routing record (key, checkout, flow, default MID)**

The store's full stored payment-routing row (key, checkout template, flow, A/B, served_by, default MID, the raw apple_pay flag; null when the store has none); GET /v1/checkouts/:shopId/routing is the checkout-side answer (Apple Pay combined with the account switch, 404 when none). Returns the store's resolved payment route: the ATRI it charges through, the CRM, the API key the storefront charges with (named, never returned), the 3DS integration, the Apple Pay and Google Pay switches, the active flag, the hosting service, and the checkout or flow assigned to the store. When a checkout profile is assigned, its payment values are the ones shown.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Response**

```json
{
  "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "owner_email": "ops@example.com",
  "atri_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
  "crm": "nmi",
  "api_key_id": "a91c3e70-5d2b-4f8e-9c11-6b0d4a7e2f33",
  "three_ds_integration_key": null,
  "apple_pay": true,
  "google_pay": false,
  "settings": {},
  "ab_test_id": null,
  "flow_id": null,
  "active": true,
  "served_by": "storefront",
  "checkout_id": "6d1e9b40-2c7a-4f3e-8b15-9a0c4e7d2f61",
  "checkout_name": "Example Store - 5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "updated_by": "jane@example.com",
  "created_at": "2026-09-16T10:00:00.000Z",
  "updated_at": "2026-09-18T15:59:02.410Z",
  "domain": "shop.example.com",
  "atri_name": "US Primary Pool",
  "api_key_name": "example-store",
  "api_key_prefix": "ck_live_ab12",
  "atri_default_mid": "NMI - Example US 01",
  "atri_default_mid_id": "0e5f7a21-6c3d-4b8e-a9f0-1d2c3b4a5e6f",
  "api_key_set": true
}
```

| response field | type | description |
|---|---|---|
| `shop_id` | string | The store ID the route is saved under. |
| `owner_email` | string | Account the route belongs to. |
| `atri_id` | uuid\|null | ATRI the store charges through; null = the key's default ATRI. |
| `crm` | string | Gateway family; nmi. |
| `api_key_id / api_key_name / api_key_prefix / api_key_set` | uuid\|string\|boolean | The account API key the storefront charges with, its name and prefix; api_key_set is true when the route carries usable key material. A route without a key cannot take a payment. |
| `three_ds_integration_key` | string\|null | Configured 3DS integration of the account used at checkout. |
| `apple_pay / google_pay` | boolean | Wallet switches. |
| `active` | boolean | Whether the route is applied. |
| `served_by` | enum: checkout\|storefront | Hosting service serving the store: storefront = Kontrol's storefront, checkout = the legacy checkout. |
| `checkout_id / checkout_name` | uuid\|string\|null | Checkout profile assigned to the store (or the store's own inline checkout, or the bootstrap checkout of an assigned flow). |
| `flow_id / ab_test_id` | uuid\|null | Assigned flow, or a legacy AB test still pinned. |
| `settings` | object | Checkout settings of the assigned checkout profile. |
| `domain` | string\|null | Host the route answers for, lower-cased without www. |
| `updated_by` | string\|null | E-mail of the last editor. |
| `atri_name / atri_default_mid / atri_default_mid_id` | string\|null | ATRI name and its first active MID by position. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- A store that has no route answers HTTP 200 with a bare null body, not 404.
- GET /v1/checkouts/:shopId/routing is a different, storefront-side route with a camelCase summary; this record is served at /v1/checkouts/:shopId/routing/details.

##### `GET /v1/checkouts/:shopId/secrets`

**Scope** `checkouts.write` - **Read a store's Shopify secrets (in clear)**

Reveals the store's Shopify Admin API access token and its Shopify app client secret in clear (empty strings when unset). Store reads only carry shopify_api_key_set and shopify_app_secret_set.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Response**

```json
{
  "shopify_api_key": "shpat_example_token",
  "shopify_app_secret": "shpss_example_secret"
}
```

| response field | type | description |
|---|---|---|
| `shopify_api_key` | string | The Admin API access token, empty when not connected. |
| `shopify_app_secret` | string | The app client secret, empty when unset or when it cannot be decrypted. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.write"}: the key lacks checkouts.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- The answer is sent with Cache-Control: no-store and Pragma: no-cache; never log or cache it.
- Each reveal that returns at least one value writes one view_secret row to the action log naming the fields, never the values.
- An API key reads the values back here when it holds checkouts.write; a key that only holds the read scope gets 403.

##### `POST /v1/checkouts/:shopId/shopify-oauth/start`

**Scope** `checkouts.write` - **Start the Shopify connection**

Saves the Shopify app's Client ID (and, the first time, its Client Secret, encrypted with the checkout encryption key) on the store, then returns the Shopify authorise URL for the browser to navigate to. Replaces hunting for an Admin API access token: Shopify hands the token to GET /v1/shopify/oauth/callback when the operator approves. Only a Partner-dashboard app works here - a custom app created in the store admin has no client credentials and its token is still pasted by hand.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string | **yes** | 8 to 200 characters (trimmed before use): the Shopify Partner app Client ID. |
| `clientSecret` | string | no | Max 2000, trimmed. "" (the default) keeps the stored secret; required the first time the store is connected. |

**Request body**

```json
{
  "clientId": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",
  "clientSecret": "<the app's client secret; empty to keep the stored one>"
}
```

**Response**

```json
{
  "redirectUrl": "https://example-store.myshopify.com/v1/oauth/authorize?client_id=...&scope=read_products%2Cread_orders%2Cwrite_orders&redirect_uri=...&state=...",
  "shopHost": "example-store.myshopify.com",
  "scopes": "read_products,read_orders,write_orders"
}
```

| response field | type | description |
|---|---|---|
| `redirectUrl` | string | Navigate the BROWSER here. It carries the client id, the scopes, the redirect_uri and a signed state that expires in 10 minutes. |
| `shopHost` | string | The `<shop>.myshopify.com` the flow will run against, derived from the store's admin_url. |
| `scopes` | string | The scopes requested, comma separated - declared in checkouts/onboarding.ts, not by the caller. |

**Errors**

- `400` {"error":"<first validation message>"}; {"error":"This store has no valid *.myshopify.com admin URL - set it first"}; {"error":"The client secret is needed the first time this store is connected"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).
- `503` {"error":"API_PUBLIC_URL is not set - Shopify needs the absolute redirect URL that is registered on the app"}; {"error":"CHECKOUT_ENCRYPTION_KEY is not set on the API, so the client secret cannot be stored. Set it, then connect again."} (before anything is written)

**Gotchas**

- It WRITES before it returns: the client id (and the secret when supplied) are saved even if the operator then abandons the Shopify screen.
- The client secret is stored with the CHECKOUT's encryption key (CHECKOUT_ENCRYPTION_KEY), not cocoapi's own. That variable is easy to have missing on a fresh service, so its absence is reported as a 503 naming it rather than as a codec error.
- An empty clientSecret means 'keep the stored one'. That is what lets a token be refreshed without retyping the secret - but on a store that has never been connected it is a 400, not a silent no-op.
- The scopes come from SHOPIFY_SCOPES in the code, not from the request. Changing what the integration needs is a code change, deliberately - the wizard used to restate them and drifted.
- Nothing is connected when this returns. The token only exists after the callback runs.
- The redirect_uri is always <API public URL>/v1/shopify/oauth/callback, never the request host: Shopify compares it character for character with the app's Allowed redirection URLs.

##### `POST /v1/checkouts/:shopId/shopify/ping`

**Scope** `checkouts.write` - **Prove the stored Shopify token reaches the right store**

Calls Shopify Admin API GET /v1/api/2024-04/shop.json with the token stored on the shop and returns what Shopify itself says: name, primary domain, currency, country and plan. This is the operator's proof that they connected the store they meant to, before importing a catalogue against it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
 "ok": true,
 "status": 200,
 "shop": {
  "name": "Example Store",
  "domain": "shop.example.com",
  "currency": "USD",
  "country": "United States",
  "plan": "Shopify"
 }
}
```

**Errors**

- `400` {"error":"Not a Shopify store - there is no connection to test"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- Never throws for a Shopify refusal: a 401/403 comes back as { ok: false, status: 401, error } so the wizard can show the reason inline.
- ok:false with status 0 means the shop has no admin URL or no stored token yet.
- Outbound: Shopify Admin REST, API version 2024-04, header X-Shopify-Access-Token, 12 s timeout.

##### `GET /v1/checkouts/:shopId/storefront`

**Scope** `checkouts.read` - **Read store site content and company identity**

Return editable shops.storefront content, including optional company identity and About us text, separately from technical whopTracking, handleRedirects and i18n. Also returns the current store theme and signed homepage preview information. This read does not change store data; absent fields are not filled on read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "storefront": {
    "contactPhone": "+1 555 010 2030",
    "homeIntro": "Explore our online collection.",
    "homeStory": "",
    "homeTestimonials": [],
    "homeFaq": [],
    "brandKit": "editorial",
    "fontFamily": "Inter",
    "headingFontFamily": "Fraunces",
    "trackOrder": {
      "enabled": true,
      "label": "Track my order",
      "url": "https://track.example.com",
      "embed": ""
    },
    "theme": {
      "header": "light",
      "footer": "dark"
    },
    "colors": {
      "primary": "#0f172a",
      "accent": "#f59e0b"
    },
    "announcement": {
      "enabled": false,
      "text": "",
      "highlight": ""
    },
    "whyShop": {
      "enabled": false,
      "eyebrow": "",
      "titleLine1": "",
      "titleLine2": "",
      "image": "",
      "bullets": []
    },
    "keypoints": {
      "enabled": false,
      "items": []
    },
    "support": {
      "enabled": false,
      "image": "",
      "line1": "",
      "answerTime": ""
    },
    "tiktok": {
      "enabled": false,
      "heading": "",
      "comments": []
    },
    "whySoCheap": {
      "enabled": false,
      "eyebrow": "",
      "title": "",
      "paragraphs": [],
      "note": "",
      "mainImage": "",
      "accentImage": ""
    },
    "whyChooseUs": {
      "enabled": false
    },
    "finalCta": {
      "enabled": false,
      "title": "",
      "text": "",
      "buttonLabel": "",
      "footnote": ""
    },
    "footerMedia": {
      "enabled": false,
      "image": "",
      "video": "",
      "poster": ""
    },
    "pressLogos": [],
    "languages": [
      {
        "code": "en",
        "label": "English"
      }
    ],
    "currencies": [
      {
        "code": "USD",
        "label": "US Dollar"
      }
    ],
    "customCss": "",
    "customJs": "",
    "company": {
      "name": "Example Trading Ltd",
      "address": "12 Example Street\nExample City"
    },
    "aboutUs": {
      "title": "About our store",
      "intro": "Explore our online collection and the details on each product page.",
      "sections": [
        {
          "title": "Product questions",
          "body": "Use the contact page for questions about a listing or an order."
        }
      ]
    },
    "locales": []
  },
  "technical": {
    "whopTracking": {
      "enabled": false
    },
    "handleRedirects": {
      "posture-corrector": "posture-corrector-pro"
    }
  },
  "preview": {
    "home": "https://checkout.example.com/preview/home/5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11?exp=1789830000&sig=9f2c...e1"
  },
  "theme": {
    "id": "legacy",
    "settings": {},
    "applies": true,
    "cms": "product",
    "product": null,
    "previews": []
  }
}
```

| response field | type | description |
|---|---|---|
| `storefront` | object | Whatever the jsonb holds minus the technical keys - the exact object to edit and send back to PUT. May contain fewer keys than the schema (defaults are applied on write, not on read). |
| `technical` | object | Only the technical keys present in the row. |
| `preview.home` | string\|null | Signed preview URL (1 h). |
| `storefront.company` | object | Explicit legal identity for this store: {name: string max 200, address: multiline registered-office string max 2000}. Missing members default to empty strings when company is supplied; unknown company keys are rejected. Omit company to retain existing facts, or send empty strings to clear. Never infer from a store brand, gateway or payment company. |
| `storefront.aboutUs` | object | Plain text About us content: {title: string max 160, intro: string max 4000, sections: max 12 of {title: string max 160, body: required string max 8000}}. Title/intro/section titles default to empty strings and sections to []. Unknown aboutUs or section keys are rejected. Omit aboutUs to retain existing content; supplying {} clears this authored block. |
| `theme` | object | Current theme { id, settings, applies, cms, product, previews[] { id, url } }; assign a theme with PUT /v1/checkouts/:shopId/theme. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- This remains a configuration save with defaults, not a deep patch: GET first, edit the returned storefront object, and PUT the complete editable configuration. Existing defaulted fields may reset when omitted. New company/aboutUs top-level fields are optional without insertion defaults, so an older client that omits them preserves those stored values.
- Technical whopTracking, handleRedirects and i18n are preserved from the stored row and rejected in the editable payload. locales is editable: en is implicit; allowed codes are fr,it,es,pt,pl,de,nl,sv,da,no,fi.
- company and aboutUs (including aboutUs.sections items) reject unknown nested keys. Existing older nested blocks retain their previous validation behavior.
- Company facts render as escaped text below the footer logo on the native storefront themes, native checkout and /paid. An ownership sentence requires a non-empty company name; the registered-office clause requires an address. No identity is invented or copied from payment configuration. Company is excluded from both translation collection and overlay application.
- About us renders at /about-us and the compatibility /pages/about-us route, with supported locale prefixes. Custom intro or sections supersede homeIntro/homeStory; when no authored About content exists the page reuses those home fields, then neutral localized copy. Blank paragraphs and body-less sections do not render. About text participates in the existing storefront i18n overlay.
- Native storefront footer links point to the About us page. Saving this configuration does not publish or modify an external Shopify or Medusa storefront theme, its About page, or its footer. Their native Kontrol checkout and confirmation can still render configured company identity.
- Example company/address values are illustrative only. Save only verified merchant-supplied legal facts; leave unknown facts empty.

##### `PUT /v1/checkouts/:shopId/storefront`

**Scope** `checkouts.write` - **Save store site content and company identity**

Validate the strict editable storefront payload and merge it into the store site content, keeping the technical keys (whopTracking, handleRedirects, i18n), then refresh the storefront caches. Every top-level key except company and aboutUs has a default, so an absent key is RESET to its default: GET first, edit the returned storefront object and send it back whole.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `company` | object | no | Optional legal identity { name, address }; strict (unknown keys refused). Absent keeps the stored value; send empty strings to clear. |
| `company.name` | string; default `""` | no | Max 200. |
| `company.address` | string; default `""` | no | Max 2000, multi-line registered office. |
| `aboutUs` | object | no | Optional About us content; strict. Absent keeps the stored value; {} clears it. |
| `aboutUs.title` | string; default `""` | no | Max 160. |
| `aboutUs.intro` | string; default `""` | no | Max 4000. |
| `aboutUs.sections[].title` | string; default `""` | no | Max 160. Up to 12 sections; strict items. |
| `aboutUs.sections[].body` | string | no | Required, max 8000. |
| `contactPhone` | string; default `""` | no | Max 64. |
| `homeIntro` | string; default `""` | no | Max 4000: hero text under the shop name. |
| `homeStory` | string; default `""` | no | Max 20000: brand story paragraphs (blank-line separated). |
| `homeTestimonials[].name` | string | no | Required, max 120. Up to 30 testimonials. |
| `homeTestimonials[].location` | string; default `""` | no | Max 120. |
| `homeTestimonials[].rating` | number; default `5` | no | 1 to 5. |
| `homeTestimonials[].date` | string; default `""` | no | Max 60. |
| `homeTestimonials[].text` | string | no | Required, max 2000. |
| `homeFaq[].q` | string | no | Required, max 300. Up to 30 items. |
| `homeFaq[].a` | string | no | Required, max 4000. |
| `brandKit` | string; default `""` | no | "", classic, editorial, warm, bold, performance or clinical. |
| `fontFamily` | string; default `""` | no | Max 80: body font. |
| `headingFontFamily` | string; default `""` | no | Max 80. |
| `trackOrder.enabled` | boolean; default `false` | no | Track my order link. |
| `trackOrder.label` | string; default `Track my order` | no | Max 120. |
| `trackOrder.url` | string; default `""` | no | Max 2048. |
| `trackOrder.embed` | string; default `""` | no | Max 2048. |
| `theme.header` | string; default `light` | no | light or dark. |
| `theme.footer` | string; default `dark` | no | light or dark. |
| `colors` | object; default `{}` | no | Map of colour tokens: key max 64 to value max 64 (for example { "primary": "#0f172a" }). |
| `announcement.enabled` | boolean; default `false` | no | Announcement bar. |
| `announcement.text` | string; default `""` | no | Max 300. |
| `announcement.highlight` | string; default `""` | no | Max 120. |
| `whyShop.enabled` | boolean; default `false` | no | Why shop block. |
| `whyShop.eyebrow` | string; default `""` | no | Max 120. |
| `whyShop.titleLine1` | string; default `""` | no | Max 200. |
| `whyShop.titleLine2` | string; default `""` | no | Max 200. |
| `whyShop.image` | string; default `""` | no | Max 2048. |
| `whyShop.bullets[].title` | string; default `""` | no | Max 200. Up to 3 bullets. |
| `whyShop.bullets[].text` | string; default `""` | no | Max 1000. |
| `keypoints.enabled` | boolean; default `false` | no | Key points block. |
| `keypoints.items[].icon` | string; default `""` | no | Max 40. Up to 4 items. |
| `keypoints.items[].title` | string; default `""` | no | Max 120. |
| `keypoints.items[].text` | string; default `""` | no | Max 400. |
| `support.enabled` | boolean; default `false` | no | Support block. |
| `support.image` | string; default `""` | no | Max 2048. |
| `support.line1` | string; default `""` | no | Max 400. |
| `support.answerTime` | string; default `""` | no | Max 60. |
| `tiktok.enabled` | boolean; default `false` | no | TikTok comments block. |
| `tiktok.heading` | string; default `""` | no | Max 200. |
| `tiktok.comments[].author` | string; default `""` | no | Max 120. Up to 20 comments. |
| `tiktok.comments[].text` | string | no | Required, max 1000. |
| `tiktok.comments[].date` | string; default `""` | no | Max 40. |
| `tiktok.comments[].likes` | string; default `""` | no | Max 20. |
| `tiktok.comments[].sex` | string; default `""` | no | Max 20. |
| `tiktok.comments[].avatar` | string; default `""` | no | Max 2048. |
| `tiktok.comments[].image` | string; default `""` | no | Max 2048. |
| `whySoCheap.enabled` | boolean; default `false` | no | Why so cheap block. |
| `whySoCheap.eyebrow` | string; default `""` | no | Max 120. |
| `whySoCheap.title` | string; default `""` | no | Max 200. |
| `whySoCheap.paragraphs[]` | string; default `[]` | no | Up to 10 strings of max 2000. |
| `whySoCheap.note` | string; default `""` | no | Max 1000. |
| `whySoCheap.mainImage` | string; default `""` | no | Max 2048. |
| `whySoCheap.accentImage` | string; default `""` | no | Max 2048. |
| `whyChooseUs.enabled` | boolean; default `false` | no | Why choose us block. |
| `finalCta.enabled` | boolean; default `false` | no | Final call to action. |
| `finalCta.title` | string; default `""` | no | Max 200. |
| `finalCta.text` | string; default `""` | no | Max 1000. |
| `finalCta.buttonLabel` | string; default `""` | no | Max 120. |
| `finalCta.footnote` | string; default `""` | no | Max 300. |
| `footerMedia.enabled` | boolean; default `false` | no | Footer media. |
| `footerMedia.image` | string; default `""` | no | Max 2048. |
| `footerMedia.video` | string; default `""` | no | Max 2048. |
| `footerMedia.poster` | string; default `""` | no | Max 2048. |
| `pressLogos[].enabled` | boolean; default `true` | no | Up to 20 logos. |
| `pressLogos[].src` | string | no | Required, max 2048. |
| `pressLogos[].alt` | string; default `""` | no | Max 200. |
| `languages[].code` | string | no | Required, max 8. Up to 12. |
| `languages[].label` | string; default `""` | no | Max 60. |
| `currencies[].code` | string | no | Required, max 8. Up to 12. |
| `currencies[].label` | string; default `""` | no | Max 60. |
| `locales[]` | string; default `[]` | no | Up to 11 of fr, it, es, pt, pl, de, nl, sv, da, no, fi (English is implicit). |
| `customCss` | string; default `""` | no | Max 200000: CSS served to every visitor. |
| `customJs` | string; default `""` | no | Max 200000: JavaScript served to every visitor. |

**Request body**

```json
{
  "contactPhone": "+1 555 010 2030",
  "homeIntro": "Explore our online collection.",
  "homeStory": "",
  "homeTestimonials": [],
  "homeFaq": [],
  "brandKit": "editorial",
  "fontFamily": "Inter",
  "headingFontFamily": "Fraunces",
  "trackOrder": {
    "enabled": true,
    "label": "Track my order",
    "url": "https://track.example.com",
    "embed": ""
  },
  "theme": {
    "header": "light",
    "footer": "dark"
  },
  "colors": {
    "primary": "#0f172a",
    "accent": "#f59e0b"
  },
  "announcement": {
    "enabled": false,
    "text": "",
    "highlight": ""
  },
  "whyShop": {
    "enabled": false,
    "eyebrow": "",
    "titleLine1": "",
    "titleLine2": "",
    "image": "",
    "bullets": []
  },
  "keypoints": {
    "enabled": false,
    "items": []
  },
  "support": {
    "enabled": false,
    "image": "",
    "line1": "",
    "answerTime": ""
  },
  "tiktok": {
    "enabled": false,
    "heading": "",
    "comments": []
  },
  "whySoCheap": {
    "enabled": false,
    "eyebrow": "",
    "title": "",
    "paragraphs": [],
    "note": "",
    "mainImage": "",
    "accentImage": ""
  },
  "whyChooseUs": {
    "enabled": false
  },
  "finalCta": {
    "enabled": false,
    "title": "",
    "text": "",
    "buttonLabel": "",
    "footnote": ""
  },
  "footerMedia": {
    "enabled": false,
    "image": "",
    "video": "",
    "poster": ""
  },
  "pressLogos": [],
  "languages": [
    {
      "code": "en",
      "label": "English"
    }
  ],
  "currencies": [
    {
      "code": "USD",
      "label": "US Dollar"
    }
  ],
  "customCss": "",
  "customJs": "",
  "company": {
    "name": "Example Trading Ltd",
    "address": "12 Example Street\nExample City"
  },
  "aboutUs": {
    "title": "About our store",
    "intro": "Explore our online collection and the details on each product page.",
    "sections": [
      {
        "title": "Product questions",
        "body": "Use the contact page for questions about a listing or an order."
      }
    ]
  },
  "locales": []
}
```

**Response**

```json
{
  "storefront": {
    "contactPhone": "+1 555 010 2030",
    "homeIntro": "Explore our online collection.",
    "homeStory": "",
    "homeTestimonials": [],
    "homeFaq": [],
    "brandKit": "editorial",
    "fontFamily": "Inter",
    "headingFontFamily": "Fraunces",
    "trackOrder": {
      "enabled": true,
      "label": "Track my order",
      "url": "https://track.example.com",
      "embed": ""
    },
    "theme": {
      "header": "light",
      "footer": "dark"
    },
    "colors": {
      "primary": "#0f172a",
      "accent": "#f59e0b"
    },
    "announcement": {
      "enabled": false,
      "text": "",
      "highlight": ""
    },
    "whyShop": {
      "enabled": false,
      "eyebrow": "",
      "titleLine1": "",
      "titleLine2": "",
      "image": "",
      "bullets": []
    },
    "keypoints": {
      "enabled": false,
      "items": []
    },
    "support": {
      "enabled": false,
      "image": "",
      "line1": "",
      "answerTime": ""
    },
    "tiktok": {
      "enabled": false,
      "heading": "",
      "comments": []
    },
    "whySoCheap": {
      "enabled": false,
      "eyebrow": "",
      "title": "",
      "paragraphs": [],
      "note": "",
      "mainImage": "",
      "accentImage": ""
    },
    "whyChooseUs": {
      "enabled": false
    },
    "finalCta": {
      "enabled": false,
      "title": "",
      "text": "",
      "buttonLabel": "",
      "footnote": ""
    },
    "footerMedia": {
      "enabled": false,
      "image": "",
      "video": "",
      "poster": ""
    },
    "pressLogos": [],
    "languages": [
      {
        "code": "en",
        "label": "English"
      }
    ],
    "currencies": [
      {
        "code": "USD",
        "label": "US Dollar"
      }
    ],
    "customCss": "",
    "customJs": "",
    "company": {
      "name": "Example Trading Ltd",
      "address": "12 Example Street\nExample City"
    },
    "aboutUs": {
      "title": "About our store",
      "intro": "Explore our online collection and the details on each product page.",
      "sections": [
        {
          "title": "Product questions",
          "body": "Use the contact page for questions about a listing or an order."
        }
      ]
    },
    "locales": [],
    "whopTracking": {
      "enabled": false
    },
    "handleRedirects": {
      "posture-corrector": "posture-corrector-pro"
    }
  },
  "cache": {
    "ok": true,
    "status": 200
  }
}
```

| response field | type | description |
|---|---|---|
| `storefront` | object | The jsonb as saved: your validated input with defaults filled PLUS the carried-over technical keys. |
| `cache` | object | Revalidation outcome { ok, status } or { ok: false, error, status }. |

**Errors**

- `400` {"error":"invalid storefront: unknown or malformed key (nothing was saved)","details":...}: an unknown key (strict), a string over its limit, a rating outside 1 to 5, a bad enum, a missing required item field
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `413` Request body over 2 MB
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- homeTestimonials[].rating is a number 1..5 (5 default), homeFaq items need both q and a, pressLogos items need src.
- customCss / customJs are served to every visitor of the storefront: treat this route as code deployment.
- This remains a configuration save with defaults, not a deep patch: GET first, edit the returned storefront object, and PUT the complete editable configuration. Existing defaulted fields may reset when omitted. New company/aboutUs top-level fields are optional without insertion defaults, so an older client that omits them preserves those stored values.
- Technical whopTracking, handleRedirects and i18n are preserved from the stored row and rejected in the editable payload. locales is editable: en is implicit; allowed codes are fr,it,es,pt,pl,de,nl,sv,da,no,fi.
- company and aboutUs (including aboutUs.sections items) reject unknown nested keys. Existing older nested blocks retain their previous validation behavior.
- Company facts render as escaped text below the footer logo on the native storefront themes, native checkout and /paid. An ownership sentence requires a non-empty company name; the registered-office clause requires an address. No identity is invented or copied from payment configuration. Company is excluded from both translation collection and overlay application.
- About us renders at /about-us and the compatibility /pages/about-us route, with supported locale prefixes. Custom intro or sections supersede homeIntro/homeStory; when no authored About content exists the page reuses those home fields, then neutral localized copy. Blank paragraphs and body-less sections do not render. About text participates in the existing storefront i18n overlay.
- Native storefront footer links point to the About us page. Saving this configuration does not publish or modify an external Shopify or Medusa storefront theme, its About page, or its footer. Their native Kontrol checkout and confirmation can still render configured company identity.
- Example company/address values are illustrative only. Save only verified merchant-supplied legal facts; leave unknown facts empty.

##### `POST /v1/checkouts/:shopId/storefront/generate`

**Scope** `checkouts.write` - **Generate homepage copy with AI**

Generate homepage copy with the store owner account's Anthropic integration (model from its configuration, default claude-sonnet-4-6, max 3000 tokens, 20 s timeout) from the shop name, domain, up to 30 active listed product titles and up to 40 published review excerpts, then write homeIntro, homeStory, homeTestimonials (6) and homeFaq (6) into the site content (only the fields that came back non-empty) and refresh the caches. Returns the fields that changed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "ok": true,
  "fields": [
    "homeIntro",
    "homeStory",
    "homeTestimonials",
    "homeFaq"
  ]
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true on 200. |
| `fields[]` | string[] | Subset of homeIntro \| homeStory \| homeTestimonials \| homeFaq whose value changed. Empty = the model returned nothing usable (still 200). |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).
- `502` {"ok":false,"error":"Veuillez configurer Anthropic"} (no Anthropic integration on the account); {"ok":false,"error":"shop_not_found"}; {"ok":false,"error":"generation_failed: <reason>"} (provider error, timeout, no or invalid JSON)

**Gotchas**

- OVERWRITES the existing homepage copy without confirmation; take a GET .../storefront snapshot first if you may want to roll back.
- Takes several seconds (one LLM completion, max_tokens 3000); do not retry aggressively.
- Testimonials are adapted from real published reviews when the store has some; otherwise invented - review them.
- :shopId is not format-validated by the route; a non-UUID value is passed straight into the checkout-database filter and surfaces as a 500, not a 404.
- The provider is called with the account's own Anthropic integration (Integrations), billed to that account. Configure it before calling.
- The cache refresh is best effort: the storefront may serve the previous copy for a couple of minutes; the write itself is committed.

##### `POST /v1/checkouts/:shopId/theme-check`

**Scope** `checkouts.write` - **Check that the store theme is wired to the checkout**

Shopify store: checks three facts, each with its own fix: the checkout snippet is installed, the button script is installed, and the native Shopify checkout button is gone. With a stored token and admin URL the theme files are read through the Shopify Theme API (read_themes, source theme-api); otherwise, or when that fails, the public cart page is fetched (source cart-page). Medusa store: checks the saved storefront and backend instead. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `storefront` | string | no | Shopify only: the storefront host (or URL, scheme and path stripped) whose cart page to check. Default: the checkout domain minus its pay. prefix. |

**Request body**

```json
{
 "storefront": "shop.example.com"
}
```

**Response**

```json
{
  "storefront": "https://shop.example.com/cart",
  "ok": false,
  "checks": [
    {
      "key": "snippet",
      "label": "Checkout button rendered",
      "status": "ok",
      "detail": ".fbm-cart-checkout-trigger found on the cart page"
    },
    {
      "key": "script",
      "label": "Button script reachable",
      "status": "ok",
      "detail": "cart-checkout-btn.js answers 200"
    },
    {
      "key": "native",
      "label": "Shopify checkout removed",
      "status": "failed",
      "detail": "the native checkout button or content_for_additional_checkout_buttons is still rendered - it short-circuits your tunnel"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `storefront` | string | What was checked (the cart page URL, or the theme API source). |
| `source` | string | theme-api or cart-page. |
| `ok` | boolean | No check failed (cart-page: every check ok). |
| `checks[]` | object[] | { key (snippet, script, native), label, status (ok, failed, unknown), detail }. |

**Errors**

- `400` {"error":"Not a Shopify store - there is no theme to check"} (an in-house store)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- storefront is optional: it defaults to the shop's tunnel domain minus the pay. prefix, which is the storefront for every store branched the standard way.
- A password-protected or unpublished store yields status 'unknown' on every line, never a false red.
- Outbound: this reaches the merchant's public storefront over HTTPS, with a 12 s timeout and the user-agent cocoapi-setup-check.
- A snippet missing from the theme files but proven on the public page (script or trigger class) counts as ok: it may come from a theme-editor block or an app block.

##### `GET /v1/checkouts/health`

**Scope** `checkouts.read` - **Check the Ecommerce integration health**

Read-only readiness of the store and checkout integration: whether the checkout database, the checkout encryption key, cache revalidation and the hosting provider API are configured, and whether the Medusa integration is enabled. The platform operator additionally receives the hosting service ID and the platform settings row; every account caller receives settings: null.

*No parameters.*

**Response**

```json
{
  "medusaEnabled": false,
  "configured": {
    "checkoutDb": true,
    "encryptionKey": true,
    "revalidate": true,
    "render": true
  },
  "settings": null
}
```

| response field | type | description |
|---|---|---|
| `medusaEnabled` | boolean | Whether the Medusa integration is enabled on this platform (stores with cms medusa can be created). |
| `configured.checkoutDb` | boolean | The checkout database is configured. False means the store routes cannot work. |
| `configured.encryptionKey` | boolean | The checkout encryption key is configured. False means stored store secrets cannot be decrypted and keys cannot be stored on payment routes (PUT /v1/checkouts/:shopId/routing answers 503). |
| `configured.revalidate` | boolean | Writes can ask the storefront to refresh its cache. |
| `configured.render` | boolean | The hosting provider API is configured (custom-domain routes). |
| `configured.renderServiceId` | string | Hosting service ID. Present only for the platform operator; absent for every account caller. |
| `settings` | object\|null | Platform settings row for the platform operator; always null for account callers. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- configured.* are booleans about the platform, not about the caller's account; they do not say that a given store is ready. Use GET /v1/checkouts/:shopId/overview for one store.

##### `GET /v1/checkouts/providers`

**Scope** `checkouts.read` - **List the legacy payment providers usable for a new store**

Lists the legacy checkout payment providers (provider rows carrying one of the account's keys) that may be passed as payment_provider_id to POST /v1/checkouts. New stores do not need one: a store is owned and charged through its payment route.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
      "name": "Kontrol - Example Store",
      "account": "ops@example.com",
      "key": "example-store"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].id` | uuid | Provider ID, the value for payment_provider_id on POST /v1/checkouts. |
| `rows[].name` | string | Provider label. |
| `rows[].account` | string\|null | Owning account (the owner of the key the provider carries). |
| `rows[].key` | string\|null | Name of that key. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- The provider-to-account map is cached for up to 10 minutes: a key created moments ago may not appear yet.
- Empty when the platform runs without the legacy checkout database or without the checkout encryption key.

##### `GET /v1/checkouts/shopify/theme-files`

**Scope** `checkouts.read` - **The two theme files to install in Shopify**

The two Shopify theme files to install (cart-checkout-btn.liquid and cart-checkout-btn.js), each with where it goes in the Shopify theme editor and the mistake it invites. Static.

*No parameters.*

**Response**

```json
{
  "files": [
    {
      "name": "cart-checkout-btn.liquid",
      "where": "Snippets",
      "note": "Name it exactly cart-checkout-btn, with no .liquid",
      "body": "<style>..."
    },
    {
      "name": "cart-checkout-btn.js",
      "where": "Assets",
      "note": "Assets, not Snippets - a 404 here is a button that does nothing",
      "body": "(function(){..."
    }
  ]
}
```

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The files are static and read from disk once per process.
- cart-checkout-btn.js builds https://pay.<storefront>/checkout/<token> with the pay. prefix hardcoded, which is why the tunnel host is derived and not typed when a Shopify store is created.

##### `GET /v1/home-ai/jobs`

**Scope** `reports.read` - **List homepage generations**

Lists the last 20 homepage copy generations of one store started by the same principal and scope as the caller, newest first, with their status and the names of the fields each proposal fills. Proposal contents are not included: read one generation with GET /v1/home-ai/jobs/:id. Works while background workers are paused.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string (uuid) | **yes** | Store id (GET /v1/checkouts). The store must be routed to this account. |

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000601",
      "shop_id": "00000000-0000-4000-8000-000000000603",
      "request_id": "00000000-0000-4000-8000-000000000602",
      "status": "ready",
      "error": null,
      "cancel_requested": false,
      "created_at": "2026-11-24T10:00:00.000Z",
      "updated_at": "2026-11-24T10:01:10.000Z",
      "finished_at": null,
      "applied_at": null,
      "cache_refreshed": null,
      "fields": [
        "homeIntro",
        "homeStory",
        "homeTestimonials",
        "homeFaq"
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | At most 20 generations, newest first: id, request_id, shop_id, status (queued, generating, ready, applied, failed, uncertain, cancelled or conflict), cancel_requested, error, created_at, updated_at, finished_at, applied_at, cache_refreshed, fields. |
| `error` | string | Only on the degraded answer described in the gotchas. |

**Errors**

- `400` {"error":"Invalid identifier"}: shopId missing or not a UUID (checked once the generations table exists).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Account access or permissions changed"}: the caller's role, account or access changed since the generation started, or the key is inactive.
- `403` {"error":"Store account is unavailable"}: the account that owns the store is banned or not a main account; {"error":"Store ownership changed"}.
- `404` {"error":"Store not found"}: unknown store, a store without checkout routing, or a store routed to another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- Before the generations table exists the answer is 200 {"jobs": []}, without validating shopId.
- A 200 can carry {"jobs": [], "error": "Home AI generation is temporarily unavailable"}: a degraded answer kept for a dropped legacy table. It is not expected any more, but treat an error key on a 200 as unavailable, not as no generations.
- Only the generations of the same principal and scope are listed: another member of the account, or another key, sees its own.
- Answers carry cache-control: no-store.

##### `POST /v1/home-ai/jobs`

**Scope** `reports.write` - **Start a homepage copy generation**

Queues one AI generation of homepage copy (intro, story, testimonials, FAQ) for a store and answers 202 once it is saved. The proposal is not applied: review it with GET /v1/home-ai/jobs/:id and apply it with POST /v1/home-ai/jobs/:id/apply.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string (uuid) | **yes** | Store id (GET /v1/checkouts). The store must be routed to this account. |
| `requestId` | string (uuid) | **yes** | Your idempotency id. The same requestId for the same store and principal returns the saved generation (202) instead of a new one. |

**Request body**

```json
{
  "shopId": "00000000-0000-4000-8000-000000000603",
  "requestId": "00000000-0000-4000-8000-000000000602"
}
```

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000601",
    "shop_id": "00000000-0000-4000-8000-000000000603",
    "request_id": "00000000-0000-4000-8000-000000000602",
    "status": "queued",
    "error": null,
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "applied_at": null,
    "cache_refreshed": null,
    "cache_attempts": 0,
    "cache_next_attempt_at": "2026-11-24T10:00:00.000Z",
    "fields": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, shop_id, request_id, status (queued, generating, ready, applied, failed, uncertain, cancelled or conflict), error, cancel_requested, created_at, updated_at, finished_at, applied_at, cache_refreshed, cache_attempts, cache_next_attempt_at, fields (names of the proposal fields). |

**Errors**

- `400` {"error":"Invalid generation request"}: shopId or requestId missing or not a UUID, or another key in the body.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Account access or permissions changed"}: the caller's role, account or access changed since the generation started, or the key is inactive.
- `403` {"error":"Store account is unavailable"}: the account that owns the store is banned or not a main account; {"error":"Store ownership changed"}.
- `404` {"error":"Store not found"}: unknown store, a store without checkout routing, or a store routed to another account.
- `409` {"error":"Request ID already belongs to another generation"}: same requestId with another store or principal; {"error":"An existing generation must finish or be discarded first","jobId":"<uuid>"}: the account already has a queued or generating one, or the store has a queued, generating or ready one.
- `422` {"error":"Configure an active Anthropic integration before generating copy"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Background homepage generation is unavailable for this checkout database"}: workers off or checkout data not local.
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- Generation runs in a background worker with the account's Anthropic integration (GET /v1/integrations). A provider timeout or crash ends as uncertain and is never retried: check the provider's usage before starting another one.
- Queued and ready proposals expire (cancelled) after seven days; finished generations are deleted after 30 days.
- Only the principal and scope that started a generation see it: another member of the account, or another key, gets 404.
- Answers carry cache-control: no-store.

##### `GET /v1/home-ai/jobs/:id`

**Scope** `reports.read` - **Read a homepage proposal**

Reads one generation with its validated proposal (homeIntro, homeStory, homeTestimonials, homeFaq). Never returns the provider credentials or the raw provider output.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Generation id returned by POST /v1/home-ai/jobs or the list. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000601",
    "shop_id": "00000000-0000-4000-8000-000000000603",
    "request_id": "00000000-0000-4000-8000-000000000602",
    "status": "ready",
    "error": null,
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:01:10.000Z",
    "finished_at": null,
    "applied_at": null,
    "cache_refreshed": null,
    "cache_attempts": 0,
    "cache_next_attempt_at": "2026-11-24T10:00:00.000Z",
    "fields": [
      "homeIntro",
      "homeStory",
      "homeTestimonials",
      "homeFaq"
    ],
    "proposal": {
      "homeIntro": "Handmade ceramics for everyday tables.",
      "homeStory": "Demo Store started in a small studio...",
      "homeTestimonials": [
        {
          "name": "Sam Example",
          "location": "Austin, TX",
          "rating": 5,
          "date": "October 2026",
          "text": "Lovely mugs, fast shipping."
        }
      ],
      "homeFaq": [
        {
          "q": "Do you ship abroad?",
          "a": "Yes, to most countries."
        }
      ]
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, shop_id, request_id, status (queued, generating, ready, applied, failed, uncertain, cancelled or conflict), error, cancel_requested, created_at, updated_at, finished_at, applied_at, cache_refreshed, cache_attempts, cache_next_attempt_at, fields (names of the proposal fields). |
| `job.proposal` | object \| null | homeIntro (up to 4000 characters), homeStory (up to 20000), homeTestimonials (up to 6 of {name, location, rating 1 to 5, date, text}), homeFaq (up to 6 of {q, a}); null until ready. |

**Errors**

- `400` {"error":"Invalid identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Account access or permissions changed"}: the caller's role, account or access changed since the generation started, or the key is inactive.
- `403` {"error":"Store account is unavailable"}: the account that owns the store is banned or not a main account; {"error":"Store ownership changed"}.
- `404` {"error":"Store not found"}: unknown store, a store without checkout routing, or a store routed to another account.
- `404` {"error":"Generation not found"}: unknown id, or a generation started by another principal or scope.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- Generation runs in a background worker with the account's Anthropic integration (GET /v1/integrations). A provider timeout or crash ends as uncertain and is never retried: check the provider's usage before starting another one.
- Queued and ready proposals expire (cancelled) after seven days; finished generations are deleted after 30 days.
- Only the principal and scope that started a generation see it: another member of the account, or another key, gets 404.
- Answers carry cache-control: no-store.

##### `POST /v1/home-ai/jobs/:id/apply`

**Scope** `reports.write` - **Apply a homepage proposal**

Merges a ready proposal into the store's storefront settings and marks the generation applied, in one transaction. If the storefront changed since the generation started, nothing is written and the generation becomes conflict (200). Applying an applied generation returns it unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Generation id returned by POST /v1/home-ai/jobs or the list. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000601",
    "shop_id": "00000000-0000-4000-8000-000000000603",
    "request_id": "00000000-0000-4000-8000-000000000602",
    "status": "applied",
    "error": null,
    "cancel_requested": false,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:05:00.000Z",
    "finished_at": "2026-11-24T10:05:00.000Z",
    "applied_at": "2026-11-24T10:05:00.000Z",
    "cache_refreshed": false,
    "cache_attempts": 0,
    "cache_next_attempt_at": "2026-11-24T10:00:00.000Z",
    "fields": [
      "homeIntro",
      "homeStory",
      "homeTestimonials",
      "homeFaq"
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, shop_id, request_id, status (queued, generating, ready, applied, failed, uncertain, cancelled or conflict), error, cancel_requested, created_at, updated_at, finished_at, applied_at, cache_refreshed, cache_attempts, cache_next_attempt_at, fields (names of the proposal fields). |

**Errors**

- `400` {"error":"Invalid identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Account access or permissions changed"}: the caller's role, account or access changed since the generation started, or the key is inactive.
- `403` {"error":"Store account is unavailable"}: the account that owns the store is banned or not a main account; {"error":"Store ownership changed"}.
- `404` {"error":"Store not found"}: unknown store, a store without checkout routing, or a store routed to another account.
- `404` {"error":"Generation not found"}: unknown id, or a generation started by another principal or scope.
- `409` {"error":"This proposal is not available to apply"}: status is not ready, or a cancel was requested; {"error":"Anthropic configuration changed; generate a new proposal"}.
- `422` {"error":"Configure an active Anthropic integration before generating copy"}: the integration was removed.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Applying generated copy is disabled"}: checkout data is not local.
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- The answer carries no proposal (read it before applying). A conflict answer has status conflict and error "The storefront changed. Your edits were preserved; generate a new proposal."
- cache_refreshed false right after applying: the worker refreshes the storefront cache afterwards (true when done).
- Generation runs in a background worker with the account's Anthropic integration (GET /v1/integrations). A provider timeout or crash ends as uncertain and is never retried: check the provider's usage before starting another one.
- Queued and ready proposals expire (cancelled) after seven days; finished generations are deleted after 30 days.
- Only the principal and scope that started a generation see it: another member of the account, or another key, gets 404.
- Answers carry cache-control: no-store.

##### `POST /v1/home-ai/jobs/:id/cancel`

**Scope** `reports.write` - **Cancel a homepage generation**

Cancels a generation. A queued or ready one becomes cancelled at once; a generating one gets cancel_requested true and the worker stops it (the provider request may already be billed, nothing is applied). Any other status is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Generation id returned by POST /v1/home-ai/jobs or the list. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000601",
    "shop_id": "00000000-0000-4000-8000-000000000603",
    "request_id": "00000000-0000-4000-8000-000000000602",
    "status": "cancelled",
    "error": null,
    "cancel_requested": true,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:30.000Z",
    "finished_at": "2026-11-24T10:00:30.000Z",
    "applied_at": null,
    "cache_refreshed": null,
    "cache_attempts": 0,
    "cache_next_attempt_at": "2026-11-24T10:00:00.000Z",
    "fields": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | id, shop_id, request_id, status (queued, generating, ready, applied, failed, uncertain, cancelled or conflict), error, cancel_requested, created_at, updated_at, finished_at, applied_at, cache_refreshed, cache_attempts, cache_next_attempt_at, fields (names of the proposal fields). |

**Errors**

- `400` {"error":"Invalid identifier"}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Account access or permissions changed"}: the caller's role, account or access changed since the generation started, or the key is inactive.
- `403` {"error":"Store account is unavailable"}: the account that owns the store is banned or not a main account; {"error":"Store ownership changed"}.
- `404` {"error":"Store not found"}: unknown store, a store without checkout routing, or a store routed to another account.
- `404` {"error":"Generation not found"}: unknown id, or a generation started by another principal or scope.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- No body is read. Cancelling twice is harmless.
- Generation runs in a background worker with the account's Anthropic integration (GET /v1/integrations). A provider timeout or crash ends as uncertain and is never retried: check the provider's usage before starting another one.
- Queued and ready proposals expire (cancelled) after seven days; finished generations are deleted after 30 days.
- Only the principal and scope that started a generation see it: another member of the account, or another key, gets 404.
- Answers carry cache-control: no-store.

##### `GET /v1/home-ai/jobs/capabilities`

**Scope** `reports.read` - **Read homepage generation availability**

Says whether AI homepage copy generation can run: background workers on, checkout data in the same database, and the generations table present.

*No parameters.*

**Response**

```json
{
  "enabled": true,
  "localOnly": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | Generation available. |
| `localOnly` | boolean | Always true: generation needs the checkout data in the same database. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure (a lock wait included).
- `503` {"error":"Required storage for Home AI jobs is unavailable. Complete the current database migrations."}: workers and local checkout data are on but the table is missing.
- `503` {"error":"Operation control deadline exceeded; reconnect to check its status"}: the 15-second control budget ran out; read the generation again before retrying.
- `504` A database statement exceeded its 5-second limit.

**Gotchas**

- enabled false means POST /v1/home-ai/jobs answers 503. localOnly is always true.
- Answers carry cache-control: no-store.

#### Products

The product catalogue: products of a store or of the account, variants, media, pages, reviews, paging, exports and the Shopify / Medusa catalogue imports.

- CSV: `POST /v1/checkouts/products/page-v1/export` (or the per-store one) returns the file. PDF: built in the browser from the rows streamed by `POST /v1/checkouts/products/export-pdf-v2`.
- Product editor, Stats total: sum of the rows of `GET /v1/checkouts/:shopId/products-stats` for that product, computed in the browser.

##### `POST /v1/checkouts/:shopId/medusa/import`

**Scope** `checkouts.write` - **Queue Medusa catalog import**

Queue a durable catalogue import of this Medusa store into Kontrol's database. Answers 202 with the job; repeating the same requestId returns the same job.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 400 {"error":"A stable requestId and valid store selection are required"}, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key of the import. Strict body: requestId only (the store comes from the path). |

**Request body**

```json
{
 "requestId": "33333333-3333-4333-8333-333333333333"
}
```

**Response** `202`

```json
{
 "jobId": "44444444-4444-4444-8444-444444444444",
 "job": {
  "id": "44444444-4444-4444-8444-444444444444",
  "status": "queued",
  "phase": "queued",
  "request_id": "33333333-3333-4333-8333-333333333333"
 },
 "queued": 0,
 "errors": []
}
```

**Errors**

- `400` {"error":"A stable requestId and valid store selection are required"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store unavailable in the caller's account
- `409` {"error":"Background Medusa imports are disabled"}; {"error":"This request ID belongs to a different selection"}; {"error":"An import is already running for this account"} (with jobId)
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Failed snapshots do not retire existing catalog rows. Restart retries start from the first page.

##### `GET /v1/checkouts/:shopId/medusa/import/status`

**Scope** `checkouts.read` - **Read Medusa import status**

Import status of the store. For the admin role: the latest durable import target { status, productsUpserted, variantsUpserted, mediaUpserted, listed, pagesFetched, updatedAt, jobId, errors[] }; otherwise (or when none exists) the legacy per-store status { status (idle when never imported), progress counters, updatedAt }.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 400 {"error":"A value has an invalid format."} for an administrator or a key (the saved import status is read from the API database first); for another role it answers 500, not 404. |

**Response**

```json
{
  "status": "queued"
}
```

**Errors**

- `400` {"error":"Not a Medusa store"}
- `400` {"error":"A value has an invalid format."}: shopId is not a UUID (administrator or key).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Medusa integration is not enabled for this account"}; {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure).

##### `GET /v1/checkouts/:shopId/products`

**Scope** `checkouts.read` - **List a store's products (unpaged)**

Lists one store's products in one unpaged answer; POST /v1/checkouts/:shopId/products/page-v1/query is the paged, filtered and sorted query of the same catalogue. List the products owned by the store plus the ones listed on it, with variant and media counts, lowest active price and first image, newest first. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "rows": [
    {
      "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "Posture Corrector Pro",
      "handle": "posture-corrector-pro",
      "status": "active",
      "currency": "USD",
      "updated_at": "2026-09-17T12:30:00.000Z",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "linked": true,
      "link_active": true,
      "variants": 3,
      "media": 5,
      "min_price_cents": 3990,
      "image": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg"
    },
    {
      "id": "8e1b3d5f-7a9c-4b2d-8e0f-1a3c5e7b9d21",
      "title": "Lumbar Cushion",
      "handle": "lumbar-cushion",
      "status": "draft",
      "currency": "USD",
      "updated_at": "2026-09-10T10:00:00.000Z",
      "shop_id": "2f4e6a8c-0b1d-4e3f-9a5c-7e9b1d3f5a70",
      "linked": true,
      "link_active": false,
      "variants": 1,
      "media": 0,
      "min_price_cents": 0,
      "image": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].shop_id` | uuid\|null | Owning store; differs from :shopId for linked products. |
| `rows[].linked / link_active` | boolean | A shop_products link to :shopId exists / is active (= listed on this store). An owned product created through this API is linked with is_active false until PUT .../availability. |
| `rows[].min_price_cents` | integer\|null | Lowest price_cents among active variants (fallback first variant); null with zero variants. |
| `rows[].variants / media` | integer | Row counts (inactive variants included). |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- No pagination. Sorted by updated_at desc.
- 'listed' on the storefront = status active AND link_active true - a product can be active yet invisible on the store.

##### `POST /v1/checkouts/:shopId/products`

**Scope** `checkouts.write` - **Create a complete product atomically**

Creates a product and store listing together with its option/variant matrix, pricing, gallery URLs, specifications, quantity tiers, bundle components, page sections and page configuration in one transaction. Minimal creation defaults to draft/USD and an inactive listing; unlike the old title-only endpoint it now creates a default variant. Returns the raw ProductRow with id, HTTP 201; GET the product detail to read related arrays. Does not activate the store, charge cards, generate AI content or fetch media URLs.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `title` | string; default `New product` | no | Max 300, trimmed; empty or absent = New product. |
| `currency` | string; default `USD` | no | Exactly three ASCII letters, upper-cased. |
| `handle` | string | no | 1 to 80; slugified (lower-case, accents stripped, [a-z0-9-], at most 60). Made unique in the owning store with -2, -3 suffixes; read the stored handle from the answer. |
| `status` | string | no | draft, active or archived. Only active products are sellable, and only where listed. |
| `subtitle` | string\|null | no | Max 300. |
| `vendor` | string\|null | no | Max 120. |
| `product_type` | string\|null | no | Max 120. |
| `tags` | string[] | no | Up to 50 tags of at most 60 characters. |
| `description` | string | no | Max 100000 characters, HTML allowed. |
| `seo_title` | string\|null | no | Max 200. |
| `seo_description` | string\|null | no | Max 500. |
| `gift_banner_text` | string\|null | no | Max 300. |
| `scarcity_text` | string\|null | no | Max 300. |
| `social_proof_text` | string\|null | no | Max 300. |
| `rating_value` | number\|null | no | 0 to 5. Recomputed (and capped at 4.7) by the next review change. |
| `rating_count` | integer | no | >= 0. Recomputed by the next review change. |
| `subscription_product_id` | uuid\|null | no | An active, not deleted subscription product of the store owner account; null removes the link (422 otherwise). The price stays on the variants. |
| `price_cents` | integer; default `0` | no | 0 to 2147483647: default price of the generated variants. |
| `compare_at_price_cents` | integer\|null | no | 0 to 2147483647; null = none. |
| `sku` | string | no | Max 120: default SKU. |
| `inventory_qty` | integer\|null | no | Default inventory; null = untracked. |
| `options` | object[] | no | Up to 2 options; omitted or [] creates one default variant. Values must be unique per option. |
| `options[].name` | string | **yes** | Option name, 1 to 60 characters. At most 2 options. |
| `options[].display_type` | string; default `button` | no | button or image-swatch. |
| `options[].values[].value` | string | **yes** | 1 to 80 characters; 1 to 50 values per option, unique within the option. The options together may imply at most 200 variants. |
| `options[].values[].swatch_image_url` | string\|null | no | Max 2048: swatch image (image-swatch). |
| `options[].values[].swatch_hex` | string\|null | no | Max 16: swatch colour. |
| `variants` | object[] | no | Up to 200 explicit variant rows (no id): each combination valid against options, in order, and unique. Strict items. |
| `variants[].option_values` | string[]; default `[]` | no | The option value texts of this row, one per declared option, in order (max 2, each max 80). |
| `variants[].price_cents` | integer | **yes** | >= 0, in cents of the product currency. |
| `variants[].sku` | string; default `""` | no | Max 120. |
| `variants[].compare_at_price_cents` | integer\|null; default `null` | no | >= 0; null = no compare-at price. |
| `variants[].cost_cents` | integer\|null | no | >= 0. Absent keeps the stored value. |
| `variants[].weight_grams` | integer\|null | no | >= 0. Absent keeps the stored value. |
| `variants[].barcode` | string\|null | no | Max 80. Absent keeps the stored value. |
| `variants[].inventory_qty` | integer\|null; default `null` | no | null = untracked. |
| `variants[].is_active` | boolean; default `true` | no | Sellable variant. |
| `variants[].image_url` | string; default `""` | no | Max 2048. |
| `media` | object[] | no | Up to 100 gallery items, stored as given (no download or rehost). Strict items. |
| `media[].url` | string | **yes** | HTTP(S) URL, max 2048. |
| `media[].alt` | string\|null | no | Max 300. |
| `media[].kind` | string; default `image` | no | image or video. |
| `tiers` | object[] | no | Quantity tiers (same schema as PUT /v1/checkouts/:shopId/products/:pid/tiers). |
| `tiers[].min_quantity` | integer | **yes** | >= 1; unique across the tiers (Each quantity threshold must be unique). At most 50 tiers. |
| `tiers[].extra_off_cents` | integer; default `0` | no | >= 0: amount off per unit, in cents. |
| `tiers[].discount_pct` | number; default `0` | no | 0 to 100: percent off. |
| `tiers[].label` | string\|null; default `null` | no | Max 120. |
| `tiers[].badge` | string\|null; default `null` | no | Max 60. |
| `tiers[].unit_price_cents` | integer\|null | no | Legacy fixed unit price, >= 0. Absent keeps the stored value of that min_quantity; null clears it; a number sets it. |
| `bundle` | object[] | no | Bundle components; each variant must belong to or be listed on this store, else the whole create is refused. |
| `bundle[].component_variant_id` | uuid | **yes** | Variant included in the bundle. At most 50 items. |
| `bundle[].quantity` | integer; default `1` | no | >= 1. |
| `bundle[].is_gift` | boolean; default `false` | no | Free item. |
| `bundle[].price_override_cents` | integer\|null; default `null` | no | >= 0; null = the component price. |
| `specs` | object[] | no | Specification rows. |
| `specs[].label` | string | **yes** | 1 to 120. At most 100 rows. |
| `specs[].value` | string | **yes** | 1 to 1000. |
| `sections` | object[] | no | Typed page sections; omitted = the default section set. |
| `sections[].id` | string | no | Max 80. Kept when present and not starting with new-; otherwise a sec_<8 hex>_<n> id is generated. |
| `sections[].type` | string | **yes** | info_tabs, logos_carousel, ugc_videos, rich_section, reviews, faq or customization. At most 30 sections. |
| `sections[].enabled` | boolean; default `true` | no | Rendered or hidden. |
| `sections[].position` | integer | no | >= 0; sections are sorted by it and renumbered 0..n-1. Default: the array index. |
| `sections[].props` | object; default `{}` | no | Free-form per type, normalised (strings trimmed, empty rows dropped, other keys kept). |
| `sections[].props (info_tabs)` | object | no | { tabs: up to 12 of { key, title (required), body (HTML) } }. |
| `sections[].props (logos_carousel)` | object | no | { heading }. |
| `sections[].props (ugc_videos)` | object | no | { heading, videos: up to 50 of { url (required), poster } }. |
| `sections[].props (rich_section)` | object | no | { layout: image_text (default), feature_grid or how_to_steps; eyebrow, title, mediaUrl; image_text adds side (left by default) and body (HTML); how_to_steps adds steps: up to 50 of { imageUrl, title (required), text }; feature_grid adds items: up to 50 of { iconUrl, title (required), text } }. |
| `sections[].props (reviews)` | object | no | { heading, moreLabel }. |
| `sections[].props (faq)` | object | no | { heading, items: up to 30 of { q (required), a } }. |
| `sections[].props (customization)` | object | no | { heading, note, fields: up to 12 of { label (required), key (derived from the label when absent, made unique), type: text, textarea, number, select, radio or checkbox (text), options (array or comma-separated string, up to 30), placeholder, helpText, max (positive integer, 0 = none), required (true, "true" or "on") } }. |
| `page_config` | object | no | Product page configuration (same schema and defaults as PUT /v1/checkouts/:shopId/products/:pid/page-config). |
| `page_config.subBar` | object; default `{}` | no | Strict top level: an unknown key is a 400. Each block defaults to its defaults when absent. |
| `page_config.subBar.enabled` | boolean; default `false` | no | Rating bar under the title. |
| `page_config.subBar.label` | string; default `""` | no | Max 200. |
| `page_config.subBar.text` | string; default `""` | no | Max 500 (image and imageAlt are forced server-side). |
| `page_config.banner.enabled` | boolean; default `false` | no | Top banner. |
| `page_config.banner.text` | string; default `""` | no | Max 300. |
| `page_config.banner.highlight` | string; default `""` | no | Max 120. |
| `page_config.freeGift.enabled` | boolean; default `false` | no | Free gift block. |
| `page_config.freeGift.subtitle` | string; default `""` | no | Max 300. |
| `page_config.freeGift.image` | string; default `""` | no | Max 2048. |
| `page_config.priceBlock.showCompareAt` | boolean; default `true` | no | Show the compare-at price. |
| `page_config.priceBlock.showSaveTag` | boolean; default `true` | no | Show the save tag. |
| `page_config.bundles.title` | string; default `Bundle & Save` | no | Max 120. |
| `page_config.bundles.countdown.enabled` | boolean; default `false` | no | Countdown on the bundles. |
| `page_config.bundles.countdown.minutes` | integer; default `0` | no | >= 0. |
| `page_config.bundles.stickPrices` | boolean; default `true` | no | Strike-through prices on bundles. |
| `page_config.salesPoints.enabled` | boolean; default `false` | no | Sales points list. |
| `page_config.salesPoints.items[].bold` | string | no | Required, max 200. Up to 20 items. |
| `page_config.salesPoints.items[].text` | string; default `""` | no | Max 500. |
| `page_config.buyButton.label` | string; default `ORDER NOW` | no | Max 80. |
| `page_config.buyButton.showPrice` | boolean; default `true` | no | Price inside the button. |
| `page_config.trustBadges.enabled` | boolean; default `false` | no | Trust badges. |
| `page_config.trustBadges.items[].label` | string | no | Required, max 120. Up to 12 items. |
| `page_config.trustBadges.items[].icon` | string; default `""` | no | Max 2048. |
| `page_config.stickyBar.enabled` | boolean; default `false` | no | Sticky order bar. |
| `page_config.stickyBar.label` | string; default `Order Now` | no | Max 80. |
| `page_config.cartDrawer.title` | string; default `Added to cart` | no | Max 120. |
| `page_config.cartDrawer.checkoutLabel` | string; default `Continue to Checkout` | no | Max 120. |
| `page_config.cartDrawer.continueLabel` | string; default `Continue shopping` | no | Max 120. |
| `page_config.cartDrawer.freeShippingBar.enabled` | boolean; default `false` | no | Free shipping bar. |
| `page_config.cartDrawer.freeShippingBar.text` | string; default `""` | no | Max 300. |
| `page_config.cartDrawer.giftBadge.enabled` | boolean; default `false` | no | Gift badge. |
| `page_config.overstock.enabled` | boolean; default `false` | no | Stock counter. |
| `page_config.overstock.unitsLeft` | integer; default `0` | no | >= 0. |
| `page_config.overstock.unitsTotal` | integer; default `0` | no | >= 0. |
| `page_config.lightbox.enabled` | boolean; default `false` | no | Image lightbox. |
| `page_config.preOrder.enabled` | boolean; default `false` | no | Pre-order mode. |
| `is_active` | boolean; default `false` | no | Initial listing on this store. |

**Request body**

```json
{
  "title": "Demo mug",
  "description": "A ceramic mug.",
  "currency": "USD",
  "status": "draft",
  "is_active": false,
  "price_cents": 2499,
  "options": [
    {
      "name": "Color",
      "values": [
        {
          "value": "Blue"
        },
        {
          "value": "White"
        }
      ]
    }
  ],
  "variants": [
    {
      "option_values": [
        "Blue"
      ],
      "price_cents": 2499,
      "sku": "MUG-BLUE"
    },
    {
      "option_values": [
        "White"
      ],
      "price_cents": 2599,
      "sku": "MUG-WHITE"
    }
  ],
  "specs": [
    {
      "label": "Material",
      "value": "Ceramic"
    }
  ],
  "sections": [
    {
      "type": "faq",
      "props": {
        "heading": "Questions",
        "items": [
          {
            "q": "Material?",
            "a": "Ceramic."
          }
        ]
      }
    }
  ],
  "page_config": {
    "buyButton": {
      "label": "Add to cart",
      "showPrice": true
    }
  }
}
```

**Response** `201`

```json
{
  "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
  "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "owner_user_id": null,
  "title": "Demo mug",
  "handle": "demo-mug",
  "status": "draft",
  "currency": "USD",
  "subtitle": null,
  "vendor": null,
  "product_type": null,
  "tags": [],
  "description": "A ceramic mug.",
  "seo_title": null,
  "seo_description": null,
  "specs": [
    {
      "label": "Material",
      "value": "Ceramic"
    }
  ],
  "page_sections": [
    {
      "id": "faq-example",
      "type": "faq",
      "enabled": true,
      "position": 0,
      "props": {
        "heading": "Questions",
        "items": [
          {
            "q": "Material?",
            "a": "Ceramic."
          }
        ]
      }
    }
  ],
  "page_config": {
    "buyButton": {
      "label": "Add to cart",
      "showPrice": true
    }
  },
  "rating_value": null,
  "rating_count": 0,
  "gift_banner_text": null,
  "scarcity_text": null,
  "social_proof_text": null,
  "shopify_product_id": null,
  "product_url": "",
  "created_at": "2026-09-19T13:00:00.000Z",
  "updated_at": "2026-09-19T13:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | products row: id, shop_id, owner_user_id, title, handle, status, currency, subtitle, vendor, product_type, tags, description, seo_title, seo_description, specs, page_sections, page_config, rating_value, rating_count, gift_banner_text, scarcity_text, social_proof_text, shopify_product_id, product_url, created_at, updated_at. |
| `handle` | string | URL slug (<= 60 chars, [a-z0-9-]); the storefront URL is /products/<handle>. |
| `page_sections[]` | object[] | Defaults: info_tabs (5 tabs, on), logos_carousel (on), ugc_videos (off), 3x rich_section (off), reviews (on), faq (off), customization (off) - ids 'sec_<8hex>_<i>'. |

**Errors**

- `400` {"error":"invalid payload","details":...}: unknown key (strict), invalid currency, options or variant combination (Option values must be unique; Duplicate variant combination; Variant option_values must match the declared options in order); {"error":"Product handle is empty after normalization"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` No unique handle available; {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `413` Request body over 2 MB
- `422` An unavailable or foreign subscription product or bundle component
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).
- `503` {"error":"Complete product creation requires the local catalogue"}

**Gotchas**

- Strict top-level schema and 2 MiB body limit. No partial product remains after a failed atomic write.
- Response is the product row directly (.id), not a detail envelope (.product.id). Read GET detail for options, variants, media, tiers, bundle and shops.
- Creation is not idempotent. After an ambiguous response, inspect products before repeating POST. Handle collisions allocate a unique suffix within the store.
- Currency is three ASCII letters and normalized uppercase. Product status defaults draft; store listing defaults inactive. Store activation and payment routing remain separate.
- Subscription product must be active, not deleted, and owned by the store account. Bundle variants must belong or be linked to the selected store.
- Generated variant rows default to price 0 until a top-level price or matching explicit variant sets it. Set intended prices before activation.
- AI generation remains a separate creative job; completed reviewed output may populate supported text/sections/media fields. No paid provider call occurs during product creation.
- Core PUT remains a core patch only. After creation update options, variants, media, specs, tiers, bundle, sections and page-config through their individual routes.
- Product catalogue routes always use Kontrol's own database. They never create or edit products upstream on Shopify.

##### `GET /v1/checkouts/:shopId/products-stats`

**Scope** `checkouts.read` - **Read per-product sales stats of a store**

Per-product sales counters of the store over a window (default: the 30 days before to), from the database function catalog_product_stats, returned as is. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string; default `to - 30 days` | no | Window start (ISO instant); default to minus 30 days. Not validated. |
| `to` | string; default `now` | no | Window end (ISO instant); default now. Not validated by the route: an unparsable value answers 400 from the read (500 when from is omitted). |

**Response**

```json
{
  "from": "2026-08-20T13:05:00.000Z",
  "to": "2026-09-19T13:05:00.000Z",
  "rows": [
    {
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "title": "Posture Corrector Pro",
      "orders": 121,
      "units": 134,
      "revenue_cents": 482790,
      "approved": 121,
      "declined": 29
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `from / to` | string | The window actually sent (defaults filled in). |
| `rows[]` | object[] | Rows of the RPC catalog_product_stats(p_shop_ids, p_from, p_to). Each carries product_id; the other columns are defined by the checkout database function and are rendered dynamically by the dashboard - treat the set as opaque and read the keys from the first row. |

**Errors**

- `400` {"error":"A date/time value is invalid."}: from or to is not a date the database can read.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId (unexpected server or database failure; also a to that is not a date sent without from, which fails before the read).

**Gotchas**

- The column set is owned by the checkout database, not by cocoapi; the example columns are illustrative.
- Money columns, when present, follow the platform rule: integer cents.
- Always pass full ISO timestamps; there is no date-only expansion here.

##### `GET /v1/checkouts/:shopId/products/:pid`

**Scope** `checkouts.read` - **Read a product in full**

Returns the product row and every child collection in one call: options with their values, variants, media, price tiers, bundle items, reviews, translation summaries and the shop_products links (availability). Read-only; nine parallel PostgREST reads.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Response**

```json
{
  "product": {
    "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
    "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "owner_user_id": null,
    "title": "Posture Corrector Pro",
    "handle": "posture-corrector-pro",
    "status": "active",
    "currency": "USD",
    "subtitle": "Sit straighter in a week",
    "vendor": "Brand",
    "product_type": "Wellness",
    "tags": [
      "posture",
      "back"
    ],
    "description": "<p>Adjustable, breathable...</p>",
    "seo_title": "Posture Corrector Pro - Brand",
    "seo_description": "Adjustable posture corrector...",
    "specs": [
      {
        "label": "Material",
        "value": "Neoprene"
      }
    ],
    "page_sections": [
      {
        "id": "sec_9f3a2c1b_0",
        "type": "info_tabs",
        "enabled": true,
        "position": 0,
        "props": {
          "tabs": [
            {
              "key": "why",
              "title": "Description",
              "body": ""
            }
          ]
        }
      }
    ],
    "page_config": {
      "subBar": {
        "enabled": true,
        "label": "Rated Excellent",
        "text": "",
        "image": "/product-page/trustpilot-stars.png",
        "imageAlt": "Rated 5 stars on Trustpilot"
      }
    },
    "rating_value": 4.7,
    "rating_count": 128,
    "gift_banner_text": null,
    "scarcity_text": "Only 12 left",
    "social_proof_text": "2,400 sold this month",
    "shopify_product_id": null,
    "product_url": "",
    "created_at": "2026-07-10T09:00:00.000Z",
    "updated_at": "2026-09-17T12:30:00.000Z"
  },
  "options": [
    {
      "id": "aaaaaaa1-bbbb-4ccc-8ddd-eeeeeeeeeee1",
      "name": "Size",
      "position": 0,
      "display_type": "button",
      "values": [
        {
          "id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff1",
          "value": "M",
          "position": 0,
          "swatch_hex": null,
          "swatch_image_url": null
        },
        {
          "id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff2",
          "value": "L",
          "position": 1,
          "swatch_hex": null,
          "swatch_image_url": null
        }
      ]
    }
  ],
  "variants": [
    {
      "id": "11111111-2222-4333-8444-555555555551",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "Black / M",
      "sku": "PCP-BLK-M",
      "price_cents": 3990,
      "compare_at_price_cents": 5990,
      "cost_cents": 900,
      "weight_grams": 180,
      "barcode": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "position": 0,
      "option1_value_id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff1",
      "option2_value_id": null,
      "created_at": "2026-07-10T09:05:00.000Z",
      "updated_at": "2026-09-17T12:30:00.000Z"
    },
    {
      "id": "11111111-2222-4333-8444-555555555552",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "L",
      "sku": "PCP-L",
      "price_cents": 3990,
      "compare_at_price_cents": 5990,
      "cost_cents": 900,
      "weight_grams": 180,
      "barcode": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "position": 1,
      "option1_value_id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff2",
      "option2_value_id": null,
      "created_at": "2026-07-10T09:05:00.000Z",
      "updated_at": "2026-09-17T12:30:00.000Z"
    }
  ],
  "media": [
    {
      "id": "cccccccc-dddd-4eee-8fff-000000000001",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "source_url": "https://cdn.example.com/pcp-front.jpg",
      "alt": "Front view",
      "position": 0,
      "kind": "image",
      "variant_id": null,
      "lqip": "data:image/webp;base64,UklGRk4AAABXRUJQVlA4...",
      "created_at": "2026-07-10T09:06:00.000Z"
    }
  ],
  "tiers": [
    {
      "id": "eeeeeeee-0000-4000-8000-000000000001",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "min_quantity": 2,
      "unit_price_cents": null,
      "extra_off_cents": 0,
      "discount_pct": 10,
      "label": "Buy 2",
      "badge": "Popular",
      "position": 0
    }
  ],
  "bundle": [],
  "reviews": [
    {
      "id": "dddddddd-eeee-4fff-8000-111111111111",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "author_name": "Sarah K.",
      "rating": 5,
      "title": "Works",
      "body": "Back pain gone in a week.",
      "photo_url": null,
      "avatar_url": null,
      "verified_buyer": true,
      "review_date": "2026-09-01",
      "is_published": true,
      "created_at": "2026-09-02T10:00:00.000Z"
    }
  ],
  "translations": [
    {
      "id": "ffffffff-0000-4000-8000-000000000001",
      "locale": "fr",
      "model": "claude-sonnet-4-6",
      "updated_at": "2026-09-15T08:00:00.000Z"
    }
  ],
  "shops": [
    {
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "is_active": true,
      "position": 0,
      "price_override_cents": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `product` | object | Raw products row (see POST). |
| `options[]` | object[] | <= 2 of { id, name, position (0\|1), display_type: button\|image-swatch, values[] { id, value, position, swatch_hex, swatch_image_url } }. |
| `variants[]` | object[] | product_variants rows ordered by position: id, product_id, title, sku, price_cents, compare_at_price_cents, cost_cents, weight_grams, barcode, inventory_qty (null = untracked), is_active, image_url, position, option1_value_id, option2_value_id, timestamps. INACTIVE variants are included. |
| `media[]` | object[] | product_media rows by position: id, url, source_url, alt, position, kind (image\|video), variant_id, lqip (tiny webp data URI or null). |
| `tiers[]` | object[] | product_price_tiers by position: min_quantity, unit_price_cents (legacy fixed price or null), extra_off_cents, discount_pct, label, badge. |
| `bundle[]` | object[] | product_bundle_items: component_variant_id, quantity, is_gift, price_override_cents, position. |
| `reviews[]` | object[] | product_reviews newest first (published or not). |
| `translations[]` | object[] | { id, locale, model, updated_at } - machine translations produced by the checkout (bodies not returned). |
| `shops[]` | object[] | { shop_id, is_active, position, price_override_cents }: one per store of the caller's account the product is listed on. |
| `product.subscription_product_id` | uuid\|null | Linked subscription product, if any. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- Money is integer cents in product.currency.
- variants[] includes deactivated rows (is_active false) left behind by option changes - filter on is_active for the sellable set.
- shops[] lists only the caller's own stores (other accounts' listings are removed), with the caller's store IDs.

##### `PUT /v1/checkouts/:shopId/products/:pid`

**Scope** `checkouts.write` - **Update product core fields**

Partial update of the product row (title, handle, status, currency, texts, tags, SEO, rating). A changed handle is slugified, made unique within the owning store and a redirect old->new is written into storefront.handleRedirects of every linked store so old URLs keep working. Currency is upper-cased. Revalidates the caches for the old and the new handle. Returns the saved row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `title` | string | no | 1 to 300 characters. |
| `handle` | string | no | 1 to 80; slugified (lower-case, accents stripped, [a-z0-9-], at most 60). Made unique in the owning store with -2, -3 suffixes; read the stored handle from the answer. |
| `status` | string | no | draft, active or archived. Only active products are sellable, and only where listed. |
| `currency` | string | no | Exactly 3 characters, upper-cased server-side (usd becomes USD). Applies to every variant price. |
| `subtitle` | string\|null | no | Max 300. |
| `vendor` | string\|null | no | Max 120. |
| `product_type` | string\|null | no | Max 120. |
| `tags` | string[] | no | Up to 50 tags of at most 60 characters. |
| `description` | string | no | Max 100000 characters, HTML allowed. |
| `seo_title` | string\|null | no | Max 200. |
| `seo_description` | string\|null | no | Max 500. |
| `gift_banner_text` | string\|null | no | Max 300. |
| `scarcity_text` | string\|null | no | Max 300. |
| `social_proof_text` | string\|null | no | Max 300. |
| `rating_value` | number\|null | no | 0 to 5. Recomputed (and capped at 4.7) by the next review change. |
| `rating_count` | integer | no | >= 0. Recomputed by the next review change. |
| `subscription_product_id` | uuid\|null | no | An active, not deleted subscription product of the store owner account; null removes the link (422 otherwise). The price stays on the variants. |

**Request body**

```json
{
  "title": "Posture Corrector Pro",
  "status": "active",
  "currency": "usd",
  "tags": [
    "posture",
    "back"
  ],
  "scarcity_text": "Only 12 left"
}
```

**Response**

```json
{
  "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
  "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "owner_user_id": null,
  "title": "Posture Corrector Pro",
  "handle": "posture-corrector-pro",
  "status": "active",
  "currency": "USD",
  "subtitle": "Sit straighter in a week",
  "vendor": "Brand",
  "product_type": "Wellness",
  "tags": [
    "posture",
    "back"
  ],
  "description": "<p>Adjustable, breathable...</p>",
  "seo_title": "Posture Corrector Pro - Brand",
  "seo_description": "Adjustable posture corrector...",
  "specs": [
    {
      "label": "Material",
      "value": "Neoprene"
    }
  ],
  "page_sections": [
    {
      "id": "sec_9f3a2c1b_0",
      "type": "info_tabs",
      "enabled": true,
      "position": 0,
      "props": {
        "tabs": [
          {
            "key": "why",
            "title": "Description",
            "body": ""
          }
        ]
      }
    }
  ],
  "page_config": {
    "subBar": {
      "enabled": true,
      "label": "Rated Excellent",
      "text": "",
      "image": "/product-page/trustpilot-stars.png",
      "imageAlt": "Rated 5 stars on Trustpilot"
    }
  },
  "rating_value": 4.7,
  "rating_count": 128,
  "gift_banner_text": null,
  "scarcity_text": "Only 12 left",
  "social_proof_text": "2,400 sold this month",
  "shopify_product_id": null,
  "product_url": "",
  "created_at": "2026-07-10T09:00:00.000Z",
  "updated_at": "2026-09-17T12:30:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | The saved products row (handle as finally stored, currency upper-cased). |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}; {"error":"handle empty after slugify"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `413` Request body over 2 MB
- `422` {"error":"Product is not available in this store local catalogue"}; {"error":"Choose an active subscription product from this store account"} (subscription_product_id only)
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- Read `handle` from the response: it may differ from what you sent (slugified, suffixed).
- Renaming the handle keeps the old URL alive via handleRedirects on each linked store's storefront jsonb; redirect chains are collapsed.
- Unknown keys (price, variants, media...) are stripped silently - prices live on variants.

##### `DELETE /v1/checkouts/:shopId/products/:pid`

**Scope** `checkouts.write` - **Delete a product**

HARD-deletes the product row; the checkout database cascades to options, values, variants, media, tiers, bundle items, reviews, translations and shop_products links. Revalidates the product and every linked store. Irreversible.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- Reachable through ANY store the product is linked to, not only its owner - a linked tenant can delete it for everyone.
- Prefer PUT .../products/:pid {status:'archived'} - variants referenced by past orders vanish with a hard delete.
- Media files stay in Storage (only rows are deleted).

##### `PUT /v1/checkouts/:shopId/products/:pid/availability`

**Scope** `checkouts.write` - **Set which stores list the product**

Replaces the product's shop_products links for every visible store. The active array is the complete desired listing selection; omitted visible stores are unlisted. Existing position and price_override_cents are preserved when omitted, explicit null clears a price override, and a new listing defaults to position 0. Links outside the caller's scope remain untouched. Revalidates the product and involved stores.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `active` | object[] | **yes** | Up to 50: the complete list of the caller's stores that should list the product. A store of the account left out is unlisted (the owning store included). |
| `active[].shop_id` | uuid | **yes** | A store of the caller's account (its store ID as listed by GET /v1/checkouts). |
| `active[].position` | integer | no | >= 0: position of the product in that store. Absent keeps the existing position (0 for a new listing). |
| `active[].price_override_cents` | integer\|null | no | >= 0: one per-store price in cents over the variant prices. Absent keeps the existing override; null clears it. |

**Request body**

```json
{
  "active": [
    {
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11"
    },
    {
      "shop_id": "8c4e2a10-5d7f-4b3e-a1c9-6e2d0f8b7a55",
      "price_override_cents": 3490
    }
  ]
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"Invalid availability","details":...} (checked before anything else: active missing, over 50, shop_id not a UUID, negative value); {"error":"invalid payload","details":...}; {"error":"Store <shop_id> is listed twice in active. List each store once."} (checked before anything is written)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); {"error":"Store is not available in this account"}: an entry targets a store outside the caller's account (nothing written); {"error":"shop <id> not visible"}; Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Omitting the OWNING store (:shopId) from `active` unlists the product there too - the owner link is not special.
- Listing on a store does not make it sellable: status must also be active and the product needs an active variant.
- price_override_cents is a single per-store price in integer cents applied over the variant prices.
- The active array is the complete desired shop selection within the caller account. Omitted shops are unlisted. Omitted price_override_cents preserves an existing override; null clears it.
- Sending {"active":[]} unlists the product from every store of the caller's account; listings on other accounts' stores are never touched.

##### `PUT /v1/checkouts/:shopId/products/:pid/bundle`

**Scope** `checkouts.write` - **Replace bundle components**

Replace-all of the components sold together when this product is a bundle (product_bundle_items): existing items deleted, given ones inserted in order. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 50 items; [] clears the bundle. |
| `[].component_variant_id` | uuid | **yes** | Variant included in the bundle. At most 50 items. |
| `[].quantity` | integer; default `1` | no | >= 1. |
| `[].is_gift` | boolean; default `false` | no | Free item. |
| `[].price_override_cents` | integer\|null; default `null` | no | >= 0; null = the component price. |

**Request body**

```json
[
  {
    "component_variant_id": "11111111-2222-4333-8444-555555555551",
    "quantity": 1
  },
  {
    "component_variant_id": "22222222-3333-4444-8555-666666666661",
    "quantity": 1,
    "is_gift": true,
    "price_override_cents": 0
  }
]
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}; {"error":"Unknown bundle component: <id> is not a variant of a product of this store. Use a variant id listed by GET /v1/checkouts/:shopId/products/:pid."}: a component_variant_id is unknown, or belongs to a product this store does not sell. Checked before anything is written: the current bundle stays as it was.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Body is a bare JSON ARRAY.
- Every component_variant_id must be a variant of a product this store sells (owned or listed); an unknown one is refused with 400 before the current bundle is replaced.
- price_override_cents is integer cents; null = the component variant's own price.

##### `POST /v1/checkouts/:shopId/products/:pid/media`

**Scope** `checkouts.write` - **Add media from a URL**

Appends an image or video to the product gallery from a URL. External images are re-hosted into the shop-assets bucket (products/<pid>/img-<pos>-...) - best effort, the original URL is kept if the fetch fails - and a 20-px LQIP placeholder is generated for Storage-hosted images. If variant_id is given, that variant's image_url is set to the media URL. Revalidates caches; returns the row, 201.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `url` | string | **yes** | 1 to 2048: absolute URL of the image or video. |
| `alt` | string\|null; default `null` | no | Max 300. |
| `kind` | string; default `image` | no | image or video. Videos are never re-hosted and get no LQIP. |
| `rehost` | boolean; default `true` | no | Copy an external image into the media bucket (skipped when the URL is already a storage public URL; best effort). |
| `variant_id` | uuid\|null | no | Attach to a variant and set its image_url (not checked to belong to this product). |

**Request body**

```json
{
  "url": "https://cdn.example.com/pcp-front.jpg",
  "alt": "Front view",
  "kind": "image",
  "rehost": true,
  "variant_id": "11111111-2222-4333-8444-555555555551"
}
```

**Response**

```json
{
  "id": "cccccccc-dddd-4eee-8fff-000000000001",
  "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
  "url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
  "source_url": "https://cdn.example.com/pcp-front.jpg",
  "alt": "Front view",
  "position": 0,
  "kind": "image",
  "variant_id": "11111111-2222-4333-8444-555555555551",
  "lqip": "data:image/webp;base64,UklGRk4AAABXRUJQVlA4...",
  "created_at": "2026-07-10T09:06:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | product_media row: id, product_id, url (final, possibly re-hosted), source_url (original URL when external, else null), alt, position (last + 1), kind, variant_id, lqip, created_at. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- 201 on success.
- Re-hosting fetches the URL from the cocoapi server; private or hot-link-protected images stay external (rehost silently false - compare url with source_url).
- Content type is not validated for URL media; kind is what you declare.

##### `PUT /v1/checkouts/:shopId/products/:pid/media/:id`

**Scope** `checkouts.write` - **Update a media item**

Patches alt text, position and/or variant attachment of one media row of the product. Setting variant_id also copies the media URL into that variant's image_url. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Media ID of this product. Not validated as a UUID: a malformed value answers 500. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `alt` | string\|null | no | Max 300. |
| `position` | integer | no | >= 0, written as is (siblings are not renumbered): prefer the move route to reorder. |
| `variant_id` | uuid\|null | no | Attach to a variant (its image_url takes the media URL); null detaches (the variant image_url is left as is). |

**Request body**

```json
{
  "alt": "Front view - black",
  "variant_id": "11111111-2222-4333-8444-555555555551"
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the row was found and patched. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Not found"}: no media with that id on this product
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- :id is not validated as a UUID; a malformed value surfaces as a 500 from the database filter.
- Sending {} is accepted and changes nothing (ok true).

##### `DELETE /v1/checkouts/:shopId/products/:pid/media/:id`

**Scope** `checkouts.write` - **Delete a media item**

Removes one media row from the product gallery and revalidates caches. The file stays in Storage.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Media ID of this product. Not validated as a UUID: a malformed value answers 500. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Not found"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- A variant whose image_url pointed at this media keeps the (still valid) URL.
- :id is not validated as a UUID (malformed -> 500).

##### `POST /v1/checkouts/:shopId/products/:pid/media/:id/move`

**Scope** `checkouts.write` - **Move a media item in the product gallery**

Move one media item of the product gallery one step (dir) or to an index (position); the whole gallery is renumbered in one transaction. Refreshes caches when it moved.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Media ID of this product. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `dir` | string | no | up or down: one step. Send either dir or position, not both (strict bodies). |
| `position` | integer | no | 0 to 2147483647: target index in the gallery (0 = first). Must be inside the current gallery. |

**Request body**

```json
{
 "dir": "up"
}
```

**Response**

```json
{
 "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the media moved or was already at the requested place. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"Invalid media ID"}; {"error":"invalid payload","details":...} (neither or both of dir and position, unknown key)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Media not found in this product"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}; {"error":"The gallery changed. Refresh and choose a position within the current gallery."} (position outside the gallery)
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` {"error":"Media ordering requires the local catalogue"}

**Gotchas**

- Since 2026-11-01 a move renumbers the whole gallery 0..n-1 (gaps left by manual PUT position edits disappear); before, the item swapped positions with one neighbour. A no-op (edge, or the current index) writes nothing.
- The order used is position, then id: two media with the same position have a stable order, and position counts in that order.
- Moving past the first or last place is a no-op that still answers ok. Every move renumbers the gallery 0..n-1.

##### `POST /v1/checkouts/:shopId/products/:pid/media/upload`

**Scope** `checkouts.write` - **Upload media bytes**

Uploads image/video bytes (JSON, base64) into shop-assets/products/<pid>/up-<timestamp>-<random>.<ext>, then appends the resulting URL to the gallery exactly like POST .../media with rehost false (kind derived from the MIME type, LQIP for images). Returns the media row, 201.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `content_type` | string | **yes** | Max 64: image/png, image/jpeg, image/webp, image/gif, video/mp4 or video/webm (video/* gives kind video). Anything else is 415. |
| `data_base64` | string | **yes** | Base64 of the bytes; decoded max 20 MB. Invalid characters are silently dropped. |
| `alt` | string\|null; default `null` | no | Max 300. |
| `variant_id` | uuid\|null | no | Attach to a variant and set its image_url. |

**Request body**

```json
{
  "content_type": "image/jpeg",
  "data_base64": "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/...",
  "alt": "Side view",
  "variant_id": null
}
```

**Response**

```json
{
  "id": "cccccccc-dddd-4eee-8fff-000000000002",
  "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
  "url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/up-1789820000000-9f3c2a1b.jpg",
  "source_url": null,
  "alt": "Side view",
  "position": 1,
  "kind": "image",
  "variant_id": null,
  "lqip": "data:image/webp;base64,UklGRk4AAABXRUJQVlA4...",
  "created_at": "2026-07-10T09:06:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | product_media row (source_url null, url in the shop-assets bucket). |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `413` {"error":"file too large (max 20 MB)"} after decoding; a request body over 30 MB is refused before parsing
- `415` {"error":"unsupported content type <type>"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `502` {"error":"storage upload failed: <status>","requestId":"<id>"}: the media storage refused the file; nothing was saved.

**Gotchas**

- 201 on success.
- Base64 inflates ~33 %: keep files <= 20 MiB so the JSON stays under 30 MiB.
- Invalid base64 is not detected (bytes silently dropped).
- A storage upload failure answers 502 (storage upload failed: <status>).

##### `PUT /v1/checkouts/:shopId/products/:pid/options`

**Scope** `checkouts.write` - **Replace product options and rebuild variants**

Defines up to two options (e.g. Size, Colour) with their values. Options are matched by POSITION (index 0 and 1) and values by TEXT: existing values keep their ids and variants; a renamed value is a delete + insert. A missing position deletes that option. Then the variant matrix is rebuilt (cartesian product: new combos inserted at the first existing variant's price, vanished combos deactivated - never deleted). Returns the full product like GET.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 2 options; together at most 200 variants. |
| `[].name` | string | **yes** | Option name, 1 to 60 characters. At most 2 options. |
| `[].display_type` | string; default `button` | no | button or image-swatch. |
| `[].values[].value` | string | **yes** | 1 to 80 characters; 1 to 50 values per option, unique within the option. The options together may imply at most 200 variants. |
| `[].values[].swatch_image_url` | string\|null | no | Max 2048: swatch image (image-swatch). |
| `[].values[].swatch_hex` | string\|null | no | Max 16: swatch colour. |

**Request body**

```json
[
  {
    "name": "Size",
    "display_type": "button",
    "values": [
      {
        "value": "M"
      },
      {
        "value": "L"
      }
    ]
  },
  {
    "name": "Colour",
    "display_type": "image-swatch",
    "values": [
      {
        "value": "Black",
        "swatch_hex": "#000000"
      },
      {
        "value": "Beige",
        "swatch_image_url": "https://cdn.example.com/sw-beige.png"
      }
    ]
  }
]
```

**Response**

```json
{
  "product": {
    "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
    "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "owner_user_id": null,
    "title": "Posture Corrector Pro",
    "handle": "posture-corrector-pro",
    "status": "active",
    "currency": "USD",
    "subtitle": "Sit straighter in a week",
    "vendor": "Brand",
    "product_type": "Wellness",
    "tags": [
      "posture",
      "back"
    ],
    "description": "<p>Adjustable, breathable...</p>",
    "seo_title": "Posture Corrector Pro - Brand",
    "seo_description": "Adjustable posture corrector...",
    "specs": [
      {
        "label": "Material",
        "value": "Neoprene"
      }
    ],
    "page_sections": [
      {
        "id": "sec_9f3a2c1b_0",
        "type": "info_tabs",
        "enabled": true,
        "position": 0,
        "props": {
          "tabs": [
            {
              "key": "why",
              "title": "Description",
              "body": ""
            }
          ]
        }
      }
    ],
    "page_config": {
      "subBar": {
        "enabled": true,
        "label": "Rated Excellent",
        "text": "",
        "image": "/product-page/trustpilot-stars.png",
        "imageAlt": "Rated 5 stars on Trustpilot"
      }
    },
    "rating_value": 4.7,
    "rating_count": 128,
    "gift_banner_text": null,
    "scarcity_text": "Only 12 left",
    "social_proof_text": "2,400 sold this month",
    "shopify_product_id": null,
    "product_url": "",
    "created_at": "2026-07-10T09:00:00.000Z",
    "updated_at": "2026-09-17T12:30:00.000Z"
  },
  "options": [
    {
      "id": "aaaaaaa1-bbbb-4ccc-8ddd-eeeeeeeeeee1",
      "name": "Size",
      "position": 0,
      "display_type": "button",
      "values": [
        {
          "id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff1",
          "value": "M",
          "position": 0,
          "swatch_hex": null,
          "swatch_image_url": null
        },
        {
          "id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff2",
          "value": "L",
          "position": 1,
          "swatch_hex": null,
          "swatch_image_url": null
        }
      ]
    }
  ],
  "variants": [
    {
      "id": "11111111-2222-4333-8444-555555555551",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "Black / M",
      "sku": "PCP-BLK-M",
      "price_cents": 3990,
      "compare_at_price_cents": 5990,
      "cost_cents": 900,
      "weight_grams": 180,
      "barcode": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "position": 0,
      "option1_value_id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff1",
      "option2_value_id": null,
      "created_at": "2026-07-10T09:05:00.000Z",
      "updated_at": "2026-09-17T12:30:00.000Z"
    },
    {
      "id": "11111111-2222-4333-8444-555555555552",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "L",
      "sku": "PCP-L",
      "price_cents": 3990,
      "compare_at_price_cents": 5990,
      "cost_cents": 900,
      "weight_grams": 180,
      "barcode": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "position": 1,
      "option1_value_id": "bbbbbbb1-cccc-4ddd-8eee-fffffffffff2",
      "option2_value_id": null,
      "created_at": "2026-07-10T09:05:00.000Z",
      "updated_at": "2026-09-17T12:30:00.000Z"
    }
  ],
  "media": [
    {
      "id": "cccccccc-dddd-4eee-8fff-000000000001",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg",
      "source_url": "https://cdn.example.com/pcp-front.jpg",
      "alt": "Front view",
      "position": 0,
      "kind": "image",
      "variant_id": null,
      "lqip": "data:image/webp;base64,UklGRk4AAABXRUJQVlA4...",
      "created_at": "2026-07-10T09:06:00.000Z"
    }
  ],
  "tiers": [
    {
      "id": "eeeeeeee-0000-4000-8000-000000000001",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "min_quantity": 2,
      "unit_price_cents": null,
      "extra_off_cents": 0,
      "discount_pct": 10,
      "label": "Buy 2",
      "badge": "Popular",
      "position": 0
    }
  ],
  "bundle": [],
  "reviews": [
    {
      "id": "dddddddd-eeee-4fff-8000-111111111111",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "author_name": "Sarah K.",
      "rating": 5,
      "title": "Works",
      "body": "Back pain gone in a week.",
      "photo_url": null,
      "avatar_url": null,
      "verified_buyer": true,
      "review_date": "2026-09-01",
      "is_published": true,
      "created_at": "2026-09-02T10:00:00.000Z"
    }
  ],
  "translations": [
    {
      "id": "ffffffff-0000-4000-8000-000000000001",
      "locale": "fr",
      "model": "claude-sonnet-4-6",
      "updated_at": "2026-09-15T08:00:00.000Z"
    }
  ],
  "shops": [
    {
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "is_active": true,
      "position": 0,
      "price_override_cents": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `(ProductFull)` | object | Same shape as GET .../products/:pid, after the rebuild. variants[] now holds one ACTIVE row per combination plus deactivated leftovers. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: more than 2 options, empty values, too long, or "these options make N variants, more than the 200 a product can hold - use fewer values"
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Body is a bare JSON ARRAY, not an object.
- Renaming a value ("Medium" -> "M") orphans its variant (deactivated) and creates a fresh one at the default price - prices, SKUs and stock must be re-entered via PUT .../variants.
- New variants copy price_cents from the first existing variant (0 if none), sku "", image_url "". Always follow with PUT .../variants.
- Reordering options (swapping positions 0 and 1) rewrites both options and orphans every variant.
- Raw JSON array; at most two options and 200 resulting variants. This rebuilds the matrix: re-read product variants and use their returned UUIDs when assigning prices, inventory or images.

##### `PUT /v1/checkouts/:shopId/products/:pid/page-config`

**Scope** `checkouts.write` - **Replace the product page configuration**

Rebuilds products.page_config from a STRICT body (unknown top-level keys refused; every key optional with defaults): sub-bar, banner, free gift, price block, bundles box, sales points, buy button, trust badges, sticky bar, cart drawer, overstock, lightbox, pre-order. Server adds the fixed Trustpilot sub-bar image, enabled flags and per-item enabled: true. Since 2026-11-01 the result is deep-merged into the stored page_config: every declared field of the 13 blocks is written (the sent value or its default), while stored keys the schema does not declare (safePage, cloak, theme settings, any other top-level or nested key) are preserved. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `subBar` | object; default `{}` | no | Strict top level: an unknown key is a 400. Each block defaults to its defaults when absent. |
| `subBar.enabled` | boolean; default `false` | no | Rating bar under the title. |
| `subBar.label` | string; default `""` | no | Max 200. |
| `subBar.text` | string; default `""` | no | Max 500 (image and imageAlt are forced server-side). |
| `banner.enabled` | boolean; default `false` | no | Top banner. |
| `banner.text` | string; default `""` | no | Max 300. |
| `banner.highlight` | string; default `""` | no | Max 120. |
| `freeGift.enabled` | boolean; default `false` | no | Free gift block. |
| `freeGift.subtitle` | string; default `""` | no | Max 300. |
| `freeGift.image` | string; default `""` | no | Max 2048. |
| `priceBlock.showCompareAt` | boolean; default `true` | no | Show the compare-at price. |
| `priceBlock.showSaveTag` | boolean; default `true` | no | Show the save tag. |
| `bundles.title` | string; default `Bundle & Save` | no | Max 120. |
| `bundles.countdown.enabled` | boolean; default `false` | no | Countdown on the bundles. |
| `bundles.countdown.minutes` | integer; default `0` | no | >= 0. |
| `bundles.stickPrices` | boolean; default `true` | no | Strike-through prices on bundles. |
| `salesPoints.enabled` | boolean; default `false` | no | Sales points list. |
| `salesPoints.items[].bold` | string | no | Required, max 200. Up to 20 items. |
| `salesPoints.items[].text` | string; default `""` | no | Max 500. |
| `buyButton.label` | string; default `ORDER NOW` | no | Max 80. |
| `buyButton.showPrice` | boolean; default `true` | no | Price inside the button. |
| `trustBadges.enabled` | boolean; default `false` | no | Trust badges. |
| `trustBadges.items[].label` | string | no | Required, max 120. Up to 12 items. |
| `trustBadges.items[].icon` | string; default `""` | no | Max 2048. |
| `stickyBar.enabled` | boolean; default `false` | no | Sticky order bar. |
| `stickyBar.label` | string; default `Order Now` | no | Max 80. |
| `cartDrawer.title` | string; default `Added to cart` | no | Max 120. |
| `cartDrawer.checkoutLabel` | string; default `Continue to Checkout` | no | Max 120. |
| `cartDrawer.continueLabel` | string; default `Continue shopping` | no | Max 120. |
| `cartDrawer.freeShippingBar.enabled` | boolean; default `false` | no | Free shipping bar. |
| `cartDrawer.freeShippingBar.text` | string; default `""` | no | Max 300. |
| `cartDrawer.giftBadge.enabled` | boolean; default `false` | no | Gift badge. |
| `overstock.enabled` | boolean; default `false` | no | Stock counter. |
| `overstock.unitsLeft` | integer; default `0` | no | >= 0. |
| `overstock.unitsTotal` | integer; default `0` | no | >= 0. |
| `lightbox.enabled` | boolean; default `false` | no | Image lightbox. |
| `preOrder.enabled` | boolean; default `false` | no | Pre-order mode. |

**Request body**

```json
{
  "subBar": {
    "enabled": true,
    "label": "Rated Excellent",
    "text": "4.7/5 from 128 reviews"
  },
  "banner": {
    "enabled": true,
    "text": "Free shipping over $50",
    "highlight": "Today"
  },
  "priceBlock": {
    "showCompareAt": true,
    "showSaveTag": true
  },
  "bundles": {
    "title": "Bundle & Save",
    "countdown": {
      "enabled": true,
      "minutes": 15
    },
    "stickPrices": true
  },
  "salesPoints": {
    "enabled": true,
    "items": [
      {
        "bold": "Free returns",
        "text": "30 days"
      }
    ]
  },
  "buyButton": {
    "label": "ORDER NOW",
    "showPrice": true
  },
  "trustBadges": {
    "enabled": false,
    "items": []
  },
  "stickyBar": {
    "enabled": true,
    "label": "Order Now"
  },
  "cartDrawer": {
    "title": "Added to cart",
    "checkoutLabel": "Continue to Checkout",
    "continueLabel": "Continue shopping",
    "freeShippingBar": {
      "enabled": true,
      "text": "Free shipping unlocked"
    },
    "giftBadge": {
      "enabled": false
    }
  },
  "overstock": {
    "enabled": false,
    "unitsLeft": 0,
    "unitsTotal": 0
  },
  "lightbox": {
    "enabled": true
  },
  "preOrder": {
    "enabled": false
  },
  "freeGift": {
    "enabled": false,
    "subtitle": "",
    "image": ""
  }
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. Read the stored page_config back with GET .../products/:pid. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: unknown top-level key (for example safePage or cloak), string over its limit, negative integer
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- {} is valid and resets every DECLARED field of every block to its default. Undeclared keys in the nested objects of the body are stripped silently (only the top level is strict), while undeclared keys already stored are kept: the write is a deep merge of the validated blocks into the stored page_config. Arrays (salesPoints.items, trustBadges.items) are replaced, never merged.
- safePage and cloak are managed elsewhere and preserved automatically - sending them is a 400.
- Top-level schema defaults replace omitted page configuration. Read the existing product page configuration and preserve its other fields before changing one section.

##### `POST /v1/checkouts/:shopId/products/:pid/reviews`

**Scope** `checkouts.write` - **Add a product review**

Inserts a review row, then recomputes products.rating_value (average of PUBLISHED reviews, 2 decimals, capped at 4.7 for display) and rating_count (published count). Revalidates caches. Returns the row, 201.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `author_name` | string; default `Anonymous` | no | Max 120; "" becomes Anonymous. |
| `rating` | integer; default `5` | no | 1 to 5. |
| `title` | string\|null; default `null` | no | Max 200. |
| `body` | string\|null; default `null` | no | Max 5000. |
| `photo_url` | string\|null; default `null` | no | Max 2048. |
| `avatar_url` | string\|null; default `null` | no | Max 2048. |
| `verified_buyer` | boolean; default `false` | no | Shows the verified badge. |
| `review_date` | string\|null; default `null` | no | Max 10 characters, meant as YYYY-MM-DD (display date; not format-checked). |
| `is_published` | boolean; default `true` | no | Unpublished reviews are hidden and excluded from the rating. |

**Request body**

```json
{
  "author_name": "Sarah K.",
  "rating": 5,
  "title": "Works",
  "body": "Back pain gone in a week.",
  "verified_buyer": true,
  "review_date": "2026-09-01",
  "is_published": true
}
```

**Response**

```json
{
  "id": "dddddddd-eeee-4fff-8000-111111111111",
  "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
  "author_name": "Sarah K.",
  "rating": 5,
  "title": "Works",
  "body": "Back pain gone in a week.",
  "photo_url": null,
  "avatar_url": null,
  "verified_buyer": true,
  "review_date": "2026-09-01",
  "is_published": true,
  "created_at": "2026-09-02T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | product_reviews row: id, product_id, author_name, rating, title, body, photo_url, avatar_url, verified_buyer, review_date, is_published, created_at. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: rating outside 1 to 5 or not an integer, string over its limit
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- 201 on success.
- An empty body {} is valid: it creates a 5-star anonymous review with no text.
- The displayed rating is capped at 4.7 even if every review is 5 stars - by design of the checkout.

##### `PUT /v1/checkouts/:shopId/products/:pid/reviews/:id`

**Scope** `checkouts.write` - **Update a review**

Partial update of one review of the product (same fields as create, all optional, no defaults applied), then rating recomputation and cache revalidation.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Review ID of this product. Not validated as a UUID: a malformed value answers 500. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `author_name` | string | no | Max 120. |
| `rating` | integer | no | 1 to 5. |
| `title` | string\|null | no | Max 200. |
| `body` | string\|null | no | Max 5000. |
| `photo_url` | string\|null | no | Max 2048. |
| `avatar_url` | string\|null | no | Max 2048. |
| `verified_buyer` | boolean | no | Verified badge. |
| `review_date` | string\|null | no | Max 10. |
| `is_published` | boolean | no | Visibility (affects the rating). |

**Request body**

```json
{
  "is_published": false
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the row was found. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Not found"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Unlike POST, omitted fields are kept (true partial).
- :id is not validated as a UUID (malformed -> 500).

##### `DELETE /v1/checkouts/:shopId/products/:pid/reviews/:id`

**Scope** `checkouts.write` - **Delete a review**

Deletes one review of the product, recomputes the rating and revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Review ID of this product. Not validated as a UUID: a malformed value answers 500. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Not found"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Deleting the last published review sets rating_value to null and rating_count to 0.

##### `PUT /v1/checkouts/:shopId/products/:pid/sections`

**Scope** `checkouts.write` - **Replace the product page sections**

Replaces products.page_sections with a normalised list of typed sections, applying the checkout editor's rules per type (known string props trimmed, row lists filtered to those having their primary field, capped; any other prop key and row key is kept as sent), keeping existing ids and generating 'sec_<8hex>_<i>' for new ones (ids starting with 'new-' are treated as new), sorting by position and renumbering 0..n-1. Revalidates caches. Returns the normalised list as saved.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 30 sections; whole replace. |
| `[].id` | string | no | Max 80. Kept when present and not starting with new-; otherwise a sec_<8 hex>_<n> id is generated. |
| `[].type` | string | **yes** | info_tabs, logos_carousel, ugc_videos, rich_section, reviews, faq or customization. At most 30 sections. |
| `[].enabled` | boolean; default `true` | no | Rendered or hidden. |
| `[].position` | integer | no | >= 0; sections are sorted by it and renumbered 0..n-1. Default: the array index. |
| `[].props` | object; default `{}` | no | Free-form per type, normalised (strings trimmed, empty rows dropped, other keys kept). |
| `[].props (info_tabs)` | object | no | { tabs: up to 12 of { key, title (required), body (HTML) } }. |
| `[].props (logos_carousel)` | object | no | { heading }. |
| `[].props (ugc_videos)` | object | no | { heading, videos: up to 50 of { url (required), poster } }. |
| `[].props (rich_section)` | object | no | { layout: image_text (default), feature_grid or how_to_steps; eyebrow, title, mediaUrl; image_text adds side (left by default) and body (HTML); how_to_steps adds steps: up to 50 of { imageUrl, title (required), text }; feature_grid adds items: up to 50 of { iconUrl, title (required), text } }. |
| `[].props (reviews)` | object | no | { heading, moreLabel }. |
| `[].props (faq)` | object | no | { heading, items: up to 30 of { q (required), a } }. |
| `[].props (customization)` | object | no | { heading, note, fields: up to 12 of { label (required), key (derived from the label when absent, made unique), type: text, textarea, number, select, radio or checkbox (text), options (array or comma-separated string, up to 30), placeholder, helpText, max (positive integer, 0 = none), required (true, "true" or "on") } }. |

**Request body**

```json
[
  {
    "id": "sec_9f3a2c1b_0",
    "type": "info_tabs",
    "enabled": true,
    "position": 0,
    "props": {
      "tabs": [
        {
          "key": "why",
          "title": "Description",
          "body": "<p>Adjustable...</p>"
        },
        {
          "key": "shipping",
          "title": "Tracked shipping",
          "body": "3-5 days"
        }
      ]
    }
  },
  {
    "id": "new-1",
    "type": "faq",
    "enabled": true,
    "position": 1,
    "props": {
      "heading": "Questions",
      "items": [
        {
          "q": "Which size?",
          "a": "M fits 60-90 kg."
        }
      ]
    }
  },
  {
    "type": "reviews",
    "enabled": true,
    "props": {
      "heading": "What our customers say",
      "moreLabel": "Read more reviews"
    }
  }
]
```

**Response**

```json
{
  "sections": [
    {
      "id": "sec_9f3a2c1b_0",
      "type": "info_tabs",
      "enabled": true,
      "position": 0,
      "props": {
        "tabs": [
          {
            "key": "why",
            "title": "Description",
            "body": "<p>Adjustable...</p>"
          },
          {
            "key": "shipping",
            "title": "Tracked shipping",
            "body": "3-5 days"
          }
        ]
      }
    },
    {
      "id": "sec_2c7d1e9a_1",
      "type": "faq",
      "enabled": true,
      "position": 1,
      "props": {
        "heading": "Questions",
        "items": [
          {
            "q": "Which size?",
            "a": "M fits 60-90 kg."
          }
        ]
      }
    },
    {
      "id": "sec_5b0e3f4c_2",
      "type": "reviews",
      "enabled": true,
      "position": 2,
      "props": {
        "heading": "What our customers say",
        "moreLabel": "Read more reviews"
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `sections[]` | object[] | The saved list: { id, type, enabled, position (0..n-1), props (normalised) }. Read the generated ids from here. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: unknown type, more than 30 sections, id over 80 characters
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `413` Request body over 4 MB
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Body is a bare JSON ARRAY and the write is a whole replace - omit a section and it is gone.
- New sections (no id, or an id starting with new-) get generated ids that differ between the stored list and this response. Re-read the product before referencing a new section by id.
- Row-list items lacking their primary field (tab title, video url, faq q, field label...) are silently DROPPED and the known string props are trimmed, but since 2026-11-01 every other prop key and row key is kept as sent, so a section saved by the editor keeps the settings this route does not know.
- customization: `required` accepts true or the strings 'on' / 'true' and is stored as a boolean; `max` accepts a number or a numeric string and is stored as a number; `options` accepts an array or a comma-separated string and is stored as an array; an existing `key` is kept, so renaming a label no longer changes the key.
- Row items lacking their primary field (tab title, video url, step or item title, faq q, field label) are dropped; strings are trimmed; other prop keys are kept as sent.
- customization fields: required accepts true, "true" or "on" and is stored as a boolean; max is parsed as an integer (0 = none); options may be an array or a comma-separated string.

##### `PUT /v1/checkouts/:shopId/products/:pid/specs`

**Scope** `checkouts.write` - **Replace product specifications**

Overwrites the products.specs jsonb (label/value table shown on the product page). Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 100 rows; [] clears. |
| `[].label` | string | **yes** | 1 to 120. At most 100 rows. |
| `[].value` | string | **yes** | 1 to 1000. |

**Request body**

```json
[
  {
    "label": "Material",
    "value": "Neoprene"
  },
  {
    "label": "Sizes",
    "value": "M, L"
  }
]
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: empty label or value, too long, more than 100 rows
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Body is a bare JSON ARRAY; whole replace.

##### `PUT /v1/checkouts/:shopId/products/:pid/tiers`

**Scope** `checkouts.write` - **Replace quantity price tiers**

Replace-all of the product's quantity discounts (product_price_tiers): every existing tier is deleted, then the given ones inserted in array order. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 50 tiers; replace-all. |
| `[].min_quantity` | integer | **yes** | >= 1; unique across the tiers (Each quantity threshold must be unique). At most 50 tiers. |
| `[].extra_off_cents` | integer; default `0` | no | >= 0: amount off per unit, in cents. |
| `[].discount_pct` | number; default `0` | no | 0 to 100: percent off. |
| `[].label` | string\|null; default `null` | no | Max 120. |
| `[].badge` | string\|null; default `null` | no | Max 60. |
| `[].unit_price_cents` | integer\|null | no | Legacy fixed unit price, >= 0. Absent keeps the stored value of that min_quantity; null clears it; a number sets it. |

**Request body**

```json
[
  {
    "min_quantity": 2,
    "discount_pct": 10,
    "label": "Buy 2",
    "badge": "Popular"
  },
  {
    "min_quantity": 3,
    "discount_pct": 15,
    "extra_off_cents": 500,
    "label": "Buy 3",
    "badge": "Best value"
  }
]
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: min_quantity < 1, discount_pct > 100, more than 50 rows, or Each quantity threshold must be unique
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Tier ids change on every save (delete + insert).
- unit_price_cents (legacy fixed unit price): absent keeps the stored value of the same min_quantity, null clears it, a number sets it.
- Duplicate min_quantity values are refused with 400.

##### `DELETE /v1/checkouts/:shopId/products/:pid/translations/:id`

**Scope** `checkouts.write` - **Delete a product translation**

Deletes one machine translation row (product_translations) of the product - translations are produced by the checkout's own translation job and are only listed/deleted through this API. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |
| `id` | uuid | **yes** | Translation ID (from GET /v1/checkouts/:shopId/products/:pid translations[]). Not validated as a UUID: a malformed value answers 500. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}; {"error":"Not found"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- There is no create/update route: deleting forces the checkout to regenerate the locale on its next pass.

##### `PUT /v1/checkouts/:shopId/products/:pid/variants`

**Scope** `checkouts.write` - **Update variant prices, SKUs and stock**

Writes the commercial fields of the listed variants (matched by id, scoped to the product): price, compare-at price, cost, weight, barcode, inventory, active flag, image. Only the ids you send are touched; unknown ids are ignored. Revalidates caches.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object[] | **yes** | The body is a bare JSON array (the fields below are its items). At most 200 rows. |
| `[].id` | uuid | **yes** | Variant ID of this product (from GET /v1/checkouts/:shopId/products/:pid variants[]). Rows of another product are ignored. |
| `[].price_cents` | integer | **yes** | >= 0, in cents of the product currency. |
| `[].sku` | string; default `""` | no | Max 120. |
| `[].compare_at_price_cents` | integer\|null; default `null` | no | >= 0; null = no compare-at price. |
| `[].cost_cents` | integer\|null | no | >= 0. Absent keeps the stored value. |
| `[].weight_grams` | integer\|null | no | >= 0. Absent keeps the stored value. |
| `[].barcode` | string\|null | no | Max 80. Absent keeps the stored value. |
| `[].inventory_qty` | integer\|null; default `null` | no | null = untracked. |
| `[].is_active` | boolean; default `true` | no | Sellable variant. |
| `[].image_url` | string; default `""` | no | Max 2048. |

**Request body**

```json
[
  {
    "id": "11111111-2222-4333-8444-555555555551",
    "sku": "PCP-BLK-M",
    "price_cents": 3990,
    "compare_at_price_cents": 5990,
    "cost_cents": 900,
    "weight_grams": 180,
    "inventory_qty": null,
    "is_active": true,
    "image_url": "https://shop.example.com/storage/v1/object/public/shop-assets/products/7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13/img-0-0a.jpg"
  },
  {
    "id": "11111111-2222-4333-8444-555555555552",
    "sku": "PCP-L",
    "price_cents": 3990,
    "compare_at_price_cents": 5990,
    "is_active": true
  }
]
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200 - even when no id matched. |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"invalid payload","details":...}: missing id or price_cents, negative amount, more than 200 rows
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- NOT a partial update per row: zod defaults apply, so omitting sku resets it to "", compare_at_price_cents to null, is_active to true, image_url to "". Send complete rows copied from GET.
- Body is a bare JSON ARRAY. Money is integer cents in the product currency.
- A variant id of another product is silently ignored (no error, ok true). Read back with GET to confirm.
- is_active false hides the variant on the storefront, but the next options change / rebuild re-activates it if its combination still exists.
- Raw JSON array, each row requires an existing variant UUID and integer price_cents. Preserve fields whose schema defaults would otherwise reset them. Values are cents, not dollars.

##### `POST /v1/checkouts/:shopId/products/:pid/variants/rebuild`

**Scope** `checkouts.write` - **Rebuild the variant matrix**

Recomputes the cartesian product of the current option values: inserts missing combinations (title 'Val1 / Val2', price of the first existing variant or 0), re-activates and re-positions existing ones, deactivates every variant whose combination no longer exists (or duplicates collapsing on the same combo). With no options it ensures exactly one option-less variant. No body. Does not revalidate caches by itself.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `pid` | uuid | **yes** | Product ID; the product must be owned by (products.shop_id) or listed on (shop_products) this store. |

**Response**

```json
{
  "variants": 4
}
```

| response field | type | description |
|---|---|---|
| `variants` | integer | Number of ACTIVE combinations after the rebuild (not the total row count). |

**Errors**

- `400` {"error":"bad product id"}: pid is not a UUID; {"error":"this product's options make N variants, more than the 200 a product can hold - remove option values first"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account; {"error":"Product not found in this checkout"}
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Use it once after creating a product with no options to obtain its single sellable variant, then price it with PUT .../variants.
- Variants are never deleted - orders reference them.
- Unlike the other writes this route does NOT bust the checkout cache; a following PUT .../variants does.

##### `POST /v1/checkouts/:shopId/products/attach`

**Scope** `checkouts.write` - **Add existing products to a store**

Adds multiple existing account catalog products to one visible store. The operation enables only the selected shop_products links, creates missing links, and preserves existing listing positions, price overrides, and every other store listing. The product definitions and their owners are unchanged. Retries with the same selection are idempotent.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `productIds` | uuid[] | **yes** | 1 to 200 product IDs (from GET /v1/checkouts/products); duplicates are collapsed. Every product must be owned by or listed on a store of the caller's account, else the whole selection is refused. Strict body. |

**Request body**

```json
{
  "productIds": [
    "00000000-0000-4000-8000-000000000011",
    "00000000-0000-4000-8000-000000000012"
  ]
}
```

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | True after all requested product links are saved. |

**Errors**

- `400` {"error":"invalid payload","details":...}: empty or over 200, invalid UUID, unknown key
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required; {"error":"Choose products from this account"} (nothing is added); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId (unexpected server or database failure; a shopId that is not a UUID).

**Gotchas**

- This adds availability to a store; it never creates a product or edits a Shopify upstream catalog.
- Listing does not activate a draft or archived product; sale requires active product status and an active variant.
- Use PUT /v1/checkouts/:shopId/products/:pid/availability for complete listing replacement, removal, or per-store price changes.

##### `POST /v1/checkouts/:shopId/products/export-pdf-v2`

**Scope** `checkouts.write` - **Stream the product catalogue for a PDF (one store)**

Streams the whole filtered catalogue of one store as NDJSON records, the source the dashboard turns into a PDF.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store (shop) id of the account. Restricts the page to that one store; store-specific columns and totals are dropped. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "columns": [
    "title",
    "handle",
    "status",
    "price"
  ],
  "timezone": "Europe/Paris"
}
```

**Response** (application/x-ndjson)

```json
{"type":"start","version":2}
{"type":"row","row":{"id":"00000000-0000-4000-8000-000000000101","title":"Example Hoodie","handle":"example-hoodie","status":"active","currency":"USD","variants":3,"media":2,"min_price_cents":4999}}
{"type":"end","version":2,"count":1,"totals":{"stores":1,"variants":3,"media":2}}
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Two exports are already running. Retry when one finishes."}` when this server process already streams two exports.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- Despite the name the answer is NDJSON (application/x-ndjson), not a PDF: one start line, one row line per product, then an end line with count and totals. The dashboard renders the PDF from it. Treat a stream without the end line as incomplete.
- Limits: 250,000 rows, 1 MiB per row and 128 MiB in all; passing one ends the stream early. The whole export has a 10-minute ceiling.
- Needs the checkouts write scope (only the page query is classified as a read).

##### `POST /v1/checkouts/:shopId/products/page-v1/export`

**Scope** `checkouts.write` - **Export the product catalogue as CSV (one store)**

Streams the whole filtered catalogue of one store as a CSV file (products.csv) with the chosen columns.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store (shop) id of the account. Restricts the page to that one store; store-specific columns and totals are dropped. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "columns": [
    "title",
    "handle",
    "status",
    "price"
  ],
  "timezone": "Europe/Paris"
}
```

**Response** (text/csv;charset=utf-8)

```json
Product,Handle,Store,Status,On the store,Variants,Media,From,Updated
Example Hoodie,example-hoodie,Example store (shop.example.com),active,visible,3,2,$49.99,20-11-2026 10:00:00
Total,,1 stores,,,3,2,,
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Two exports are already running. Retry when one finishes."}` when this server process already streams two exports.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- Exports return the complete filtered population (no limit, offset ignored) as a stream; a failure after the first byte truncates the file instead of returning an error status.
- Exports need the checkouts write scope (only the page query is classified as a read).

##### `POST /v1/checkouts/:shopId/products/page-v1/query`

**Scope** `checkouts.read` - **Query one store's product catalogue (paged, filtered, sorted)**

Queries one store's product catalogue, paged, filtered and sorted, with totals; GET /v1/checkouts/:shopId/products returns it unpaged. Reads one page of the product catalogue of one store with filters, sort and favorites, plus the filtered and unfiltered totals.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store (shop) id of the account. Restricts the page to that one store; store-specific columns and totals are dropped. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "listing": [
    "visible"
  ],
  "sort": "updated_at",
  "dir": "desc",
  "limit": 50
}
```

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000101",
      "title": "Example Hoodie",
      "handle": "example-hoodie",
      "status": "active",
      "currency": "USD",
      "updated_at": "2026-11-20T10:00:00.000Z",
      "shop_id": "00000000-0000-4000-8000-000000000201",
      "store": {
        "id": "00000000-0000-4000-8000-000000000201",
        "name": "Example store",
        "domain": "shop.example.com",
        "cms": "shopify"
      },
      "linked": true,
      "link_active": true,
      "variants": 3,
      "media": 2,
      "min_price_cents": 4999,
      "image": "https://cdn.example.com/hoodie.jpg"
    }
  ],
  "total": 1,
  "totalUnfiltered": 12,
  "totals": {
    "stores": 1,
    "variants": 3,
    "media": 2
  },
  "stores": [
    {
      "id": "00000000-0000-4000-8000-000000000201",
      "name": "Example store",
      "domain": "shop.example.com",
      "cms": "shopify"
    }
  ],
  "offset": 0,
  "limit": 50
}
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- The page reads only stores the account can see; stores and favorites never widen access.
- rows[] are product rows per store membership (a product listed on two stores appears twice). min_price_cents is the lowest active variant price (else any variant); image is the first image URL.

##### `POST /v1/checkouts/:shopId/shopify/import`

**Scope** `checkouts.write` - **Import the Shopify catalogue**

Pull the store's products from its Shopify Admin API into Kontrol's own catalogue (never the legacy checkout's rows): products, variants and gallery media upserted, and one listing per product so the catalogue is listed on the store. Paginated through Shopify's Link header. Existing listings are left untouched, so a product the operator unlisted stays unlisted. Needs the store connected (read_products).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `since` | string\|null | no | ISO instant: only products Shopify changed after it (updated_at_min). Absent or null = full import. |

**Request body**

```json
{
  "since": "2026-09-26T00:00:00.000Z"
}
```

**Response**

```json
{
 "productsUpserted": 18,
 "variantsUpserted": 49,
 "mediaUpserted": 52,
 "listed": 18,
 "pagesFetched": 1,
 "errors": []
}
```

**Errors**

- `400` {"error":"since must be an ISO instant"}; {"error":"This store has no valid *.myshopify.com admin URL"}; {"error":"This store is not connected to Shopify yet - do that first"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).

**Gotchas**

- Never throws on a bad product: per-page and per-row failures come back in `errors` while everything else imports. A response with `productsUpserted: 0` and one error is a failed import; a response with both is a partial one.
- `listed` counts the shop_products rows this run CREATED, not the total listed on the store - a second import of the same catalogue answers 0.
- Shopify refusing with 401/403 means the token was revoked or lacks read_products; reconnect the store from the wizard.

##### `GET /v1/checkouts/medusa/catalog-jobs`

**Scope** `checkouts.read` - **List Medusa catalogue imports**

Lists up to 20 Medusa catalogue imports visible to the caller, active ones first, then newest first; optionally only those touching one store.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | string (uuid) | no | Only jobs with a target for this store, or still discovering with this store requested (or all stores). |

**Response**

```json
{
  "jobs": [
    {
      "id": "9d3e1b7a-2c4f-4e8a-b6d1-0a5c7e9f2b48",
      "origin": "manual",
      "status": "running",
      "phase": "work",
      "cancel_requested": false,
      "error": null,
      "request_id": "4a8c2e6f-1b3d-4f7a-9c5e-2d0b8a6f4c13",
      "created_at": "2026-11-20T14:00:00.000Z",
      "updated_at": "2026-11-20T14:00:31.000Z",
      "finished_at": null,
      "details_expired": false,
      "total": 2,
      "processed": 1,
      "failed": 0,
      "succeeded": 1,
      "skipped": 0,
      "products": 148,
      "pages": 3
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | At most 20 jobs. |
| `jobs[].id` | string (uuid) | Job id. |
| `jobs[].origin` | enum: manual \| scheduler | manual = created through this API or the dashboard; scheduler = the automatic sync. |
| `jobs[].status` | enum: queued \| running \| completed \| partial \| failed \| cancelled | Lifecycle status. |
| `jobs[].phase` | enum: discover \| work \| done | discover = listing the Medusa stores to import; work = importing pages; done = finished. |
| `jobs[].cancel_requested` | boolean | True once a cancel was requested. |
| `jobs[].error` | string \| null | Job-level failure reason. |
| `jobs[].request_id` | string (uuid) | The requestId sent at creation. |
| `jobs[].created_at` | string (ISO 8601) | Creation time. |
| `jobs[].updated_at` | string (ISO 8601) | Last change. |
| `jobs[].finished_at` | string \| null | End time. |
| `jobs[].details_expired` | boolean | True once the per-store details were pruned (90 days after the end); the counters below stay. |
| `jobs[].total` | integer | Stores in the job. |
| `jobs[].processed` | integer | Stores finished (any outcome). |
| `jobs[].failed` | integer | Stores that failed. |
| `jobs[].succeeded` | integer | Stores imported completely. |
| `jobs[].skipped` | integer | Stores cancelled before completion. |
| `jobs[].products` | integer | Products written so far, all stores. |
| `jobs[].pages` | integer | Catalogue pages fetched so far, all stores. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when shopId is not a uuid (zod validation of the query): one issue per problem with its `path`, the zod `code` and its `message`.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- No pagination.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `POST /v1/checkouts/medusa/catalog-jobs`

**Scope** `checkouts.write` - **Queue a Medusa catalogue import**

Queues a background import of the products, variants and media of the account's Medusa stores (one store, a selection, or all of them) and answers 202. Each store is read page by page from its saved Medusa connection; products no longer in Medusa are retired at the end. Follow it with GET /v1/checkouts/medusa/catalog-jobs/:id.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Your idempotency key. The same requestId with the same shopIds returns the existing job; with a different selection it answers 409. |
| `shopIds` | string[] (uuid) \| null; default `null` | no | Medusa stores of the account to import, 1 to 1000 ids (duplicates ignored). null or omitted = every Medusa store of the account (discovered by the worker). With exactly one id the store and its saved connection are checked before the job is accepted. |
| `shopIds[]` | string (uuid) | no | A store id (a Medusa store of the account). |

**Request body**

```json
{
  "requestId": "4a8c2e6f-1b3d-4f7a-9c5e-2d0b8a6f4c13",
  "shopIds": [
    "5b2e8d1c-7f4a-4c3e-9a6b-1d0f3e8c2a57"
  ]
}
```

**Response**

```json
{
  "jobId": "9d3e1b7a-2c4f-4e8a-b6d1-0a5c7e9f2b48",
  "job": {
    "id": "9d3e1b7a-2c4f-4e8a-b6d1-0a5c7e9f2b48",
    "status": "queued",
    "phase": "discover",
    "request_id": "4a8c2e6f-1b3d-4f7a-9c5e-2d0b8a6f4c13"
  },
  "queued": 0,
  "errors": []
}
```

| response field | type | description |
|---|---|---|
| `jobId` | string (uuid) | The job id. |
| `job` | object | {id, status, phase, request_id} of the job (HTTP 202). An existing job of the same requestId is returned with its current status. |
| `queued` | integer | Always 0 (stores are discovered by the worker). |
| `errors` | array | Always empty. |

**Errors**

- `400` {"error":"A stable requestId and valid store selection are required"} for an invalid body.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Administrator access required"}; {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed; {"error":"Store access changed"} or {"error":"Medusa integration is not enabled"} for a single selected store that is not the account's or when Medusa is off for the account.
- `404` {"error":"Medusa store not found"} for a single selected store that is not a Medusa store.
- `409` {"error":"Background Medusa imports are disabled"}; {"error":"This request ID belongs to a different selection"}; {"error":"An import is already running for this account"}; {"error":"Test and save the Medusa connection first"} or {"error":"Test and save a connection with storefront, region and supported currency first"} for a single selected store.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- Strict body: an unknown field is a 400.
- One running import per account: a second one answers 409 while any import of the account (any caller, or the scheduler) is not done.
- A store already owned by another running import is marked failed in this job ("Another import already owns this store; wait for its saved progress").
- No snapshot guarantee: pages committed before a cancel or a failure stay applied.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `GET /v1/checkouts/medusa/catalog-jobs/:id`

**Scope** `checkouts.read` - **Get a Medusa catalogue import**

Reads one import with its counters. Poll it until phase is done.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "9d3e1b7a-2c4f-4e8a-b6d1-0a5c7e9f2b48",
    "origin": "manual",
    "status": "running",
    "phase": "work",
    "cancel_requested": false,
    "error": null,
    "request_id": "4a8c2e6f-1b3d-4f7a-9c5e-2d0b8a6f4c13",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:31.000Z",
    "finished_at": null,
    "details_expired": false,
    "total": 2,
    "processed": 1,
    "failed": 0,
    "succeeded": 1,
    "skipped": 0,
    "products": 148,
    "pages": 3
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job. |
| `job.id` | string (uuid) | Job id. |
| `job.origin` | enum: manual \| scheduler | manual = created through this API or the dashboard; scheduler = the automatic sync. |
| `job.status` | enum: queued \| running \| completed \| partial \| failed \| cancelled | Lifecycle status. |
| `job.phase` | enum: discover \| work \| done | discover = listing the Medusa stores to import; work = importing pages; done = finished. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Job-level failure reason. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.details_expired` | boolean | True once the per-store details were pruned (90 days after the end); the counters below stay. |
| `job.total` | integer | Stores in the job. |
| `job.processed` | integer | Stores finished (any outcome). |
| `job.failed` | integer | Stores that failed. |
| `job.succeeded` | integer | Stores imported completely. |
| `job.skipped` | integer | Stores cancelled before completion. |
| `job.products` | integer | Products written so far, all stores. |
| `job.pages` | integer | Catalogue pages fetched so far, all stores. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the path id is not a uuid (zod validation; the issue path is empty): one issue per problem with its `path`, the zod `code` and its `message`.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `404` {"error":"Import not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- Counters are live counts until the job ends, then a saved summary.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `POST /v1/checkouts/medusa/catalog-jobs/:id/cancel`

**Scope** `checkouts.write` - **Cancel a Medusa catalogue import**

Cancels an import at once: every unfinished store becomes cancelled, worker claims are revoked and the job ends as cancelled. Pages already committed stay. A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "ok": true,
  "job": {
    "id": "9d3e1b7a-2c4f-4e8a-b6d1-0a5c7e9f2b48",
    "origin": "manual",
    "status": "cancelled",
    "phase": "done",
    "cancel_requested": true,
    "error": null,
    "request_id": "4a8c2e6f-1b3d-4f7a-9c5e-2d0b8a6f4c13",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:31.000Z",
    "finished_at": "2026-11-20T14:01:00.000Z",
    "details_expired": false,
    "total": 2,
    "processed": 2,
    "failed": 0,
    "succeeded": 1,
    "skipped": 1,
    "products": 148,
    "pages": 3
  }
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `job` | object | The job after cancellation. |
| `job.id` | string (uuid) | Job id. |
| `job.origin` | enum: manual \| scheduler | manual = created through this API or the dashboard; scheduler = the automatic sync. |
| `job.status` | enum: queued \| running \| completed \| partial \| failed \| cancelled | Lifecycle status. |
| `job.phase` | enum: discover \| work \| done | discover = listing the Medusa stores to import; work = importing pages; done = finished. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Job-level failure reason. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.details_expired` | boolean | True once the per-store details were pruned (90 days after the end); the counters below stay. |
| `job.total` | integer | Stores in the job. |
| `job.processed` | integer | Stores finished (any outcome). |
| `job.failed` | integer | Stores that failed. |
| `job.succeeded` | integer | Stores imported completely. |
| `job.skipped` | integer | Stores cancelled before completion. |
| `job.products` | integer | Products written so far, all stores. |
| `job.pages` | integer | Catalogue pages fetched so far, all stores. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the path id is not a uuid (zod validation; the issue path is empty): one issue per problem with its `path`, the zod `code` and its `message`.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `404` {"error":"Import not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- No body is read.
- No remote write happens on Medusa; only the local import stops.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `GET /v1/checkouts/medusa/catalog-jobs/:id/errors`

**Scope** `checkouts.read` - **List the errors of a Medusa import**

Reads the stores of one import that failed or were cancelled, with a safe reason, offset paginated.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer; default `0` | no | Rows to skip, 0 to 1000. |
| `limit` | integer; default `100` | no | Rows per page, 1 to 100. |

**Response**

```json
{
  "errors": [
    {
      "itemId": "Example Store",
      "reason": "Cancelled before this store completed"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `errors` | object[] | Failed or cancelled stores, ordered by target id. |
| `errors[].itemId` | string | The store name. |
| `errors[].reason` | string | The saved error, else "Cancelled before this store completed" or "Import failed". |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the path id is not a uuid, offset is outside 0-1000 or limit is outside 1-100 (zod validation; both are coerced from the query): one issue per problem with its `path`, the zod `code` and its `message`.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `404` {"error":"Import not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- offset above 1000 is refused (400, see errors); the list cannot be read past 1100 rows.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `GET /v1/checkouts/medusa/catalog-jobs/:id/targets`

**Scope** `checkouts.read` - **List the stores of a Medusa import**

Reads the per-store progress of one import, 100 stores per page (keyset pagination).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `after` | string (uuid) | no | The next value of the previous page; omit for the first page. |

**Response**

```json
{
  "targets": [
    {
      "id": "7c1e3a9b-5d2f-4b8e-a6c4-3f0d9b2e1a75",
      "shop_id": "5b2e8d1c-7f4a-4c3e-9a6b-1d0f3e8c2a57",
      "name": "Example Store",
      "status": "running",
      "phase": "fetch",
      "cursor_offset": 100,
      "expected_count": 240,
      "pages": 2,
      "products": 100,
      "variants": 310,
      "media": 180,
      "listed": 100,
      "warnings": 0,
      "retired": 0,
      "error": null,
      "updated_at": "2026-11-20T14:00:31.000Z"
    }
  ],
  "next": null
}
```

| response field | type | description |
|---|---|---|
| `targets` | object[] | Up to 100 stores of the job, ordered by target id. |
| `targets[].id` | string (uuid) | Target id (use as after). |
| `targets[].shop_id` | string (uuid) | Store id. |
| `targets[].name` | string | Store name. |
| `targets[].status` | enum: queued \| running \| completed \| failed \| cancelled | Store status. |
| `targets[].phase` | enum: fetch \| retire \| done | fetch = reading pages; retire = retiring products no longer in Medusa; done. |
| `targets[].cursor_offset` | integer | Next Medusa offset to read. |
| `targets[].expected_count` | integer \| null | Product count reported by Medusa. |
| `targets[].pages` | integer | Pages fetched. |
| `targets[].products` | integer | Products written. |
| `targets[].variants` | integer | Variants written. |
| `targets[].media` | integer | Media written. |
| `targets[].listed` | integer | Products listed by Medusa so far. |
| `targets[].warnings` | integer | Items skipped with a warning. |
| `targets[].retired` | integer | Products retired. |
| `targets[].error` | string \| null | Store failure reason. |
| `targets[].updated_at` | string (ISO 8601) | Last change. |
| `next` | string (uuid) \| null | Pass as after to read the next page; null on the last page. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the path id or the after query value is not a uuid (zod validation): one issue per problem with its `path`, the zod `code` and its `message`.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `404` {"error":"Import not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- After details_expired becomes true (90 days after the end) the list is empty.
- A job is visible to the caller that created it (the same API key or login, with the same ATRI grants); scheduler jobs of the account are visible to every caller without an ATRI restriction (an API key has none). A job created by another key answers 404.

##### `GET /v1/checkouts/medusa/catalog-jobs/capability`

**Scope** `checkouts.read` - **Medusa catalogue job capability**

Says whether background Medusa catalogue imports can be queued on this deployment (POST /v1/checkouts/medusa/catalog-jobs). Also re-checks the caller's access to the account.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | True when the Medusa integration and background jobs are enabled on the deployment. It does not say whether Medusa is enabled for this account or whether a store is connected. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"} when the account owner is banned or no longer an owner; {"error":"API key access changed"} when the key was deactivated or changed account; {"error":"Account permissions changed"} when the account's ATRI grants changed.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second control budget is exceeded.

**Gotchas**

- enabled:true is not a promise that a job will succeed: each store still needs a tested, saved Medusa connection.

##### `POST /v1/checkouts/medusa/sync-all`

**Scope** `checkouts.write` - **Queue visible Medusa stores**

Queue one durable catalogue import over every Medusa store of the caller's account. Answers 202 with the job; repeating the same requestId returns the same job.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key of the run. Strict body: requestId only. |

**Request body**

```json
{
 "requestId": "33333333-3333-4333-8333-333333333333"
}
```

**Response** `202`

```json
{
 "jobId": "44444444-4444-4444-8444-444444444444",
 "job": {
  "id": "44444444-4444-4444-8444-444444444444",
  "status": "queued",
  "phase": "queued",
  "request_id": "33333333-3333-4333-8333-333333333333"
 },
 "queued": 0,
 "errors": []
}
```

**Errors**

- `400` {"error":"A stable requestId and valid store selection are required"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `409` {"error":"Background Medusa imports are disabled"}; {"error":"This request ID belongs to a different selection"}; {"error":"An import is already running for this account"} (with jobId)
- `500` Internal Server Error with a requestId (unexpected server or database failure).

##### `GET /v1/checkouts/products`

**Scope** `checkouts.read` - **List every product across the account's stores (unpaged)**

Lists every product across the account's stores in one unpaged answer (one row per product and store); POST /v1/checkouts/products/page-v1/query is the paged, filtered and sorted query. Cross-store catalogue view: one row per (product, store) pair for every store of the account that has a copy in Kontrol's catalogue database. A product owned by one store and listed on two others appears once per store, each row with its own store object. Read-only.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "title": "Posture Corrector Pro",
      "handle": "posture-corrector-pro",
      "status": "active",
      "currency": "USD",
      "updated_at": "2026-09-17T12:30:00.000Z",
      "shop_id": "4697ca72-0000-4000-8000-00000000a001",
      "variants": 3,
      "media": 5,
      "min_price_cents": 3990,
      "image": "https://cdn.example.com/products/7d0a2c14/img-0.jpg",
      "linked": true,
      "link_active": true,
      "store": {
        "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
        "name": "Example US",
        "domain": "shop.example.com",
        "cms": "product"
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].shop_id` | uuid\|null | The store that OWNS the product in the catalogue database. It can differ from rows[].store.id when the product is only listed on that store, and for older stores it is the catalogue database's own ID of the store. |
| `rows[].linked` | boolean | A listing link exists between the product and rows[].store. |
| `rows[].link_active` | boolean | That listing is active, meaning the product is listed on the store. |
| `rows[].variants / rows[].media` | integer | Number of variants (active or not) and of media. |
| `rows[].min_price_cents` | integer\|null | Lowest price among active variants, falling back to a variant's price when none is active; null when the product has no variant. Integer cents in the product currency. |
| `rows[].image` | string\|null | URL of the first image media by position. |
| `rows[].store` | object | id (the store ID used by every store route), name (internal_name), domain and cms of the store this row is for. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module products): the plan lacks the products module.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- Sorted by updated_at descending across all stores; no pagination.
- The same product id can appear several times, once per store it belongs to or is listed on. De-duplicate on id for the catalogue itself.
- A store that has no copy in Kontrol's catalogue database yet contributes no rows.

##### `POST /v1/checkouts/products/export-pdf-v2`

**Scope** `checkouts.write` - **Stream the product catalogue for a PDF**

Streams the whole filtered catalogue of every store as NDJSON records, the source the dashboard turns into a PDF.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "columns": [
    "title",
    "handle",
    "status",
    "price"
  ],
  "timezone": "Europe/Paris"
}
```

**Response** (application/x-ndjson)

```json
{"type":"start","version":2}
{"type":"row","row":{"id":"00000000-0000-4000-8000-000000000101","title":"Example Hoodie","handle":"example-hoodie","status":"active","currency":"USD","variants":3,"media":2,"min_price_cents":4999}}
{"type":"end","version":2,"count":1,"totals":{"stores":1,"variants":3,"media":2}}
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Two exports are already running. Retry when one finishes."}` when this server process already streams two exports.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- Despite the name the answer is NDJSON (application/x-ndjson), not a PDF: one start line, one row line per product, then an end line with count and totals. The dashboard renders the PDF from it. Treat a stream without the end line as incomplete.
- Limits: 250,000 rows, 1 MiB per row and 128 MiB in all; passing one ends the stream early. The whole export has a 10-minute ceiling.
- Needs the checkouts write scope (only the page query is classified as a read).

##### `POST /v1/checkouts/products/page-v1/export`

**Scope** `checkouts.write` - **Export the product catalogue as CSV**

Streams the whole filtered catalogue of every store as a CSV file (products.csv) with the chosen columns, ending with a Total row when store, variants or media is exported.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "columns": [
    "title",
    "handle",
    "status",
    "price"
  ],
  "timezone": "Europe/Paris"
}
```

**Response** (text/csv;charset=utf-8)

```json
Product,Handle,Store,Status,On the store,Variants,Media,From,Updated
Example Hoodie,example-hoodie,Example store (shop.example.com),active,visible,3,2,$49.99,20-11-2026 10:00:00
Total,,1 stores,,,3,2,,
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Two exports are already running. Retry when one finishes."}` when this server process already streams two exports.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- Exports return the complete filtered population (no limit, offset ignored) as a stream; a failure after the first byte truncates the file instead of returning an error status.
- Exports need the checkouts write scope (only the page query is classified as a read).

##### `POST /v1/checkouts/products/page-v1/query`

**Scope** `checkouts.read` - **Query the product catalogue across stores (paged, filtered, sorted)**

Queries the product catalogue across every store of the account, paged, filtered and sorted, with totals; GET /v1/checkouts/products returns the whole list unpaged. Reads one page of the product catalogue across every store of the account with filters, sort and favorites, plus the filtered and unfiltered totals.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0-10000000); default `0` | no | Rows to skip. |
| `limit` | integer (1-250); default `50` | no | Page size (query only; exports return every filtered row). |
| `q` | string (0-300); default `""` | no | Case-insensitive substring of title + handle (and store name + domain on the all-stores routes). |
| `stores` | uuid[] (max 1000); default `[]` | no | Restrict to these store ids (only stores the account can see count). Empty = all. |
| `status` | array of enum: draft \| active \| archived (max 3); default `[]` | no | Product status filter. Empty = all. |
| `listing` | array of enum: visible \| hidden \| unlisted (max 3); default `[]` | no | On-the-store filter: visible (linked and active), hidden (linked, inactive), unlisted (not linked to the store). Empty = all. |
| `favorites` | string[] (max 300, each max 300); default `[]` | no | Favorite keys (lower-cased handle, or name:<lower-cased title>) sorted first. Display preference only. |
| `sort` | enum: image \| title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at; default `title` | no | Sort key (text sorts are bytewise lower-case; ties by id then store). |
| `dir` | enum: asc \| desc; default `asc` | no | Sort direction. |
| `columns` | array of enum: title \| handle \| store \| status \| listing \| variants \| media \| price \| updated_at (1-9) | no | Export columns, in order (CSV header labels: Product, Handle, Store, Status, On the store, Variants, Media, From, Updated). Accepted on every route, used by the exports. Default: title, handle, store (all-stores only), status, listing, variants, media, price, updated_at; handle is always added on the all-stores routes. |
| `timezone` | string (IANA zone, max 80); default `UTC` | no | Timezone of the CSV Updated column (DD-MM-YYYY HH:MM:SS). |

**Request body**

```json
{
  "q": "hoodie",
  "status": [
    "active"
  ],
  "listing": [
    "visible"
  ],
  "sort": "updated_at",
  "dir": "desc",
  "limit": 50
}
```

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000101",
      "title": "Example Hoodie",
      "handle": "example-hoodie",
      "status": "active",
      "currency": "USD",
      "updated_at": "2026-11-20T10:00:00.000Z",
      "shop_id": "00000000-0000-4000-8000-000000000201",
      "store": {
        "id": "00000000-0000-4000-8000-000000000201",
        "name": "Example store",
        "domain": "shop.example.com",
        "cms": "shopify"
      },
      "linked": true,
      "link_active": true,
      "variants": 3,
      "media": 2,
      "min_price_cents": 4999,
      "image": "https://cdn.example.com/hoodie.jpg"
    }
  ],
  "total": 1,
  "totalUnfiltered": 12,
  "totals": {
    "stores": 1,
    "variants": 3,
    "media": 2
  },
  "stores": [
    {
      "id": "00000000-0000-4000-8000-000000000201",
      "name": "Example store",
      "domain": "shop.example.com",
      "cms": "shopify"
    }
  ],
  "offset": 0,
  "limit": 50
}
```

**Errors**

- `400` `{"error":"Invalid catalogue query","details":{...}}` when the body fails the schema (strict: unknown fields refused), `{"error":"Invalid timezone"}`, or `{"error":"Invalid store"}` when :shopId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `404` `{"error":"Catalog paging is unavailable"}` when this deployment has no local checkout database (see GET /v1/checkouts/products/paging-capabilities); `{"error":"Checkout not found"}` when :shopId is not a store of the account.
- `413` Body larger than 128 KiB.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the store lookup or the page read passes its 15-second budget.

**Gotchas**

- The page reads only stores the account can see; stores and favorites never widen access.
- rows[] are product rows per store membership (a product listed on two stores appears twice). min_price_cents is the lowest active variant price (else any variant); image is the first image URL.

##### `GET /v1/checkouts/products/paging-capabilities`

**Scope** `checkouts.read` - **Read catalogue paging availability**

Says whether the server-side catalogue page, CSV export and PDF source routes are available on this deployment (they need the local checkout database). Version 1 contract, sent with cache-control: no-store.

*No parameters.*

**Response**

```json
{
  "version": 1,
  "enabled": true
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"}` when the account's plan does not include the products module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- When enabled is false, every catalogue page and export route answers 404 `Catalog paging is unavailable`.

##### `GET /v1/checkouts/shopify/job-capabilities`

**Scope** `checkouts.read` - **Read background Shopify import availability**

Tell whether background Shopify catalogue imports can be admitted now: true when background workers run and the import storage exists.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Required storage for Shopify catalog jobs is unavailable. Complete the current database migrations.","requestId":"<id>"} (Retry-After: 1) when background workers are on but the import storage is not migrated.

**Gotchas**

- enabled false means POST /v1/checkouts/shopify/jobs answers 503; reading and cancelling existing jobs still work.

##### `GET /v1/checkouts/shopify/jobs`

**Scope** `checkouts.read` - **List Shopify catalogue import progress**

List the 25 most recent Shopify catalogue imports visible to the caller (active first, then newest), with per-job counters. Scheduler-created imports are included when every target store is still visible to the account. No product payloads or credentials are returned.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "request_id": "00000000-0000-4000-8000-000000000001",
      "status": "running",
      "origin": "manual",
      "since_at": null,
      "cancel_requested": false,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:01:00.000Z",
      "finished_at": null,
      "stores": 2,
      "processed": 1,
      "failed": 0,
      "pages": 6,
      "products": 1240,
      "variants": 3810,
      "media": 2950
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[].id` | uuid | Import job id. |
| `jobs[].request_id` | uuid | Idempotency key it was created with. |
| `jobs[].status` | string | queued, running, completed, partial, failed or cancelled. |
| `jobs[].origin` | string | manual (an admission) or scheduler (the automatic sync). |
| `jobs[].since_at` | timestamp\|null | The since filter of the import. |
| `jobs[].cancel_requested` | boolean | true once a cancel was requested. |
| `jobs[].created_at / updated_at / finished_at` | timestamp | Lifecycle timestamps. |
| `jobs[].stores / processed / failed` | integer | Target stores, stores finished (completed, failed or cancelled), stores failed. |
| `jobs[].pages / products / variants / media` | integer | Totals imported so far across the stores. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed while the request ran: "Import API key or account access changed", "Import account no longer has access", "Import account or role changed", "Import permissions changed", "Store ownership or access changed", "Store mapping changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Returns {"jobs":[]} when the import storage is not migrated. Jobs are visible to the caller that created them (same key or user and same permission snapshot) plus visible scheduler jobs.

##### `POST /v1/checkouts/shopify/jobs`

**Scope** `checkouts.write` - **Queue a Shopify catalogue import**

Queue a background import of the Shopify catalogue (products, variants, media) into the local copy of one or more of the account's Shopify stores. Returns 202 with the job id; follow it with the job detail endpoint.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key per account and caller. Same id with the same stores and since returns the existing job; with different parameters, 409. |
| `storeIds` | uuid[] \| null | **yes** | 1..1000 store ids (Shopify stores of the account, as listed by GET /v1/checkouts). null = every visible Shopify store of the account. The key is required: send null explicitly. |
| `since` | ISO 8601 UTC datetime \| null | **yes** | Import only products updated at or after this instant (for example 2026-11-01T00:00:00Z; an offset is refused). null = the full catalogue. The key is required. |

**Request body**

```json
{
  "requestId": "00000000-0000-4000-8000-000000000001",
  "storeIds": null,
  "since": null
}
```

**Response** `202`

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000002",
    "request_id": "00000000-0000-4000-8000-000000000001",
    "status": "queued"
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Import job id. |
| `job.request_id` | uuid | Idempotency key it was created with. |
| `job.status` | string | queued, running, completed, partial, failed or cancelled. |

**Errors**

- `400` {"error":"Invalid import parameters"} (body shape), {"error":"Choose between 1 and 1000 Shopify stores"} (none visible or too many), {"error":"Choose between 1 and 1000 connected stores"} or {"error":"Duplicate store"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed while the request ran: "Import API key or account access changed", "Import account no longer has access", "Import account or role changed", "Import permissions changed", "Store ownership or access changed", "Store mapping changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan does not include that module.
- `404` {"error":"Shopify store not found"}: a storeIds entry is not a visible Shopify store of the account.
- `409` {"error":"Request ID was already used with different parameters"}, {"error":"One of these stores is currently importing"}, {"error":"One of these stores already has an active catalogue import. Wait or cancel it."}, {"error":"Three catalogue imports are already active for this account"}, or "No unambiguous local copy for <store>; save the store before importing".
- `413` Body larger than 64 KiB.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Background catalogue imports are unavailable"}: background workers are off. {"error":"Required storage for Shopify catalog jobs is unavailable. Complete the current database migrations.","requestId":"<id>"} (Retry-After: 1) when workers are on but the import storage is not migrated.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` The admission transaction ran past its deadline; retry with the same requestId.

**Gotchas**

- Imports write the local catalogue only (products, variants, media of the stores). Shopify credentials are resolved when the job runs and never stored in the job. A page holds at most 250 products and 8 MiB; one store import stops after 100 pages. Job metadata is kept 30 days.
- At most three active imports per account and one active import per store. The body is strict (unknown keys answer 400) and limited to 64 KiB.

##### `GET /v1/checkouts/shopify/jobs/:jobId`

**Scope** `checkouts.read` - **Read Shopify catalogue import details**

Read one Shopify catalogue import with its per-store items (status, pages, products, variants, media, listed, error).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Import job id from the create or list endpoint. A non-uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000002",
    "request_id": "00000000-0000-4000-8000-000000000001",
    "status": "partial",
    "origin": "manual",
    "since_at": null,
    "cancel_requested": false,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:09:00.000Z",
    "finished_at": "2026-11-20T10:09:00.000Z",
    "items": [
      {
        "id": "00000000-0000-4000-8000-000000000003",
        "shop_id": "00000000-0000-4000-8000-000000000004",
        "name": "Example Store",
        "status": "completed",
        "pages": 4,
        "products": 800,
        "variants": 2400,
        "media": 1900,
        "listed": 800,
        "error": null
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Import job id. |
| `job.request_id` | uuid | Idempotency key it was created with. |
| `job.status` | string | queued, running, completed, partial, failed or cancelled. |
| `job.origin` | string | manual (an admission) or scheduler (the automatic sync). |
| `job.since_at` | timestamp\|null | The since filter of the import. |
| `job.cancel_requested` | boolean | true once a cancel was requested. |
| `job.created_at / updated_at / finished_at` | timestamp | Lifecycle timestamps. |
| `job.items[]` | object[] | One per target store: id, shop_id, name, status (queued, running, completed, failed, cancelled), pages, products, variants, media, listed, error. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed while the request ran: "Import API key or account access changed", "Import account no longer has access", "Import account or role changed", "Import permissions changed", "Store ownership or access changed", "Store mapping changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan does not include that module.
- `404` {"error":"Not found"} (jobId not a uuid) or {"error":"Import not found or permissions changed"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Status partial = some stores completed and some failed. Another account's job, or a job created under a different permission snapshot, answers 404.

##### `POST /v1/checkouts/shopify/jobs/:jobId/cancel`

**Scope** `checkouts.write` - **Cancel a Shopify catalogue import**

Cooperatively cancel a queued or running Shopify catalogue import: pending store items are cancelled and their unapplied staged pages dropped; pages already committed stay. Returns the job detail. A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Import job id. A non-uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000002",
    "status": "cancelled",
    "cancel_requested": true,
    "items": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | Same shape as the job detail. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed while the request ran: "Import API key or account access changed", "Import account no longer has access", "Import account or role changed", "Import permissions changed", "Store ownership or access changed", "Store mapping changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan does not include that module.
- `404` {"error":"Not found"} (jobId not a uuid) or {"error":"Import not found or permissions changed"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A store item already running finishes its current page before stopping. Cancelling a scheduler job requires every target store to be visible to the account; otherwise 404.
- Works even when background imports are disabled.

##### `POST /v1/checkouts/shopify/sync-all`

**Scope** `checkouts.write` - **Resync every connected Shopify catalogue**

Resync the catalogue of every connected Shopify store of the caller's account into Kontrol's own catalogue, one store after another, inside this request. A store that is not cms shopify, has no admin URL or is not connected is skipped, not failed; one store's failure never stops the next, and the answer carries a line per store.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `since` | string\|null | no | ISO instant: only products Shopify changed after it (a light pass). Absent or null = full catalogue. |

**Request body**

```json
{
 "since": null
}
```

**Response** `200`

```json
{
 "stores": [
  {
   "shopId": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "name": "Example US",
   "domain": "pay.shop.example.com",
   "ok": true,
   "productsUpserted": 12,
   "variantsUpserted": 31,
   "mediaUpserted": 40,
   "listed": 0
  }
 ],
 "synced": 1,
 "skipped": 2,
 "productsUpserted": 12,
 "variantsUpserted": 31,
 "mediaUpserted": 40,
 "errors": []
}
```

| response field | type | description |
|---|---|---|
| `stores[]` | object[] | { shopId, name, domain, ok, productsUpserted, variantsUpserted, mediaUpserted, listed, error? } per store touched. |
| `synced / skipped` | integer | Stores synced (including failed ones) and skipped. |
| `productsUpserted / variantsUpserted / mediaUpserted` | integer | Totals over the stores. |
| `errors[]` | string[] | One "<store name>: <reason>" per store that failed or could not be resolved. |

**Errors**

- `400` {"error":"since must be an ISO instant"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- A 200 with a non-empty errors is a partial pass, not a success.
- A store with no copy in Kontrol's database yet is reported in errors ("<name>: <reason>") and not synced.
- Runs synchronously: a large account can take a while; Shopify rate-limits per store.

##### `POST /v1/v5/catalog/products`

**Scope** `checkouts.write` - **Create an account catalogue product**

Creates a product owned by the account catalogue itself (no store needed) with its options, variant matrix, media, quantity tiers, bundle components and page settings, in one transaction. requestKey makes the call replay-safe: the same key with the same product returns the product created the first time; the same key with a different product is refused (409). Use the returned product and variant ids in page offers (PUT /v1/v5/funnels/:id/document/draft).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestKey` | string | **yes** | Replay key, 1-100 characters matching ^[a-zA-Z0-9][a-zA-Z0-9:_-]{0,99}$. Store it before calling and resend it with the identical product after an uncertain outcome. |
| `product` | object | **yes** | The product. Strict object: an unknown key is refused (400). Every product.* field is optional unless stated. |
| `product.title` | string | no | 1-300 characters, trimmed. Needed in practice: when both title and handle are blank the route answers 400 Enter a product title and handle. |
| `product.handle` | string | no | 1-80 characters, slugified (lowercase a-z, 0-9 and hyphens, at most 60). Defaults to the slug of title. A handle already used in the account catalogue gets -2, -3 ... appended (after 1000 tries: 409 Choose a different product handle). |
| `product.status` | enum | no | draft, active or archived. Default draft: send active to sell the product. |
| `product.currency` | string | no | Three letters (^[A-Za-z]{3}$), stored uppercase. Default USD. |
| `product.subtitle` | string \| null | no | At most 300 characters. |
| `product.vendor` | string \| null | no | At most 120 characters. |
| `product.product_type` | string \| null | no | At most 120 characters. |
| `product.tags` | string[] | no | At most 50 tags of at most 60 characters. Default []. |
| `product.description` | string | no | At most 100000 characters. Default empty. |
| `product.seo_title` | string \| null | no | At most 200 characters. |
| `product.seo_description` | string \| null | no | At most 500 characters. |
| `product.gift_banner_text` | string \| null | no | At most 300 characters. |
| `product.scarcity_text` | string \| null | no | At most 300 characters. |
| `product.social_proof_text` | string \| null | no | At most 300 characters. |
| `product.rating_value` | number \| null | no | 0 to 5. |
| `product.rating_count` | integer | no | 0 or more. |
| `product.subscription_product_id` | uuid \| null | no | Must be absent or null: a value answers 422 Bind subscription plans explicitly in the page offer. Subscription plans are bound on the published page offer instead. |
| `product.price_cents` | integer | no | 0-2147483647, minor units. Unit price of every matrix variant that has no explicit variants entry; 0 when omitted. |
| `product.compare_at_price_cents` | integer \| null | no | 0-2147483647. Compare-at price of matrix variants without an explicit entry; default null. |
| `product.sku` | string | no | At most 120 characters. SKU of matrix variants without an explicit entry; default empty. |
| `product.inventory_qty` | integer \| null | no | Inventory of matrix variants without an explicit entry; null (default) means untracked. |
| `product.is_active` | boolean | no | Accepted and ignored for account catalogue products (it only sets the store link on the store product routes). |
| `product.options` | object[] | no | At most 2 option axes. The matrix (product of the value counts) may not exceed 200 variants (400). Omit for a single default variant. |
| `product.options[].name` | string | **yes** | 1-60 characters. |
| `product.options[].display_type` | enum; default `button` | no | button or image-swatch. |
| `product.options[].values` | object[] | **yes** | 1-50 values; value strings must be unique within the option (400 Option values must be unique). |
| `product.options[].values[].value` | string | **yes** | 1-80 characters. |
| `product.options[].values[].swatch_image_url` | string \| null | no | At most 2048 characters. |
| `product.options[].values[].swatch_hex` | string \| null | no | At most 16 characters, for example #1f2937. |
| `product.variants` | object[] | no | At most 200 explicit variant values, each matched to one matrix combination by option_values. Supply options too whenever option_values name values (400 Variant option_values must match the declared options in order). |
| `product.variants[].option_values` | string[] | no | One value per declared option, in option order (max 2, default []); no two entries with the same combination (400 Duplicate variant combination). |
| `product.variants[].price_cents` | integer | **yes** | 0 or more, minor units. Required in every variants entry. |
| `product.variants[].compare_at_price_cents` | integer \| null; default `null` | no | 0 or more. |
| `product.variants[].sku` | string | no | At most 120 characters. |
| `product.variants[].cost_cents` | integer \| null | no | 0 or more. |
| `product.variants[].weight_grams` | integer \| null | no | 0 or more. |
| `product.variants[].barcode` | string \| null | no | At most 80 characters. |
| `product.variants[].inventory_qty` | integer \| null; default `null` | no | null means untracked. |
| `product.variants[].is_active` | boolean; default `true` | no | Inactive variants cannot be sold. |
| `product.variants[].image_url` | string | no | At most 2048 characters. |
| `product.media` | object[] | no | At most 100 items, kept in order. URLs are stored as given (not re-hosted). |
| `product.media[].url` | string | **yes** | HTTP(S) URL, at most 2048 characters (400 Use an HTTP(S) media URL). |
| `product.media[].alt` | string \| null | no | At most 300 characters. |
| `product.media[].kind` | enum; default `image` | no | image or video. |
| `product.tiers` | object[] | no | Quantity price tiers, at most 50, min_quantity unique (400 Each quantity threshold must be unique). |
| `product.tiers[].min_quantity` | integer | **yes** | 1 or more. |
| `product.tiers[].extra_off_cents` | integer; default `0` | no | 0 or more, minor units off. |
| `product.tiers[].discount_pct` | number; default `0` | no | 0 to 100. |
| `product.tiers[].label` | string \| null; default `null` | no | At most 120 characters. |
| `product.tiers[].badge` | string \| null; default `null` | no | At most 60 characters. |
| `product.tiers[].unit_price_cents` | integer \| null | no | Legacy fixed unit price, 0 or more. |
| `product.bundle` | object[] | no | Bundle components, at most 50. Each component variant must belong to a product of this account catalogue (422 Bundle components must belong to this store). |
| `product.bundle[].component_variant_id` | uuid | **yes** | Variant UUID of an account catalogue product. |
| `product.bundle[].quantity` | integer; default `1` | no | 1 or more. |
| `product.bundle[].is_gift` | boolean; default `false` | no | Component offered as a gift. |
| `product.bundle[].price_override_cents` | integer \| null; default `null` | no | 0 or more. |
| `product.specs` | object[] | no | At most 100 specification rows. |
| `product.specs[].label` | string | **yes** | 1-120 characters. |
| `product.specs[].value` | string | **yes** | 1-1000 characters. |
| `product.sections` | object[] | no | Validated (at most 30 items of {id?, type, enabled, position?, props}; type info_tabs, logos_carousel, ugc_videos, rich_section, reviews, faq or customization) and then ignored: account catalogue products are created with no page sections. |
| `product.page_config` | object | no | Strict product page settings, every key optional with editor defaults: subBar{enabled,label,text}, banner{enabled,text,highlight}, freeGift{enabled,subtitle,image}, priceBlock{showCompareAt,showSaveTag}, bundles{title,countdown{enabled,minutes},stickPrices}, salesPoints{enabled,items[{bold,text}] max 20}, buyButton{label,showPrice}, trustBadges{enabled,items[{label,icon}] max 12}, stickyBar{enabled,label}, cartDrawer{title,checkoutLabel,continueLabel,freeShippingBar{enabled,text},giftBadge{enabled}}, overstock{enabled,unitsLeft,unitsTotal}, lightbox{enabled}, preOrder{enabled}. An unknown key is refused (400). |

**Request body**

```json
{
  "requestKey": "funnel-travel-kit-v1",
  "product": {
    "title": "Travel kit",
    "handle": "travel-kit",
    "status": "active",
    "currency": "USD",
    "price_cents": 2995,
    "options": [
      {
        "name": "Size",
        "display_type": "button",
        "values": [
          {
            "value": "M"
          },
          {
            "value": "L"
          }
        ]
      }
    ],
    "variants": [
      {
        "option_values": [
          "M"
        ],
        "price_cents": 2995,
        "sku": "KIT-M"
      },
      {
        "option_values": [
          "L"
        ],
        "price_cents": 3495,
        "sku": "KIT-L"
      }
    ],
    "media": [
      {
        "url": "https://assets.example.com/kit-m.webp",
        "alt": "Travel kit",
        "kind": "image"
      }
    ]
  }
}
```

**Response** `200`

```json
{
  "product": {
    "id": "00000000-0000-4000-8000-000000000001",
    "shop_id": null,
    "title": "Travel kit",
    "handle": "travel-kit",
    "status": "active",
    "currency": "USD",
    "subtitle": null,
    "vendor": null,
    "product_type": null,
    "tags": [],
    "description": "",
    "seo_title": null,
    "seo_description": null,
    "rating_value": null,
    "rating_count": 0,
    "catalog_account_id": "acc_0123456789abcdef",
    "created_at": "2026-11-16T12:00:00.123456+00:00",
    "updated_at": "2026-11-16T12:00:00.123456+00:00"
  },
  "variants": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "title": "M",
      "sku": "KIT-M",
      "price_cents": 2995,
      "compare_at_price_cents": null,
      "is_active": true,
      "image_url": "",
      "position": 0
    },
    {
      "id": "00000000-0000-4000-8000-000000000003",
      "title": "L",
      "sku": "KIT-L",
      "price_cents": 3495,
      "compare_at_price_cents": null,
      "is_active": true,
      "image_url": "",
      "position": 1
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `product` | object | The stored products row (id, title, handle, status, currency, descriptive fields, catalog_account_id, created_at, updated_at...). Keep updated_at: it is the baseUpdatedAt of the next PATCH. |
| `variants[]` | object[] | Every variant of the matrix: id, title, sku, price_cents, compare_at_price_cents, is_active, image_url, position. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: the body fails the strict schema (unknown key, bad requestKey, bounds, option values not unique, more than 200 variants, variant option_values not matching the options, duplicate combination).
- `400` {"error":"Enter a product title and handle."}: title and handle are both blank.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"} when the plan excludes the products tool.
- `409` {"error":"This product creation key was used with different content"}: the requestKey already created a different product.
- `409` {"error":"Choose a different product handle"}: the handle and its 1000 numbered variants are all taken.
- `413` {"error":"Request body is too large"}: the JSON body is over 2 MiB.
- `422` {"error":"Bind subscription plans explicitly in the page offer."}: product.subscription_product_id was set.
- `422` {"error":"Bundle components must belong to this store"}: a bundle component variant is not in this account catalogue.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Money fields are integer minor units. A variant is not a second product: reuse the returned product and variant ids in page offers.
- A matrix variant without an explicit variants entry is priced at product.price_cents, which is 0 when omitted. Send price_cents or one variants entry per combination.
- status defaults to draft. Offers need an active product with active variants, so send status active when the product is meant to be sold.
- Replay: the same requestKey with the same product (compared after validation) answers 200 with the product created the first time and creates nothing.
- Creating a product publishes no page and starts no payment. The body limit of this route is 2 MiB.
- The account comes from the credential; no request field can select another account.

##### `GET /v1/v5/catalog/products/:id`

**Scope** `checkouts.read` - **Read an account catalogue product**

Reads one product of the account catalogue with its options and values, variants, media, quantity tiers, bundle items, reviews, translations and store links. Products created through a store are not account catalogue products and answer 404 here; read them with the store product routes.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account catalogue product UUID (product.id from POST /v1/v5/catalog/products). |

**Response** `200`

```json
{
  "product": {
    "id": "00000000-0000-4000-8000-000000000001",
    "shop_id": null,
    "title": "Travel kit",
    "handle": "travel-kit",
    "status": "active",
    "currency": "USD",
    "subtitle": null,
    "vendor": null,
    "product_type": null,
    "tags": [],
    "description": "",
    "seo_title": null,
    "seo_description": null,
    "rating_value": null,
    "rating_count": 0,
    "catalog_account_id": "acc_0123456789abcdef",
    "created_at": "2026-11-16T12:00:00.123456+00:00",
    "updated_at": "2026-11-16T12:00:00.123456+00:00"
  },
  "options": [
    {
      "id": "00000000-0000-4000-8000-000000000003",
      "name": "Size",
      "position": 0,
      "display_type": "button",
      "values": [
        {
          "id": "00000000-0000-4000-8000-000000000004",
          "option_id": "00000000-0000-4000-8000-000000000003",
          "value": "M",
          "position": 0,
          "swatch_hex": null,
          "swatch_image_url": null
        }
      ]
    }
  ],
  "variants": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "product_id": "00000000-0000-4000-8000-000000000001",
      "title": "M",
      "sku": "KIT-M",
      "price_cents": 2995,
      "compare_at_price_cents": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "",
      "position": 0
    }
  ],
  "media": [
    {
      "id": "00000000-0000-4000-8000-000000000005",
      "product_id": "00000000-0000-4000-8000-000000000001",
      "url": "https://assets.example.com/kit-m.webp",
      "alt": "Travel kit",
      "kind": "image",
      "position": 0
    }
  ],
  "tiers": [],
  "bundle": [],
  "reviews": [],
  "translations": [],
  "shops": []
}
```

| response field | type | description |
|---|---|---|
| `product` | object | The products row; product.updated_at is the exact baseUpdatedAt to send on PATCH. |
| `options[]` | object[] | id, name, position, display_type and values[] (id, option_id, value, position, swatch_hex, swatch_image_url). |
| `variants[]` | object[] | Full product_variants rows, ordered by position. |
| `media[] / tiers[] / bundle[] / reviews[]` | object[] | Full rows of each list, ordered by position (reviews newest first). |
| `translations[]` | object[] | id, locale, model, updated_at of each stored translation. |
| `shops[]` | object[] | Store links: shop_id, is_active, position, price_override_cents. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"} when the plan excludes the products tool.
- `404` {"error":"Account catalogue product not found."}: unknown id, another account's product, or a store-owned product.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The account comes from the credential; no request field can select another account.

##### `PATCH /v1/v5/catalog/products/:id`

**Scope** `checkouts.write` - **Update an account catalogue product**

Updates the metadata, options, variant prices and media of an account catalogue product under a row lock, guarded by the exact updated_at you last read. Variant ids and store links survive; removed combinations are deactivated. Store pages showing the product are revalidated after the commit. Returns the full product as GET /v1/v5/catalog/products/:id does.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account catalogue product UUID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseUpdatedAt` | string | **yes** | ISO 8601 date-time with offset, exactly product.updated_at as last read (PostgreSQL microsecond precision kept). A different value answers 409 Product changed. Reload it before saving. |
| `product` | object | **yes** | The product. Strict object: an unknown key is refused (400). The same schema as the create route; on this edit route bundle, tiers, sections, page_config and specs are refused (422) and only the keys you send change anything. |
| `product.title` | string | no | 1-300 characters, trimmed. A blank title answers 422 Enter a product title. Sent only to change it; omitted fields keep their stored value. |
| `product.handle` | string | no | 1-80 characters, slugified (lowercase a-z, 0-9 and hyphens, at most 60). Must stay unique in the account catalogue (409 That product handle already exists); a handle that slugifies to nothing answers 422 Enter a product handle. Sent only to change it; omitted fields keep their stored value. |
| `product.status` | enum | no | draft, active or archived. Sent only to change it; omitted fields keep their stored value. |
| `product.currency` | string | no | Three letters (^[A-Za-z]{3}$), stored uppercase. Sent only to change it; omitted fields keep their stored value. |
| `product.subtitle` | string \| null | no | At most 300 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.vendor` | string \| null | no | At most 120 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.product_type` | string \| null | no | At most 120 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.tags` | string[] | no | At most 50 tags of at most 60 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.description` | string | no | At most 100000 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.seo_title` | string \| null | no | At most 200 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.seo_description` | string \| null | no | At most 500 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.gift_banner_text` | string \| null | no | At most 300 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.scarcity_text` | string \| null | no | At most 300 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.social_proof_text` | string \| null | no | At most 300 characters. Sent only to change it; omitted fields keep their stored value. |
| `product.rating_value` | number \| null | no | 0 to 5. Sent only to change it; omitted fields keep their stored value. |
| `product.rating_count` | integer | no | 0 or more. Sent only to change it; omitted fields keep their stored value. |
| `product.subscription_product_id` | uuid \| null | no | Must be absent or null: a value answers 422 Bind subscription plans explicitly in the page offer. Subscription plans are bound on the published page offer instead. |
| `product.price_cents` | integer | no | 0-2147483647, minor units. Applied to EVERY existing and new variant when sent (and the price of new matrix variants that have no variants entry). |
| `product.compare_at_price_cents` | integer \| null | no | 0-2147483647. Applied to every variant when sent. |
| `product.sku` | string | no | At most 120 characters. Applied to every variant when sent. |
| `product.inventory_qty` | integer \| null | no | Applied to every variant when sent; null means untracked. |
| `product.is_active` | boolean | no | Accepted and ignored for account catalogue products (it only sets the store link on the store product routes). |
| `product.options` | object[] | no | At most 2 option axes. When sent, the options are replaced and the variant matrix is rebuilt: variant ids of combinations that still exist are kept, removed combinations are deactivated (never deleted). The matrix (product of the value counts) may not exceed 200 variants (400). Omit for a single default variant. |
| `product.options[].name` | string | **yes** | 1-60 characters. |
| `product.options[].display_type` | enum; default `button` | no | button or image-swatch. |
| `product.options[].values` | object[] | **yes** | 1-50 values; value strings must be unique within the option (400 Option values must be unique). |
| `product.options[].values[].value` | string | **yes** | 1-80 characters. |
| `product.options[].values[].swatch_image_url` | string \| null | no | At most 2048 characters. |
| `product.options[].values[].swatch_hex` | string \| null | no | At most 16 characters, for example #1f2937. |
| `product.variants` | object[] | no | At most 200 entries, each matched to a matrix combination by option_values; matched variants are patched, other variants keep their values. A NEW combination with no entry and no product-level price_cents answers 422 Set a price for every new variant. Supply options too whenever option_values name values (400 Variant option_values must match the declared options in order). |
| `product.variants[].option_values` | string[] | no | One value per declared option, in option order (max 2, default []); no two entries with the same combination (400 Duplicate variant combination). |
| `product.variants[].price_cents` | integer | **yes** | 0 or more, minor units. Required in every variants entry. |
| `product.variants[].compare_at_price_cents` | integer \| null; default `null` | no | 0 or more. |
| `product.variants[].sku` | string | no | At most 120 characters. |
| `product.variants[].cost_cents` | integer \| null | no | 0 or more. |
| `product.variants[].weight_grams` | integer \| null | no | 0 or more. |
| `product.variants[].barcode` | string \| null | no | At most 80 characters. |
| `product.variants[].inventory_qty` | integer \| null; default `null` | no | null means untracked. |
| `product.variants[].is_active` | boolean; default `true` | no | Inactive variants cannot be sold. |
| `product.variants[].image_url` | string | no | At most 2048 characters. |
| `product.media` | object[] | no | At most 100 items. Omitted keeps the media; [] clears it; a list replaces the whole media list in that order. URLs are stored as given (not re-hosted). |
| `product.media[].url` | string | **yes** | HTTP(S) URL, at most 2048 characters (400 Use an HTTP(S) media URL). |
| `product.media[].alt` | string \| null | no | At most 300 characters. |
| `product.media[].kind` | enum; default `image` | no | image or video. |
| `product.tiers` | any | no | Refused on this route (even empty): sending it answers 422 Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder. |
| `product.bundle` | any | no | Refused on this route (even empty): sending it answers 422 Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder. |
| `product.specs` | any | no | Refused on this route (even empty): sending it answers 422 Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder. |
| `product.sections` | any | no | Refused on this route (even empty): sending it answers 422 Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder. |
| `product.page_config` | any | no | Refused on this route (even empty): sending it answers 422 Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder. |

**Request body**

```json
{
  "baseUpdatedAt": "2026-11-16T12:00:00.123456+00:00",
  "product": {
    "title": "Travel kit",
    "price_cents": 2995
  }
}
```

**Response** `200`

```json
{
  "product": {
    "id": "00000000-0000-4000-8000-000000000001",
    "shop_id": null,
    "title": "Travel kit",
    "handle": "travel-kit",
    "status": "active",
    "currency": "USD",
    "subtitle": null,
    "vendor": null,
    "product_type": null,
    "tags": [],
    "description": "",
    "seo_title": null,
    "seo_description": null,
    "rating_value": null,
    "rating_count": 0,
    "catalog_account_id": "acc_0123456789abcdef",
    "created_at": "2026-11-16T12:00:00.123456+00:00",
    "updated_at": "2026-11-16T12:00:00.123456+00:00"
  },
  "options": [
    {
      "id": "00000000-0000-4000-8000-000000000003",
      "name": "Size",
      "position": 0,
      "display_type": "button",
      "values": [
        {
          "id": "00000000-0000-4000-8000-000000000004",
          "option_id": "00000000-0000-4000-8000-000000000003",
          "value": "M",
          "position": 0,
          "swatch_hex": null,
          "swatch_image_url": null
        }
      ]
    }
  ],
  "variants": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "product_id": "00000000-0000-4000-8000-000000000001",
      "title": "M",
      "sku": "KIT-M",
      "price_cents": 2995,
      "compare_at_price_cents": null,
      "inventory_qty": null,
      "is_active": true,
      "image_url": "",
      "position": 0
    }
  ],
  "media": [
    {
      "id": "00000000-0000-4000-8000-000000000005",
      "product_id": "00000000-0000-4000-8000-000000000001",
      "url": "https://assets.example.com/kit-m.webp",
      "alt": "Travel kit",
      "kind": "image",
      "position": 0
    }
  ],
  "tiers": [],
  "bundle": [],
  "reviews": [],
  "translations": [],
  "shops": []
}
```

| response field | type | description |
|---|---|---|
| `(body)` | object | Same shape as GET /v1/v5/catalog/products/:id, read after the update; its product.updated_at is the next baseUpdatedAt. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseUpdatedAt is not an ISO date-time with offset, or product fails the strict schema.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"products"} when the plan excludes the products tool.
- `404` {"error":"Account catalogue product not found."}: unknown id, another account's product, or a store-owned product.
- `409` {"error":"Product changed. Reload it before saving."}: baseUpdatedAt is not the current updated_at.
- `409` {"error":"That product handle already exists."}: another product of the account catalogue uses the new handle.
- `413` {"error":"Request body is too large"}: the JSON body is over 2 MiB.
- `422` {"error":"Bind subscription plans explicitly in the page offer."}: product.subscription_product_id was set.
- `422` {"error":"Edit catalog metadata, options, variant prices and media here; page layout belongs in the Funnel Builder."}: bundle, tiers, sections, page_config or specs was sent.
- `422` {"error":"Enter a product title."} or {"error":"Enter a product handle."}: the new title is blank or the new handle slugifies to nothing.
- `422` {"error":"Set a price for every new variant."}: new options created a combination with no variants entry and no product-level price_cents.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Only the keys you send change. price_cents, compare_at_price_cents, sku and inventory_qty sent at product level overwrite EVERY variant; use variants[] to change one combination.
- Send options whenever variants[].option_values name values; combinations must match the declared values in order.
- Omitting media keeps it; [] clears it; a list replaces the whole media list.
- Never retry a 409 with the same baseUpdatedAt: read the product again, reconcile, and send the new updated_at.
- The body limit of this route is 2 MiB.

#### Themes

Storefront themes: the catalogue, the account's own themes and the theme applied to a store.

##### `PUT /v1/checkouts/:shopId/theme`

**Scope** `checkouts.write` - **Apply a theme to a store**

Apply a built-in theme or an account-owned custom theme (by slug) to an in-house store. A custom theme clears the store's per-store theme_settings (the shared theme is edited in the theme builder). A visual builtin: theme chosen while the store is on market or a custom theme keeps the store's composition in a private, store-specific copy of the theme. Returns the saved store row and the cache refresh outcome.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. Another account's store, an archived store or an unknown ID answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `themeId` | string | **yes** | Trimmed and lower-cased, 1 to 40 characters. One of the ten built-ins (legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery) or the slug of a custom theme of the account (GET /v1/checkouts/themes/custom). Plain visual names such as circuit are custom slugs, not aliases of the builtin: IDs. |

**Request body**

```json
{
  "themeId": "builtin:circuit"
}
```

**Response**

```json
{
  "shop": {
    "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
    "internal_name": "Example US",
    "shop_name": "Example Store",
    "domain": "shop.example.com",
    "admin_url": null,
    "cms": "product",
    "is_active": true,
    "payment_provider_id": "c2e7a4d1-0b6f-4a9e-b3d5-7f1c8e2a9b40",
    "canary_payment_provider_id": null,
    "canary_percent": 0,
    "render_domain_id": "cdm-example0001",
    "dns_record_type": "CNAME",
    "dns_record_target": "storefront-example.onrender.com",
    "domain_verification_status": "verified",
    "domain_verified_at": "2026-09-10T08:12:44.000Z",
    "user_id": null,
    "updated_at": "2026-09-18T16:03:21.115Z",
    "created_at": "2026-06-02T09:41:03.220Z",
    "unified_tool_mode": "external",
    "recovery_sink_mode": "external",
    "sms_recovery_enabled": true,
    "email_recovery_enabled": false,
    "shopify_app_client_id": null,
    "theme_id": "builtin:circuit",
    "shopify_app_secret_set": false,
    "whop_tracking_enabled": false,
    "shopify_api_key_set": false,
    "support_email": "support@example.com",
    "support_phone": null,
    "logo_url": null,
    "logo_height_override": null,
    "favicon_url": null,
    "primary_color": "#0f172a",
    "language_mode": "auto",
    "forced_locale": null,
    "shipping_protection_mode": "on",
    "shipping_protection_price_cents": 299,
    "shipping_protection_label": null,
    "shipping_protection_description": null,
    "allowed_countries": [
      "US",
      "CA"
    ],
    "affiliate_id": null,
    "checkout_tags": [],
    "theme_settings": {}
  },
  "cache": {
    "ok": true,
    "status": 200
  }
}
```

| response field | type | description |
|---|---|---|
| `shop` | object | The saved store row (every column except the encrypted app secret, the Shopify access token and the storefront content, plus the *_set flags). shop.theme_id is the assigned ID, or the slug of the private copy when a composition was preserved: read it from the response. |
| `cache` | object | Storefront cache refresh outcome: { ok, status } or { ok: false, error, status }. |

**Errors**

- `400` {"error":"Invalid","details":...}; No theme "<id>" in this account - a store can only run a built-in theme or one of its own; Made themes are not available yet (migration 182); This store is served by Shopify|Medusa: it has no product page here, so it has no theme; This store needs an account before its theme can be copied.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Checkout not found: unknown store, archived store, or a store of another account.
- `409` The store changed while its theme was being prepared. Reload it and retry.
- `500` Internal Server Error with a requestId (unexpected server or checkout-database failure).

**Gotchas**

- Only in-house (cms product) stores use themes; Shopify and Medusa stores are refused. Cart, checkout, payment, catalogue and routing are unchanged.
- Preserving a composition copies the per-store overrides into the private copy; the original custom theme and other stores are not edited, and identical copies are reused.
- Switching away from builtin:bikery keeps only the stored overrides the target built-in accepts.
- Do not confuse a store ID, a checkout profile ID, a custom theme UUID (theme.id) and a custom theme slug (theme.slug, the value a store's themeId takes).

##### `GET /v1/checkouts/themes`

**Scope** `checkouts.read` - **List storefront themes, editor metadata and optional usage**

The ten built-in storefront themes (legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery) with their labels, ordered sections, default tokens and fonts, plus the section palette, groups, presentation roots, pages and page templates the builder offers. ?usage=1 (or true) adds which theme each of the caller's stores chose and renders, its overrides and any drift; read-only, it never repairs a store.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `usage` | string | no | 1 or true adds the usage block (extra reads of the stores). Any other value, or absent, returns the catalogue alone (no 400). |

**Response**

```json
{
  "rows": [],
  "fonts": [],
  "palette": {},
  "groups": [],
  "roots": [],
  "pages": [],
  "templates": []
}
```

| response field | type | description |
|---|---|---|
| `rows[].id` | string | Built-in selection ID written to a store's theme_id: legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery. Custom slugs are listed by GET /v1/checkouts/themes/custom. |
| `rows[].label` | string | The name shown in the picker. |
| `rows[].description` | string | One line on what the theme looks like. |
| `rows[].sections` | string[] | The sections the manifest turns on, in render order, in the operator's words (ENGLISH since 2026-10-02 - the dashboard is English; the words are derived from one SECTION_LABELS table keyed by section type, so they cannot drift from the types). |
| `rows[].types` | string[] | The same sections as their registry TYPES, which is what the validation and the lockstep test compare. |
| `rows[].tokens` | object | Every token the manifest declares, with its default - the only names a store's theme_settings may override. |
| `rows[].fonts` | object | The manifest's body and heading families. |
| `fonts[]` | string[] | Every font the renderer resolves, so the editor can only offer those. |
| `usage.stores[]` | object | { id, name, shopName, domain, cms, applies, chosen, chosenRaw, rendering, overrides } - `chosen` is normalised (an unknown id reads as legacy, exactly as the renderer treats it) and `chosenRaw` is what is actually stored; `rendering` is what OUR copy of the shop would render. |
| `usage.counts` | object | Stores per theme, counted only over the stores a theme applies to. |
| `usage.notApplicable` | number | Shopify stores - their product pages are not served here, so they have no theme. |
| `usage.drift[]` | object | Stores whose chosen theme is not what our front renders. Reported, never auto-fixed. |
| `usage.copyChecked` | boolean | False when our own copy of the stores could not be read - the page then says the rendering is unknown rather than inventing Legacy. |
| `roots[]` | string[] | Available presentation roots for document.root: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery. Visual roots use plain names, not builtin: IDs. |
| `palette[]` | object[] | 43 section types across product/home/collection/content, including content_about with classic variant on the content page. Read the returned palette instead of hardcoding its count. |
| `groups[]` | string[] | Palette groups: Chrome, Hero, Buy box, Product, Catalogue, Page, Trust, Store. |
| `pages[]` | object[] | The four pages a theme lays out: pdp (product), home, collection, content, each with its labels. |
| `templates[]` | object[] | Ready-made page templates (named ordered block lists per page) usable as template when creating a custom theme. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The eight visual built-ins use the builtin: namespace (builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery). A plain slug such as circuit is an account-owned custom theme, never an alias. Presentation roots (document.root, manifest.chrome.root) stay plain: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery.
- Merchant overrides can intentionally change preset colours or fonts. Theme choice does not add sections, new commerce capabilities or reference content.
- content_about renders only the About us body. A stored non-empty content layout that predates it receives one enabled content_about block on read with a collision-free ID; an explicitly disabled existing block stays disabled. Other content pages keep their own bodies and order.

##### `GET /v1/checkouts/themes/custom`

**Scope** `checkouts.read` - **The account's made themes**

List the caller's account custom storefront themes with their store usage. ready is false (and rows empty) while the themes table is not available; the built-in catalogue stays available.

*No parameters.*

**Response**

```json
{
  "rows": [],
  "ready": true
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | id (management UUID), slug (the themeId a store takes), name, basedOn (legacy or market), basedOnLabel, blocks, disabled, types[], fonts, tokens (count of tokens), changes, stores (count), storeNames[], hasDraft, draftAt, updatedAt. |
| `ready` | boolean | False when the themes table is not available. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Custom themes style in-house storefronts, not checkout documents. theme.id is the management UUID; theme.slug is the value assigned as themeId on a store. Draft preview does not publish. PATCH document publishes immediately; PATCH draft saves only the draft.
- The eight visual built-ins use the builtin: namespace (builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery). A plain slug such as circuit is an account-owned custom theme, never an alias. Presentation roots (document.root, manifest.chrome.root) stay plain: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery.

##### `POST /v1/checkouts/themes/custom`

**Scope** `checkouts.write` - **Create a theme**

Create a custom storefront theme for the caller's account from one of the ten built-ins, optionally started from a named page template. Answers 201 with the theme row: id is the management UUID, slug the stable value a store's themeId takes.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 80 characters, unique per account. The slug is derived from it (lower-case, dashes, a -2, -3 suffix when taken) and never changes afterwards. |
| `basedOn` | string; default `legacy` | no | Built-in to extend: legacy, market, builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery. market is stored as based_on market; every other value is stored as legacy, a visual built-in keeping its plain root in manifest.chrome.root. |
| `template` | string | no | Trimmed, max 60: a page template ID from GET /v1/checkouts/themes templates[]. legacy and market bases refuse a template made for the other base; the resulting document is validated like any save. |

**Request body**

```json
{"name": "Agent theme", "basedOn": "market"}
```

**Response** `201`

```json
{
 "theme": {
  "id": "22222222-2222-4222-8222-222222222222",
  "slug": "agent-theme",
  "owner_email": "owner@example.com",
  "name": "Agent theme",
  "based_on": "market",
  "manifest": {},
  "draft": null,
  "draft_updated_at": null,
  "created_at": "2026-10-01T10:00:00.000Z",
  "updated_at": "2026-10-01T10:00:00.000Z"
 }
}
```

**Errors**

- `400` {"error":"Invalid","details":...}; {"error":"No account on this session"}; unknown page template "<id>"; the template "<label>" is for a theme based on <base>; template refused: <first errors> (with errors[])
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `409` That name is already used by one of your themes; Too many themes with that name
- `500` Internal Server Error with a requestId (unexpected server or database failure). Also when the themes table is not available.

**Gotchas**

- Custom themes style in-house storefronts, not checkout documents. theme.id is the management UUID; theme.slug is the value assigned as themeId on a store. Draft preview does not publish. PATCH document publishes immediately; PATCH draft saves only the draft.
- The eight visual built-ins use the builtin: namespace (builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery). A plain slug such as circuit is an account-owned custom theme, never an alias. Presentation roots (document.root, manifest.chrome.root) stay plain: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery.
- The request basedOn accepts namespaced visual IDs; the stored based_on field still contains only legacy or market. Read the expanded document from the detail endpoint before editing tokens or page sections.

##### `GET /v1/checkouts/themes/custom/:id`

**Scope** `checkouts.read` - **Open a theme in the builder**

Everything the theme builder opens on: the list row, the saved document expanded against its base (real values, not a patch), the draft if one is in progress (expanded), signed preview links for every page, and the page templates that fit its base.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The theme. |

**Response**

```json
{"row": {"id": "22222222-2222-4222-8222-222222222222", "slug": "agent-theme"}, "document": {}, "draft": null, "preview": {"url": null, "savedUrl": null, "pages": {"pdp": {"url": null, "savedUrl": null}, "home": {"url": null, "savedUrl": null}, "collection": {"url": null, "savedUrl": null}, "content": {"url": null, "savedUrl": null}}, "product": null, "store": null}, "templates": []}
```

| response field | type | description |
|---|---|---|
| `row` | object | The list row (see GET /v1/checkouts/themes/custom). |
| `document` | object | The saved theme expanded against its base: tokens, fonts, root, sections (product page) and pages (home, collection, content). |
| `draft` | object\|null | The work in progress, expanded the same way; null when none. |
| `preview` | object | Signed links: url (draft) and savedUrl for the product page, and pages.{pdp,home,collection,content}.{url,savedUrl}, plus the product and store they render. |
| `templates[]` | object[] | { id, label, description, page, sections } of the page templates that fit this theme. |

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Theme not found"}: no such theme in the caller's account (or the themes table is not available)
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Custom themes style in-house storefronts, not checkout documents. theme.id is the management UUID; theme.slug is the value assigned as themeId on a store. Draft preview does not publish. PATCH document publishes immediately; PATCH draft saves only the draft.
- The preview object uses url, savedUrl, pages, product and store; use returned URLs verbatim. Example is abbreviated; links depend on available store/product context.
- The eight visual built-ins use the builtin: namespace (builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery). A plain slug such as circuit is an account-owned custom theme, never an alias. Presentation roots (document.root, manifest.chrome.root) stay plain: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery.
- A visual custom theme is expanded from its plain manifest.chrome.root even though based_on remains legacy or market. Explicit merchant token and font edits are preserved in both saved and signed draft previews. A custom slug matching a plain preset name still loads the owned saved/draft theme.
- Content previews include page=about-us for the native About us page. The shared content layout supports content_about (classic); old stored non-empty layouts gain it only when absent, while an explicitly disabled block is respected. About page text is edited per store through GET/PUT /v1/checkouts/:shopId/storefront, not in the theme document.
- Preview links are null when the storefront host or its signing secret is not configured; never an unsigned URL.

##### `PATCH /v1/checkouts/themes/custom/:id`

**Scope** `checkouts.write` - **Save a theme, or its work in progress**

Rename, publish a validated document, save a validated draft, or discard the draft with null. document changes the live theme for every store on it and clears the draft unless draft is sent in the same request. There is no revision field: the last write wins.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Custom theme ID (management UUID). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed, 1 to 80. Rename; the slug never moves. |
| `document` | object | no | Theme document: tokens (object), fonts (object), root (plain presentation root), sections (product page blocks {id, type, variant, enabled, settings}), pages (home, collection, content block lists). Extra keys pass through to the validator, which refuses what the renderer would not read. Start from the expanded document of the GET. A page left out keeps its blocks. |
| `document.tokens` | object | no | Token values; only the tokens the base declares are accepted. |
| `document.fonts` | object | no | The body and heading font families, from the fonts list of GET /v1/checkouts/themes. |
| `document.root` | string | no | Plain presentation root: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery (never a builtin: ID). |
| `document.sections` | array | no | Product page blocks, in render order. |
| `document.pages` | object | no | Blocks of the home, collection and content pages, keyed by page. |
| `draft` | object\|null | no | The same shape (draft.tokens, draft.fonts, draft.root, draft.sections, draft.pages), saved as work in progress for the preview. null discards it. |

**Request body**

```json
{"name": "Agent theme renamed"}
```

**Response**

```json
{
  "theme": {
    "id": "22222222-2222-4222-8222-222222222222"
  },
  "document": {}
}
```

| response field | type | description |
|---|---|---|
| `theme` | object | The saved theme row (id, slug, owner_email, name, based_on, manifest, draft, draft_updated_at, created_at, updated_at). |
| `document` | object | The saved manifest expanded against its base. |

**Errors**

- `400` {"error":"Invalid","details":...}; {"error":"theme refused: <first three errors> (+N more)","errors":[...]} naming every refused value; Invalid (id not a UUID)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Theme not found"}
- `409` That name is already used by one of your themes
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Custom themes style in-house storefronts, not checkout documents. theme.id is the management UUID; theme.slug is the value assigned as themeId on a store. Draft preview does not publish. PATCH document publishes immediately; PATCH draft saves only the draft.
- The eight visual built-ins use the builtin: namespace (builtin:circuit, builtin:depot, builtin:haven, builtin:pulse, builtin:nest, builtin:terrain, builtin:botanica, builtin:bikery). A plain slug such as circuit is an account-owned custom theme, never an alias. Presentation roots (document.root, manifest.chrome.root) stay plain: classic, market, circuit, depot, haven, pulse, nest, terrain, botanica, bikery.
- Changing a shell in the builder must preserve section/page composition and explicit shared token/font edits. Store-level visual selection uses the separate theme assignment endpoint, whose private-copy/version guard does not change this shared document-publish contract.

##### `DELETE /v1/checkouts/themes/custom/:id`

**Scope** `checkouts.write` - **Delete a theme**

Delete a custom theme. Refused while any store still runs it, with the stores named: a store whose theme no longer exists renders Legacy.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The theme. |

**Response**

```json
{
  "deleted": true
}
```

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Theme not found"}
- `409` "<N> store(s) still use this theme: <first five store names>": move them first
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Custom themes style in-house storefronts, not checkout documents. theme.id is the management UUID; theme.slug is the value assigned as themeId on a store. Draft preview does not publish. PATCH document publishes immediately; PATCH draft saves only the draft.

#### Checkouts

The store checkouts (templates), their visual editor document, versions and preview links, the editor's fonts, saved blocks and pickers, the checkout sessions and the retired A/B tests.

- Duplicate (store checkout): the dashboard copies the settings into a new `POST /v1/checkouts/profiles`; it does not copy the builder layout. Copy the layout with `GET /v1/checkouts/profiles/:id/document`, `PUT .../document/draft` on the copy, then `POST .../document/publish`.
- The list's review status of affiliate edits comes from `GET /v1/v5/affiliates/store-checkouts/reviews` and is joined to the list in the browser.

##### `GET /v1/checkouts/ab-tests`

**Scope** `checkouts.read` - **Read legacy checkout split history**

Read the account's historical checkout AB tests (kept for reporting and cart attribution), each with the number of stores still routed to it. New experiments are AB Test nodes in a flow.

*No parameters.*

**Response**

```json
{"rows": []}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | Every column of the AB test row (id, owner_email, name, variants [{ checkoutId, weight }], active, created_at, updated_at) plus sites (stores routed to it), ordered by name. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Read-only historical compatibility. Checkout experiment editing and assignment are retired.

##### `POST /v1/checkouts/ab-tests`

**Scope** `checkouts.write` - **Create a checkout A/B test (retired: answers 410)**

Retired create of a checkout A/B test: always answers 410; create an AB Test node in a flow instead. Always responds 410 to every authorized caller. Create or edit an AB Test node in a published flow instead.

*No parameters.*

**Request body**

```json
{}
```

**Response** `410`

```json
{
  "error": "Checkout AB tests have moved to Flow Builder. Add an AB Test node to a flow.",
  "code": "checkout_ab_tests_retired"
}
```

| response field | type | description |
|---|---|---|
| `code` | string | checkout_ab_tests_retired |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `410` {"error":"Checkout AB tests have moved to Flow Builder. Add an AB Test node to a flow.","code":"checkout_ab_tests_retired"}

**Gotchas**

- The body is not read. No legacy experiment is created or updated; existing history stays readable with GET /v1/checkouts/ab-tests.

##### `PATCH /v1/checkouts/ab-tests/:id`

**Scope** `checkouts.write` - **Edit a checkout A/B test (retired: answers 410)**

Retired edit of a checkout A/B test: always answers 410; edit the AB Test node of the flow instead. Always responds 410 to every authorized caller. Create or edit an AB Test node in a published flow instead.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string | **yes** | Ignored: every call answers 410. |

**Request body**

```json
{}
```

**Response** `410`

```json
{
  "error": "Checkout AB tests have moved to Flow Builder. Add an AB Test node to a flow.",
  "code": "checkout_ab_tests_retired"
}
```

| response field | type | description |
|---|---|---|
| `code` | string | checkout_ab_tests_retired |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `410` {"error":"Checkout AB tests have moved to Flow Builder. Add an AB Test node to a flow.","code":"checkout_ab_tests_retired"}

**Gotchas**

- The body is not read. No legacy experiment is created or updated; existing history stays readable with GET /v1/checkouts/ab-tests.

##### `GET /v1/checkouts/profiles`

**Scope** `checkouts.read` - **List the checkouts (templates)**

Lists the account-owned checkout templates and their current usage. A store can use a checkout directly, through an AB test, or through any checkout node in its assigned published Flow. Store payment-method settings choose accepted Card, Wallet and Wire sources; historical checkout Apple/Google switches do not determine current payment availability. Published documents and draft indicators are returned as metadata; use the document endpoint for full editor content. Archived templates are omitted unless includeArchived=true.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `includeArchived` | string; default `false` | no | true includes archived checkouts; false or absent omits them. Any other value is a 400. |

**Response**

```json
{
  "rows": []
}
```

| response field | type | description |
|---|---|---|
| `rows[].sites` | integer | Distinct current store consumers across direct assignment, AB variants and the current published graph of assigned Flows. A Flow bootstrap checkout_id does not count as a direct assignment. |
| `rows[].api_key_set` | boolean | An API key is stored (encrypted for the storefront). The key itself never leaves the API. |
| `rows[].settings` | object | Checkout settings keyed by the shop column being overridden. These include layout and behavior settings; their count is not a payment-method count. |
| `rows[].published_version` | integer | Migration 187 - the editor document version every site using it renders; 0 = never published (the default document). |
| `rows[].has_draft` | boolean | Migration 187 - an editor draft is in progress (not live). |
| `rows[].settings.catalog_archived` | boolean | True means the catalog template is archived. Its documents and transaction history remain stored. |
| `rows[].direct_sites` | integer | Stores assigned this checkout directly, with no Flow or AB assignment. |
| `rows[].ab_sites` | integer | Stores assigned an AB test containing this checkout, with no Flow assignment. |
| `rows[].published_flows` | integer | Account-owned, unarchived Flows whose current published graph contains this checkout. Each Flow counts once, including Flows used through direct links without store assignments. |
| `rows[].api_key_id / api_key_name / atri_id / atri_name` | string\|null | The key and ATRI the checkout charges with, named. |

**Errors**

- `400` {"error":"Invalid archive filter"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- A checkout with active=false is hidden from the picker; sites already using it keep rendering - a template is not a switch.
- There is no single-profile read: filter this list by id (send includeArchived to find an archived one).

##### `POST /v1/checkouts/profiles`

**Scope** `checkouts.write` - **Create a checkout**

Create a checkout (payment page template) in the caller's account. The ATRI must be one of the account's classic ATRIs and the key one of its active API keys: the key secret is re-encrypted for the storefront. Nothing is applied by this call: give it to a store with POST /v1/checkouts/:shopId/checkout. 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 80, unique per account (case-insensitive). |
| `description` | string\|null | no | Trimmed, max 300; empty or null clears it. |
| `atriId` | uuid\|null | no | An active classic ATRI of the account: every store using the checkout charges through it. |
| `crm` | string; default `nmi` | no | nmi (the only value). |
| `apiKeyId` | uuid\|null | no | An active API key of the account whose secret the API can read back: its secret is re-encrypted for the storefront. When omitted and the checkout has no key, one is derived: the single key the account's active store routes already charge with, else the account's only eligible key, else the only one whose default ATRI is this ATRI. Eligible keys are the account's active keys whose secret the API can read back; the keys that were its checkout keys before keys had a single type come first, and any other active key is considered only when the account has none of them. |
| `threeDsIntegrationKey` | string\|null | no | Trimmed, max 200: a configured 3DS integration of the account (GET /v1/checkouts/profiles/3ds-options); null or "" = none. |
| `applePay` | boolean; default `false` | no | Historical wallet switch kept on the row; current payment availability follows the store payment methods. |
| `googlePay` | boolean; default `false` | no | Historical wallet switch kept on the row. |
| `active` | boolean; default `true` | no | false hides it from the picker; stores already using it keep rendering. |
| `settings` | object | no | Strict object of payment-page settings (an unknown key is a 400). Each key overrides the store column of the same name on every store using the checkout. |
| `settings.shipping_protection_mode` | string | no | off, on or forced. |
| `settings.shipping_protection_price_cents` | integer | no | >= 0, in cents. |
| `settings.shipping_protection_label` | string\|null | no | Trimmed, max 120. |
| `settings.shipping_protection_description` | string\|null | no | Trimmed, max 500. |
| `settings.countdown_enabled` | boolean | no | Countdown banner. |
| `settings.trustpilot_header_enabled` | boolean | no | Trustpilot header. |
| `settings.sales_points_header_enabled` | boolean | no | Sales points header. |
| `settings.cta_subtext_enabled` | boolean | no | Text under the pay button. |
| `settings.reassurance_secure_enabled` | boolean | no | Secure payment reassurance. |
| `settings.reassurance_refund_enabled` | boolean | no | Refund reassurance. |
| `settings.reassurance_tracking_enabled` | boolean | no | Tracking reassurance. |
| `settings.support_help_enabled` | boolean | no | Help link. |
| `settings.support_chat_enabled` | boolean | no | Chat link. |
| `settings.language_selector_enabled` | boolean | no | Language selector. |
| `settings.language_mode` | string | no | auto or forced. |
| `settings.forced_locale` | string\|null | no | Trimmed, max 5 (for example fr or en-US), used when language_mode is forced. |
| `settings.allowed_countries` | string[] | no | Up to 250 ISO alpha-2 codes (trimmed, upper-cased, exactly 2 letters each). |
| `settings.limits` | object | no | Per-cart limit; every key optional. |
| `settings.limits.enabled` | boolean | no | Turns the cap on; with no cap set it never refuses a sale. |
| `settings.limits.maxItemsPerCart` | integer\|null | no | >= 1: most items one cart may hold (quantities summed); null = no cap. |
| `settings.limits.maxAmountCents` | integer\|null | no | >= 1: most one cart may total, in cents; null = no cap. |
| `settings.limits.message` | string | no | Trimmed, max 300: what the buyer reads when over the cap; empty = the default sentences. |

**Request body**

```json
{"name": "Agent checkout", "description": "Draft API-built checkout", "active": false, "applePay": false, "googlePay": false}
```

**Response** `201`

```json
{
  "checkout": {
    "id": "22222222-2222-4222-8222-222222222222",
    "name": "Agent checkout"
  }
}
```

| response field | type | description |
|---|---|---|
| `checkout` | object | The stored template (201). |

**Errors**

- `400` {"error":"Invalid","details":...} (missing name, unknown settings key); {"error":"No account on this session"}; Choose a configured 3DS integration from this account; ATRI not found for this account; That API key does not belong to this account; That API key is revoked - pick an active one; That key predates secure reveal, so cocoapi cannot read it back. Create a new API key and pick that one.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `409` This account already has a checkout with that name
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` CHECKOUT_ENCRYPTION_KEY is not set on the API, so the key cannot be stored for the storefront

**Gotchas**

- A checkout with no key cannot take a payment: the storefront refuses rather than charging blind.

##### `GET /v1/checkouts/profiles/3ds-options`

**Scope** `checkouts.read` - **List configured 3DS integrations for a checkout**

Returns selectable, configured 3DS integrations from the checkout owner account. No credentials are returned. Checkout profile creation, edits and store routing reject integration keys that are not configured 3DS integrations for that same owner.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | no | Existing checkout whose owner account supplies the choices. Omit when creating a checkout (the caller's account is used). |

**Response**

```json
{"options":[{"value":"paay_3ds","label":"PAAY"}]}
```

| response field | type | description |
|---|---|---|
| `options` | array | Configured 3DS catalog choices with stable value key and human-readable label. |

**Errors**

- `400` {"error":"Invalid checkout"}: checkoutId is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); {"error":"No account"}: no account selected; Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}: no such checkout in the caller's account
- `500` Internal Server Error with a requestId (unexpected server or database failure).

##### `PATCH /v1/checkouts/profiles/:id`

**Scope** `checkouts.write` - **Edit a checkout**

Partial edit. The link is live: every field written here reaches every store using this checkout the moment it returns (check GET /v1/checkouts/profiles/:id/sites first). Changing apiKeyId re-encrypts the key material; clearing it drops the material. To restore an archived checkout send only {"catalogArchived":false}: it stays inactive until enabled separately.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed, 1 to 80, unique per account (case-insensitive). |
| `description` | string\|null | no | Trimmed, max 300; empty or null clears it. |
| `atriId` | uuid\|null | no | An active classic ATRI of the account: every store using the checkout charges through it. |
| `crm` | string | no | nmi (the only value). |
| `apiKeyId` | uuid\|null | no | An active API key of the account whose secret the API can read back: its secret is re-encrypted for the storefront. Changing it re-encrypts; null clears the key and its material. When omitted and the checkout has no key, one is derived: the single key the account's active store routes already charge with, else the account's only eligible key, else the only one whose default ATRI is this ATRI. Eligible keys are the account's active keys whose secret the API can read back; the keys that were its checkout keys before keys had a single type come first, and any other active key is considered only when the account has none of them. |
| `threeDsIntegrationKey` | string\|null | no | Trimmed, max 200: a configured 3DS integration of the account (GET /v1/checkouts/profiles/3ds-options); null or "" = none. |
| `applePay` | boolean | no | Historical wallet switch kept on the row; current payment availability follows the store payment methods. |
| `googlePay` | boolean | no | Historical wallet switch kept on the row. |
| `active` | boolean | no | false hides it from the picker; stores already using it keep rendering. Disabling is refused while an active AB test or an assigned flow uses it. |
| `settings` | object | no | Strict object of payment-page settings (an unknown key is a 400). Each key overrides the store column of the same name on every store using the checkout. |
| `settings.shipping_protection_mode` | string | no | off, on or forced. |
| `settings.shipping_protection_price_cents` | integer | no | >= 0, in cents. |
| `settings.shipping_protection_label` | string\|null | no | Trimmed, max 120. |
| `settings.shipping_protection_description` | string\|null | no | Trimmed, max 500. |
| `settings.countdown_enabled` | boolean | no | Countdown banner. |
| `settings.trustpilot_header_enabled` | boolean | no | Trustpilot header. |
| `settings.sales_points_header_enabled` | boolean | no | Sales points header. |
| `settings.cta_subtext_enabled` | boolean | no | Text under the pay button. |
| `settings.reassurance_secure_enabled` | boolean | no | Secure payment reassurance. |
| `settings.reassurance_refund_enabled` | boolean | no | Refund reassurance. |
| `settings.reassurance_tracking_enabled` | boolean | no | Tracking reassurance. |
| `settings.support_help_enabled` | boolean | no | Help link. |
| `settings.support_chat_enabled` | boolean | no | Chat link. |
| `settings.language_selector_enabled` | boolean | no | Language selector. |
| `settings.language_mode` | string | no | auto or forced. |
| `settings.forced_locale` | string\|null | no | Trimmed, max 5 (for example fr or en-US), used when language_mode is forced. |
| `settings.allowed_countries` | string[] | no | Up to 250 ISO alpha-2 codes (trimmed, upper-cased, exactly 2 letters each). |
| `settings.limits` | object | no | Per-cart limit; every key optional. |
| `settings.limits.enabled` | boolean | no | Turns the cap on; with no cap set it never refuses a sale. |
| `settings.limits.maxItemsPerCart` | integer\|null | no | >= 1: most items one cart may hold (quantities summed); null = no cap. |
| `settings.limits.maxAmountCents` | integer\|null | no | >= 1: most one cart may total, in cents; null = no cap. |
| `settings.limits.message` | string | no | Trimmed, max 300: what the buyer reads when over the cap; empty = the default sentences. |
| `catalogArchived` | boolean | no | Only false is accepted, as the only field of the body: restores an archived checkout (it stays inactive). Archive with DELETE. |

**Request body**

```json
{"description": "Updated checkout description"}
```

**Response**

```json
{
  "checkout": {
    "id": "22222222-2222-4222-8222-222222222222",
    "name": "Agent checkout"
  }
}
```

| response field | type | description |
|---|---|---|
| `checkout` | object | The template after the edit, with its current site count. |

**Errors**

- `400` {"error":"Invalid","details":...}; Choose a configured 3DS integration from this account; Restore the checkout before editing it (catalogArchived with other fields); ATRI not found for this account; A checkout needs a name; the API key refusals of the create
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `409` This account already has a checkout with that name; Restore this archived checkout before editing it.; Remove this checkout from active AB tests before disabling it; Remove this checkout from the flows assigned to stores before disabling it.
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` CHECKOUT_ENCRYPTION_KEY is not set on the API, so the key cannot be stored for the storefront

**Gotchas**

- Editing the ATRI of a checkout applied to seven sites re-routes seven sites. That is the model, not a bug - the site count is on the row so the size of the change is visible.
- Do not combine catalogArchived:false with editing fields; the API returns 400. Restore, review, then activate in a separate request.

##### `DELETE /v1/checkouts/profiles/:id`

**Scope** `checkouts.write` - **Archive a checkout template**

Recoverably archives an unused checkout catalog template by setting settings.catalog_archived=true and active=false. Retains editor documents, carts, transactions and history. Refuses active dependencies: store assignments, checkout A/B tests, nonarchived draft or published flows, and active saved links. The default catalog omits archived templates; recover them through includeArchived=true and PATCH {"catalogArchived":false}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | checkouts.id. |

**Response**

```json
{
  "ok": true,
  "sites": 0
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | True when the template is archived. |
| `sites` | integer | Zero: store assignments must be removed before archive; no live route is silently detached. |

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `409` Remove this checkout from its stores before archiving it.; Remove this checkout from its AB tests before archiving it.; Remove this checkout from its flows before archiving it.; Archive the saved links for this checkout first.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- This endpoint archives rather than deleting rows or financial history.
- Restoring a catalog item keeps it inactive until explicitly enabled.

##### `GET /v1/checkouts/profiles/:id/document`

**Scope** `checkouts.read` - **Open a checkout in the visual editor**

Everything the checkout builder opens on: the draft in progress, the published document, their counters, the default document and the validation issues. Stored documents come back migrated to the current block versions. published: null means the checkout renders the default document (defaultDocument), drawn from one store using the checkout (else from the checkout settings over a new store's values); defaultFrom says which.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | checkouts.id. |

**Response**

```json
{
 "checkout": {
  "id": "22222222-2222-4222-8222-222222222222",
  "name": "Main checkout",
  "sites": 2
 },
 "draft": {
  "format": 1,
  "pageType": "checkout",
  "root": {
   "props": {}
  },
  "content": [
   {
    "id": "a1B2c3D4e5",
    "type": "checkout.email",
    "props": {}
   }
  ]
 },
 "published": null,
 "publishedVersion": 0,
 "draftRevision": 7,
 "draftUpdatedAt": "2026-10-04T10:00:00.000Z",
 "versions": 0,
 "defaultDocument": {
  "format": 1,
  "pageType": "checkout",
  "root": {
   "props": {}
  },
  "content": [
   {
    "id": "a1B2c3D4e5",
    "type": "checkout.email",
    "props": {}
   }
  ]
 },
 "defaultFrom": {
  "kind": "store",
  "shopId": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
  "name": "Example store"
 },
 "issues": []
}
```

| response field | type | description |
|---|---|---|
| `checkout` | { id, name, sites } | `sites` = the stores using this checkout: what a publish reaches. |
| `draft` | EditorDocument \| null | The work in progress (migrated). Never rendered by a public page. |
| `published` | EditorDocument \| null | What every store using the checkout renders (migrated). null = the default document. |
| `publishedVersion` | integer | The version `published` holds; 0 = never published. |
| `draftRevision` | integer | Send it back as `baseRevision` on the next save / publish. |
| `draftUpdatedAt` | ISO string \| null | When the draft was last written. |
| `versions` | integer | How many versions were ever published. |
| `defaultDocument` | EditorDocument | The default document (see purpose). |
| `defaultFrom` | { kind: "store", shopId, name } \| { kind: "settings" } | What the default document was drawn from. |
| `issues[]` | Issue[] | The engine's validateDocument verdicts: `{ severity: "error"\|"warning", code, message, blockId?, field? }`. The draft's, else the published document's, else the default document's. |

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The default document is drawn from ONE store. Stores sharing the checkout but differing on a switch the checkout's settings do not override render that store's value once the document is published - `checkout.sites` is the blast radius.
- Read-only for every role that reads checkouts; nothing here is cached by the storefront (the published document travels with `checkout_routing_resolved`).

##### `PUT /v1/checkouts/profiles/:id/document/draft`

**Scope** `checkouts.write` - **Save the editor's draft**

The editor autosave. A draft is never refused for its content: validation errors and warnings come back as issues (the publish is where errors block). It is refused only when it is not a checkout document at all (400 with the engine's shape issues), when it is too large (413), or when it is based on a revision another write already replaced (409). Stored migrated to the current block versions.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `document` | object | **yes** | The editor document { format: 1, pageType: "checkout", root: { props }, content: BlockNode[] } (each block { id, type, props, ... }). At most 2048 KB of JSON (the request body may be up to 2.5 MB). |
| `baseRevision` | integer | **yes** | >= 0: the draftRevision this document was based on (GET .../document, or the previous save's answer). |

**Request body**

```json
{ "document": { "format": 1, "pageType": "checkout", "root": { "props": {} }, "content": [ { "id": "a1B2c3D4e5", "type": "checkout.email", "props": {} } ] }, "baseRevision": 7 }
```

**Response**

```json
{ "draftRevision": 8, "draftUpdatedAt": "2026-10-04T10:00:00.000Z", "issues": [ { "severity": "error", "code": "required-missing", "message": "..." } ] }
```

| response field | type | description |
|---|---|---|
| `draftRevision` | integer | The new revision - the next save's baseRevision. |
| `draftUpdatedAt` | ISO string | When it was written. |
| `issues[]` | Issue[] | The engine's validateDocument verdicts: `{ severity: "error"\|"warning", code, message, blockId?, field? }`. |

**Errors**

- `400` {"error":"Invalid","details":...} (no baseRevision, id not a UUID); {"error":"Not a checkout document","issues":[...]} (invalid-document, unsupported-format and other shape issues); {"error":"Not a checkout document: its page type is \"<type>\"","issues":[wrong-page-type]}. Nothing is written.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `409` {"error":"The draft changed since this copy was loaded (saved from another tab?) - reload it before saving again","draftRevision":<current>}
- `413` {"error":"The document is <N> KB; a builder document holds at most 2048 KB.","issues":[]}; a request body over 2.5 MB is refused before parsing.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Every draft write moves the revision - a save, a discard of an existing draft, a restore, a publish. Keep the answer's draftRevision as the next baseRevision.
- The answer's issues are the document AS STORED (migrated), which may differ from what was sent when a block's props version moved.
- Get the current draftRevision before saving and send it as baseRevision. A 409 means reload/rebase, never silently overwrite. Content issues may be saved in drafts; structural failures are rejected. Document limit is 2048 KB.

##### `DELETE /v1/checkouts/profiles/:id/document/draft`

**Scope** `checkouts.write` - **Discard the draft**

Drops the work in progress; the editor goes back to the published document (or the default one). The revision moves when there was a draft, so a tab still holding it cannot bring it back with its next save (409). Discard requires the loaded baseRevision and never overwrites a newer draft from another tab.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | >= 0: the draftRevision of the last document read. Strict body: any other key is a 400. |

**Request body**

```json
{
  "baseRevision": 3
}
```

**Response**

```json
{
  "ok": true,
  "draftRevision": 4
}
```

| response field | type | description |
|---|---|---|
| `draftRevision` | integer | The current revision (unchanged when there was no draft). |

**Errors**

- `400` {"error":"Invalid"} (id not a UUID); {"error":"Invalid request."} (missing or invalid baseRevision, or an extra key)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `409` {"error":"The draft changed since this copy was loaded (saved from another tab?) - reload it before saving again","draftRevision":<current>}: a newer draft is preserved.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The revision moves only when a draft existed; discarding when there is none answers ok with the unchanged revision.

##### `POST /v1/checkouts/profiles/:id/document/links`

**Scope** `checkouts.write` - **A signed storefront link for the editor canvas or the Preview**

Mint a signed storefront URL (valid 2 hours) for the editor canvas iframe or the Preview tab, only once the checkout is known to be the caller's: on the storefront the link is the authorization. canvas: <storefront>/editor/canvas/checkout/<id>?origin=<editor origin>&exp=...&sig=... signed for the request Origin, which the storefront alone lets frame the canvas. preview: <storefront>/preview/checkout/<id>?mode=draft|published&exp=...&sig=..., the mode inside the signature. The allowed preview store IDs are signed too, so storeId cannot escape the account.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string | **yes** | canvas (the editor iframe, signed for the request Origin) or preview (the read-only Preview tab). |
| `mode` | string; default `draft` | no | draft or published: what the Preview shows. Ignored by the canvas. |
| `storeId` | uuid\|null; default `null` | no | A store from GET /v1/checkouts/profiles/:id/document/stores to preview with; null renders a neutral demonstration. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Origin` | string | no | Required for kind canvas: the browser origin of the editor, which must be one of the API's allowed CORS origins. Ignored for preview. |

**Request body**

```json
{"kind": "preview", "mode": "draft", "storeId": null}
```

**Response**

```json
{"url": "https://storefront.example.com/preview/checkout/22222222-2222-4222-8222-222222222222?mode=draft&exp=1792300000&sig=example", "origin": "https://storefront.example.com", "expiresAt": "2026-10-18T12:00:00.000Z", "previewStores": [], "selectedStoreId": null}
```

| response field | type | description |
|---|---|---|
| `url` | string | The signed storefront URL. |
| `origin` | string | The storefront's origin - what the editor checks postMessage events against. |
| `expiresAt` | ISO string | Two hours from now: mint a fresh one after that. |
| `previewStores` | array | Account-scoped choices with id and name. |
| `selectedStoreId` | uuid \| null | Requested preview store or neutral null. |

**Errors**

- `400` {"error":"Invalid","details":...}: id not a UUID, kind missing or unknown, mode unknown, storeId not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); canvas only: {"error":"The canvas is signed for the editor that asks for it: this request's Origin is not one of the API's allowed origins (CORS_ORIGINS)"}: a call without a browser Origin cannot mint one; Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}; {"error":"Preview store not found in this checkout account"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).
- `503` {"error":...} naming what is missing: the storefront URL (STOREFRONT_INTERNAL_URL unset, not absolute or not http(s)) or the signing secret. Never an unsigned link.

**Gotchas**

- canvas: the signed origin is the request's Origin, never a body field - the browser sets it, and the API refuses one it does not already allow for CORS. The storefront takes it back from the VERIFIED claim (the `origin` query parameter alone counts for nothing): a link copied to another site cannot be framed there.
- Answered with Cache-Control: no-store. Each call is one action-log row (a POST), nothing else is stored.
- storeId=null is generic demo context; an account-owned storeId resolves logo, colors, fonts, shipping and store configuration. Use the returned signed URL verbatim. Canvas links additionally require an allowed Origin. Preview never proves live wallet/provider readiness.

##### `POST /v1/checkouts/profiles/:id/document/publish`

**Scope** `checkouts.write` - **Publish the draft**

The draft becomes the document every store using this checkout renders, at its next checkout render. One transaction: the checkout row is locked (two publishes queue), the draft is validated (an error refuses the publish with the list of what to fix, nothing written), version n+1 is appended to the version history with the operator and note, and the draft is cleared.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | >= 0: the draftRevision being published; a stale one is a 409, so what is published is what was reviewed. |
| `note` | string\|null | no | Trimmed, max 500: kept on the version row; "" or null = none. |

**Request body**

```json
{ "baseRevision": 8, "note": "New trust badges" }
```

**Response**

```json
{ "publishedVersion": 3, "draftRevision": 9, "issues": [] }
```

| response field | type | description |
|---|---|---|
| `publishedVersion` | integer | The version now live. |
| `draftRevision` | integer | The revision after the draft was cleared. |
| `issues[]` | Issue[] | The engine's validateDocument verdicts: `{ severity: "error"\|"warning", code, message, blockId?, field? }`. Warnings only - an error is a 422. |

**Errors**

- `400` {"error":"Invalid","details":...}: baseRevision missing, note too long, or id not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `409` {"error":"The draft changed since this copy was loaded (saved from another tab?) - reload it before saving again","draftRevision":<current>}; {"error":"There is no draft to publish - save one first","draftRevision":<current>}
- `422` {"error":"The draft has errors to fix before it can be published","issues":[...]}: nothing is written
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- THE LINK IS LIVE (migration 175): a publish reaches every site using this checkout at once - `checkout.sites` on GET .../document is the number.
- Publishing requires the latest baseRevision and a valid saved draft. Validation errors return 422. Successful publication increments the revision; fetch the document again before another write.

##### `GET /v1/checkouts/profiles/:id/document/stores`

**Scope** `checkouts.read` - **List stores available for checkout preview**

The stores routed by the checkout owner account that a preview can render with (storeId of POST /v1/checkouts/profiles/:id/document/links). Checks the checkout belongs to the caller first. Answers with Cache-Control no-store.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |

**Response**

```json
{
 "stores": [
  {
   "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "name": "Example store"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `stores[]` | object[] | { id, name } of the account stores, ordered by name (name falls back to the domain). |

**Errors**

- `400` {"error":"Invalid checkout"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Read only; it does not reassign the checkout or alter a store.

##### `GET /v1/checkouts/profiles/:id/document/versions`

**Scope** `checkouts.read` - **The published versions of a checkout**

The history of what the checkout's page looked like: every published version, newest first (at most 500), without the documents themselves - restoring one copies it into the draft.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | checkouts.id. |

**Response**

```json
{ "versions": [ { "version": 2, "createdAt": "2026-10-04T10:00:00.000Z", "createdBy": "op@example.com", "note": null } ], "publishedVersion": 2 }
```

| response field | type | description |
|---|---|---|
| `versions[]` | { version, createdAt, createdBy, note }[] | createdBy = the operator who published it. |
| `publishedVersion` | integer | The one live now. |

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

##### `POST /v1/checkouts/profiles/:id/document/versions/:version/restore`

**Scope** `checkouts.write` - **Restore a version into the draft**

The version becomes the DRAFT (migrated to the current block versions), never the published document: the operator reviews it in the editor and publishes it, which makes it the next version - the history only ever grows.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Checkout ID. |
| `version` | integer | **yes** | 1 to 2147483647: a version listed by GET /v1/checkouts/profiles/:id/document/versions. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | no | >= 0. When given, guards the draft it replaces like a save does (409 when stale). Without it the current draft is replaced. |

**Request body**

```json
{ "baseRevision": 9 }
```

**Response**

```json
{ "draftRevision": 10, "issues": [] }
```

| response field | type | description |
|---|---|---|
| `draftRevision` | integer | The new revision. |
| `issues[]` | Issue[] | The engine's validateDocument verdicts: `{ severity: "error"\|"warning", code, message, blockId?, field? }`. |

**Errors**

- `400` {"error":"Invalid","details":...}: id, version or body invalid
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}; {"error":"This checkout has no version <N>"}
- `409` {"error":"The draft changed since this copy was loaded (saved from another tab?) - reload it before saving again","draftRevision":<current>}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- With a JSON content-type the body must be a JSON object (`{}`), or Fastify answers 400 for an empty body.

##### `GET /v1/checkouts/profiles/:id/sites`

**Scope** `checkouts.read` - **List the stores using a checkout**

Lists current account-owned store consumers through direct assignment, AB tests and all checkout nodes of assigned published Flows. Each store appears once with its actual route type. Unpublished drafts, older graph versions and archived Flows are excluded.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | checkouts.id. |

**Response**

```json
{
  "rows": []
}
```

| response field | type | description |
|---|---|---|
| `rows[].route_type` | string | direct, flow or ab_test, matching the store assignment that reaches this checkout. |
| `rows[].flow_id` | uuid\|null | The assigned Flow ID, or null for direct and AB assignments. |
| `rows[].flow_name` | string\|null | The assigned account-owned Flow name, or null. |
| `rows[]` | object[] | One row per store, ordered by store name: shop_id, name, domain, active, route_type, flow_id, flow_name. |

**Errors**

- `400` {"error":"Invalid"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module checkouts): the plan lacks the checkouts module.
- `404` {"error":"Not found"}
- `500` Internal Server Error with a requestId (unexpected server or database failure).

##### `GET /v1/checkouts/sessions`

**Scope** `checkouts.read` - **List recent checkout sessions**

Session lookup list: the newest checkout sessions (grouped by cart token, newest first, up to 50) across the caller's stores, built from the most recent checkout events carrying a cart token, plus, when q is an identifier, every session that identifier names found by an exact lookup over all events. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string | no | Optional identifier (cart token, visitor id or session id). When it is 6 to 200 characters and contains no space, comma, parenthesis, quote, backslash, *, . or %, it is matched exactly against cart_token, visitor_id and session_id over EVERY event of the caller's stores, and the sessions found are appended with matched: true. Any other value (shorter, or with those characters) is ignored server-side; a value over 200 characters is ignored too (no 400). |

**Response**

```json
{
 "rows": [
  {
   "cart_token": "c1-9f8e7d6c5b4a",
   "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "last_at": "2026-09-19T09:14:02.511Z",
   "events": 7,
   "last_event": "payment_success"
  }
 ],
 "bound": {
  "scanned": 2000,
  "cap": 2000,
  "truncated": true,
  "sessions": 312,
  "sessionCap": 50,
  "sessionsTruncated": true,
  "search": null,
  "searchFound": 0
 },
 "shops": [
  {
   "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "name": "Example US",
   "domain": "shop.example.com"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | cart_token, shop_id, last_at, events (events of that cart among those scanned), last_event (event_type of the newest one), and matched: true on rows found by the exact q lookup. |
| `bound` | object | scanned, cap (2000), truncated (a source returned a full cap: older events exist), sessions (sessions found in the scan), sessionCap (50), sessionsTruncated, search (the identifier looked up, or null), searchFound. |
| `shops[]` | object[] | { id, name (internal name), domain } of the visible stores. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- The newest list is built from at most 2000 recent events with a cart token (per checkout database); on a busy account that is minutes of traffic, not a history. bound says what was read and whether the cap was hit.
- Events without a cart token (pure visitor pings) never create a row; the exact q lookup still finds them through visitor_id or session_id, grouped by their cart token.
- Open one row with GET /v1/checkouts/sessions/cart/<cart_token>.

##### `GET /v1/checkouts/sessions/:kind/:id`

**Scope** `checkouts.read` - **Read one checkout session timeline**

Chronological reconstruction of one shopper's checkout: every checkout event (up to 5000) and every checkout order row (up to 200) carrying the given cart token, visitor id or session id across the caller's stores, each order with the customer's 3DS proof summary. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string | **yes** | One of cart, visitor, session: which key :id is (cart_token, visitor_id or session_id). |
| `id` | string | **yes** | The exact key value, 3 to 200 characters. |

**Response**

```json
{
 "events": [
  {
   "id": "b7e1c2d3-0000-4000-8000-000000000001",
   "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "event_type": "session_start",
   "occurred_at": "2026-09-19T09:12:31.000Z",
   "cart_token": "c1-9f8e7d6c5b4a",
   "visitor_id": "v_7f3a9c",
   "session_id": "s_1e2d3c",
   "metadata": null,
   "country_iso2": "US",
   "ua_device_kind": "mobile",
   "browser": "Safari",
   "os": "iOS",
   "referrer_host": null,
   "load_time_ms": 820,
   "nav_to_lcp_ms": 1240,
   "webview_kind": null
  }
 ],
 "orders": [
  {
   "id": "d4c3b2a1-0000-4000-8000-000000000002",
   "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "created_at": "2026-09-19T09:13:58.000Z",
   "updated_at": "2026-09-19T09:14:02.000Z",
   "status": "approved",
   "amount_cents": 4999,
   "currency": "USD",
   "customer_email": "buyer@example.com",
   "card_brand": "visa",
   "card_last4": "4242",
   "payment_method": "card",
   "payment_path": "direct",
   "wallet_kind": null,
   "gateway_kind": "nmi",
   "gateway_order_id": "1000000001",
   "decline_reason": null,
   "decline_category": null,
   "processing_ms": 2100,
   "three_ds_status": null,
   "cart_token": "c1-9f8e7d6c5b4a",
   "visitor_id": "v_7f3a9c",
   "session_id": "s_1e2d3c",
   "utm_source": "tiktok",
   "utm_campaign": "fall",
   "referrer_host": null,
   "threeDsSummary": {
    "total": 0,
    "ready": 0,
    "used": 0,
    "expired": 0,
    "pending": 0,
    "failed": 0,
    "readyForRebill": 0,
    "authenticationMode": "none"
   }
  }
 ],
 "bound": {
  "events": {
   "scanned": 7,
   "cap": 5000,
   "truncated": false
  },
  "orders": {
   "scanned": 1,
   "cap": 200,
   "truncated": false
  }
 },
 "shops": [
  {
   "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "name": "Example US",
   "domain": "shop.example.com"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `events[]` | object[] | id, shop_id, event_type, occurred_at, cart_token, visitor_id, session_id, metadata (free-form per event type), country_iso2, ua_device_kind, browser, os, referrer_host, load_time_ms, nav_to_lcp_ms, webview_kind. Ascending by occurred_at. |
| `orders[]` | object[] | Checkout order rows (one per pay click): id, shop_id, created_at, updated_at, status, amount_cents, currency, customer_email, card_brand, card_last4, payment_method, payment_path, wallet_kind, gateway_kind, gateway_order_id, decline_reason, decline_category, processing_ms, three_ds_status, cart_token, visitor_id, session_id, utm_source, utm_campaign, referrer_host, plus threeDsSummary. Ascending by created_at. |
| `orders[].threeDsSummary` | object\|null | { total, ready, used, expired, pending, failed, readyForRebill, authenticationMode (none \| single \| double) } for the customer, or null. |
| `bound` | object | { events: { scanned, cap, truncated }, orders: { scanned, cap, truncated } }. |
| `shops[]` | object[] | Visible stores { id, name, domain } for labelling. |

**Errors**

- `400` {"error":"Invalid"} (no details): kind not cart, visitor or session, or id shorter than 3 or longer than 200 characters.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- An unknown key is not a 404: the answer is 200 with empty events and orders.
- Only rows of the caller's stores are returned; a token seen on another account's store yields empty arrays.
- Caps: 5000 events and 200 orders; bound.events / bound.orders say whether a cap was hit.
- orders[].threeDsSummary is read for the order's customer e-mail within the caller's account and ATRI view; null when the e-mail is missing or masked.

##### `GET /v1/editor/catalog`

**Scope** `checkouts.read` - **Read the checkout editor catalogue**

Machine-readable projection of the checkout builder registry: the checkout page definition and variables, every block schema with its defaults, the reusable library sections, a complete default document, and the named template documents with their validation issues. Start from these documents instead of inventing block types or fields.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `pageType` | enum: checkout; default `checkout` | no | Only checkout is supported; any other value or unknown query field answers 400. |

**Response**

```json
{
 "version": 1,
 "format": 1,
 "catalogVersion": 1,
 "pageType": {
  "id": "checkout"
 },
 "blocks": [],
 "library": [],
 "defaultDocument": {},
 "templates": [],
 "validation": {
  "authoritative": "draft-save-and-publish",
  "executablePredicatesOmitted": true,
  "maxDocumentBytes": 524288
 }
}
```

**Errors**

- `400` `{"error":"Only pageType=checkout is supported; unknown query fields are refused","details":{...}}`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- The example is abbreviated; the real catalogVersion, schemas and documents come from the running registry.
- Sent with cache-control: private, max-age=300. Node ids in generated documents may change between calls: keep the ids of the document you are editing.
- Executable predicates and migrations are omitted; draft save and publish validation are authoritative (validation.maxDocumentBytes gives the document size limit).
- The full store, product, draft, preview and publish sequence is described in the *Build stores, product pages and checkouts* section of llm.md.

##### `GET /v1/editor/entities/discount-codes`

**Scope** `checkouts.read` - **Pick discount codes for the editor**

The account's discount codes by code, as a Discount block links them (no note, no redemption figures).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string (0-120, trimmed) | no | Code contains. |
| `limit` | integer (1-200); default `100` | no | Maximum rows. |

**Response**

```json
{
 "rows": [
  {
   "id": "7c2f0a51-3d1e-4b8a-9f00-1a2b3c4d5e6f",
   "code": "SAVE10",
   "scope": "checkout",
   "checkout_id": "11111111-1111-4111-8111-111111111111",
   "shop_id": null,
   "target_name": "Main checkout",
   "kind": "percent",
   "percent_bp": 1000,
   "amount_cents": null,
   "currency": null,
   "min_subtotal_cents": 2000,
   "starts_at": null,
   "ends_at": null,
   "active": true,
   "archived": false
  }
 ]
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is out of bounds or unknown.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- percent_bp is basis points (1000 = 10%); amount_cents is minor units in currency. archived tells whether the code was archived.

##### `GET /v1/editor/entities/products`

**Scope** `checkouts.read` - **Pick products for the editor**

The account's products (own catalogue or linked to one of its stores), newest edit first, each with its variants, image and default price (first active variant). With checkoutId: one line per store the checkout is applied to, saying whether the product is sold there and at what price (store override, else the variant price).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string (0-120, trimmed) | no | Title or handle contains. |
| `checkoutId` | uuid | no | A checkout of the account: adds shops[] per product. |
| `limit` | integer (1-100); default `50` | no | Maximum rows. |

**Response**

```json
{
 "rows": [
  {
   "id": "22222222-2222-4222-8222-222222222222",
   "title": "Lamp",
   "handle": "lamp",
   "status": "active",
   "currency": "USD",
   "image": "https://cdn.example.com/lamp.jpg",
   "default_variant_id": "00000000-0000-4000-8000-000000000601",
   "price_cents": 2999,
   "compare_at_price_cents": 3999,
   "variants": [
    {
     "id": "00000000-0000-4000-8000-000000000601",
     "title": "Large",
     "sku": "LMP-L",
     "price_cents": 2999,
     "compare_at_price_cents": 3999,
     "image_url": null,
     "is_active": true,
     "position": 1
    }
   ],
   "shops": [
    {
     "shop_id": "00000000-0000-4000-8000-000000000601",
     "name": "DWELO",
     "domain": "dwelo.com",
     "available": true,
     "override_cents": 2499,
     "price_cents": 2499
    }
   ]
  }
 ]
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is out of bounds or unknown.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Unknown checkout"}` when checkoutId is not a checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

##### `GET /v1/editor/entities/resolve`

**Scope** `checkouts.read` - **Resolve editor references**

Returns the display snapshot of each reference a document holds, in the order asked, or missing true (unknown, deleted or another account's: never told apart).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `refs` | string (1-8000): CSV of kind:<uuid> | **yes** | Up to 100 distinct references; kind is product \| productVariant \| subscriptionProduct \| discountCode \| checkout. Duplicates are merged. |

**Response**

```json
{
 "entities": [
  {
   "ref": "product:22222222-2222-4222-8222-222222222222",
   "kind": "product",
   "id": "22222222-2222-4222-8222-222222222222",
   "missing": false,
   "snapshot": {
    "id": "00000000-0000-4000-8000-000000000601",
    "title": "Lamp",
    "price_cents": 2999
   }
  },
  {
   "ref": "discountCode:66666666-6666-4666-8666-666666666666",
   "kind": "discountCode",
   "id": "66666666-6666-4666-8666-666666666666",
   "missing": true
  }
 ]
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when refs is missing, empty or over 8000 characters, or an unknown query field is sent.
- `400` `bad ref "<ref>" (kind:<uuid>, kind product | productVariant | subscriptionProduct | discountCode | checkout)` or `{"error":"at most 100 refs"}`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

##### `GET /v1/editor/entities/subscription-products`

**Scope** `checkouts.read` - **Pick subscription products for the editor**

The account's subscription products (never a deleted one) by name: price, first charge delay, interval, cycles, plan mode, attach mode (optin = attached only through a checkout opt-in) and active flag.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string (0-120, trimmed) | no | Name contains. |
| `limit` | integer (1-200); default `100` | no | Maximum rows. |

**Response**

```json
{
 "rows": [
  {
   "id": "00000000-0000-4000-8000-000000000601",
   "name": "VIP Club",
   "amount_cents": 2999,
   "first_after_days": 14,
   "interval_days": 30,
   "first_after_value": 14,
   "first_after_unit": "days",
   "interval_value": 30,
   "interval_unit": "days",
   "max_cycles": null,
   "plan_mode": "simple",
   "attach_mode": "optin",
   "active": true
  }
 ]
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is out of bounds or unknown.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- There is no currency column: subscription amounts are in the account currency.

##### `GET /v1/editor/fonts`

**Scope** `checkouts.read` - **List custom fonts**

The account's uploaded font files with their public URL, which a document's custom font reference names by family.

*No parameters.*

**Response**

```json
{
 "rows": [
  {
   "id": "5b6c7d8e-0000-4000-8000-000000000001",
   "owner_email": "owner@example.com",
   "family": "Brand Sans",
   "weight": 700,
   "style": "normal",
   "format": "woff2",
   "storage_path": "3f9a...c21e/5b6c7d8e-0000-4000-8000-000000000001.woff2",
   "size_bytes": 48213,
   "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
   "created_at": "2026-10-05T09:00:00.000Z",
   "created_by": "owner@example.com",
   "url": "https://storage.example.com/storage/v1/object/public/editor-fonts/3f9a...c21e/5b6c7d8e-0000-4000-8000-000000000001.woff2"
  }
 ],
 "max": 60,
 "maxBytes": 2097152
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- max is the per-account file limit (60) and maxBytes the per-file limit (2 MiB). Font URLs are public by design.

##### `POST /v1/editor/fonts`

**Scope** `checkouts.write` - **Upload a custom font**

Uploads one font file as JSON with the bytes in base64. The format is read from the file itself (woff2, woff, ttf or otf), never from a name or MIME type. At most 2 MiB per file, one file per family + weight + style, 60 files per account. Answers 201 with the font and its public URL.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `family` | string (max 200) | **yes** | Font family; sanitized to letters, digits, spaces and hyphens, at most 64 characters after sanitizing. |
| `weight` | integer: 100 \| 200 \| 300 \| 400 \| 500 \| 600 \| 700 \| 800 \| 900; default `400` | no | Font weight. |
| `style` | enum: normal \| italic; default `normal` | no | Font style. |
| `data_base64` | string (base64, max about 2.8 MiB) | **yes** | The file bytes in base64; a data:...;base64, prefix is accepted and stripped. |
| `content_type` | string (max 100) | no | Accepted and ignored (the format is sniffed from the bytes). |
| `filename` | string (max 255) | no | Accepted and ignored. |

**Request body**

```json
{
  "family": "Brand Sans",
  "weight": 700,
  "style": "normal",
  "data_base64": "d09GMgABAAAAA..."
}
```

**Response** `201`

```json
{
 "font": {
  "id": "5b6c7d8e-0000-4000-8000-000000000001",
  "owner_email": "owner@example.com",
  "family": "Brand Sans",
  "weight": 700,
  "style": "normal",
  "format": "woff2",
  "storage_path": "3f9a...c21e/5b6c7d8e-0000-4000-8000-000000000001.woff2",
  "size_bytes": 48213,
  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
  "created_at": "2026-10-05T09:00:00.000Z",
  "created_by": "owner@example.com",
  "url": "https://storage.example.com/storage/v1/object/public/editor-fonts/3f9a...c21e/5b6c7d8e-0000-4000-8000-000000000001.woff2"
 }
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body fails the schema (strict: unknown fields refused; weight not one of the nine values).
- `400` `{"error":"family: letters, digits, spaces and hyphens, at most 64"}` or `{"error":"data_base64 is not base64"}`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `409` `{"error":"<family> already has a <weight> <style> file"}`.
- `413` `The file is <n> KB; a font file holds at most 2 MB.`; a body over about 2.8 MiB is refused before the route.
- `415` `{"error":"Not a font file: woff2, woff, ttf or otf (read from the file itself, not its name)"}`.
- `422` `{"error":"An account holds at most 60 font files: delete one first"}`.
- `502` The storage upload failed (its own message); nothing is stored.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Font storage is not configured on the API"}`.

**Gotchas**

- If the database row cannot be written, the uploaded object is removed: no orphan file.
- The full store, product, draft, preview and publish sequence is described in the *Build stores, product pages and checkouts* section of llm.md.

##### `DELETE /v1/editor/fonts/:id`

**Scope** `checkouts.write` - **Delete a custom font**

Deletes the font row, then its storage object. A document still naming the family falls back to the page font stack.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Font id. |

**Response**

```json
{
  "ok": true,
  "objectRemoved": true
}
```

| response field | type | description |
|---|---|---|
| `objectRemoved` | boolean | False when the storage could not confirm the object's removal (the row is gone either way). |

**Errors**

- `400` `{"error":"Invalid"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the id is unknown or belongs to another account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- objectRemoved false means the row is gone but the file could not be removed (an unlisted orphan); the font is no longer usable either way.

##### `GET /v1/editor/saved-blocks`

**Scope** `checkouts.read` - **List saved blocks**

The account's saved blocks with their nodes. With a page type: the blocks saved for it plus those saved for every page type ('*').

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `pageType` | string: '*' or a page type: checkout \| landing \| post_sell \| thank_you | no | Filter; '*' or absent lists every block. |

**Response**

```json
{
 "rows": [
  {
   "id": "6c7d8e9f-0000-4000-8000-000000000001",
   "owner_email": "owner@example.com",
   "name": "Shipping banner",
   "page_type": "checkout",
   "nodes": [
    {
     "id": "a1B2c3D4e5",
     "type": "content.text",
     "props": {
      "text": "Free shipping over $50"
     }
    }
   ],
   "catalog": 2,
   "created_at": "2026-10-05T09:00:00.000Z",
   "created_by": "owner@example.com",
   "updated_at": "2026-10-05T09:00:00.000Z"
  }
 ]
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when pageType is not '*' or a known page type, or an unknown query field is sent.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

##### `POST /v1/editor/saved-blocks`

**Scope** `checkouts.write` - **Save a block**

Stores a subtree of block nodes for the account. The nodes are migrated, then validated for the page type ('*' = every page type): issues about the nodes themselves refuse the save with 422; issues of the surrounding page and the placement of the top-level nodes do not. Answers 201 with the block and the non-blocking issues. At most 200 blocks per account.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-80, trimmed) | **yes** | Block name, unique per account. |
| `pageType` | string: '*' or a page type: checkout \| landing \| post_sell \| thank_you; default `*` | no | Page type the block is for; '*' = validated against every page type and offered on all of them. |
| `nodes` | array of block nodes (1-200 top-level, max 256 KiB) | **yes** | The block subtree, in the document node format of GET /v1/editor/catalog. Migrated to the current catalogue and validated; ids must be unique. |
| `catalog` | integer (0-1000000) or null | no | Catalogue version the nodes were written against (informational). |

**Request body**

```json
{
 "name": "Shipping banner",
 "pageType": "checkout",
 "nodes": [
  {
   "id": "a1B2c3D4e5",
   "type": "content.text",
   "props": {
    "text": "Free shipping over $50"
   }
  }
 ],
 "catalog": 2
}
```

**Response** `201`

```json
{
 "block": {
  "id": "6c7d8e9f-0000-4000-8000-000000000001",
  "owner_email": "owner@example.com",
  "name": "Shipping banner",
  "page_type": "checkout",
  "nodes": [
   {
    "id": "a1B2c3D4e5",
    "type": "content.text",
    "props": {
     "text": "Free shipping over $50"
    }
   }
  ],
  "catalog": 2,
  "created_at": "2026-10-05T09:00:00.000Z",
  "created_by": "owner@example.com",
  "updated_at": "2026-10-05T09:00:00.000Z"
 },
 "issues": []
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body fails the schema (strict: unknown fields refused; name empty or over 80 characters).
- `400` `{"error":"nodes must be a non-empty list of blocks"}`, `a saved block holds at most 200 top-level blocks`, `unknown page type "<type>"`, or `{"error":"Not a list of blocks","issues":[...]}` when the nodes are not block nodes.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `409` `{"error":"A saved block with this name already exists"}`.
- `413` `The block is <n> KB; a saved block holds at most 256 KB.` when the serialized nodes exceed 256 KiB; a body over 512 KiB is refused before the route.
- `422` `{"error":"The block has errors to fix before it can be saved","issues":[...]}` when validation finds an error in the nodes (unknown block type, a block the page type does not offer, duplicate ids, a bad prop...).
- `422` `{"error":"An account holds at most 200 saved blocks: delete one first"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- issues in a 201 answer are warnings; 422 issues name the blocks (blockId) and fields to fix.
- The full store, product, draft, preview and publish sequence is described in the *Build stores, product pages and checkouts* section of llm.md.

##### `PATCH /v1/editor/saved-blocks/:id`

**Scope** `checkouts.write` - **Update a saved block**

Renames a saved block, replaces its nodes (validated like a save), or moves it to another page type (the stored nodes are validated again for it). Send only the fields to change.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Saved block id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-80, trimmed) | no | Block name, unique per account. |
| `pageType` | string: '*' or a page type: checkout \| landing \| post_sell \| thank_you | no | Page type the block is for; '*' = validated against every page type and offered on all of them. |
| `nodes` | array of block nodes (1-200 top-level, max 256 KiB) | no | The block subtree, in the document node format of GET /v1/editor/catalog. Migrated to the current catalogue and validated; ids must be unique. |
| `catalog` | integer (0-1000000) or null | no | Catalogue version the nodes were written against (informational). |

**Request body**

```json
{
  "name": "Free shipping banner"
}
```

**Response**

```json
{
 "block": {
  "id": "6c7d8e9f-0000-4000-8000-000000000001",
  "owner_email": "owner@example.com",
  "name": "Free shipping banner",
  "page_type": "checkout",
  "nodes": [
   {
    "id": "a1B2c3D4e5",
    "type": "content.text",
    "props": {
     "text": "Free shipping over $50"
    }
   }
  ],
  "catalog": 2,
  "created_at": "2026-10-05T09:00:00.000Z",
  "created_by": "owner@example.com",
  "updated_at": "2026-10-05T09:00:00.000Z"
 },
 "issues": []
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when :id is not a UUID or the body fails the schema.
- `400` `{"error":"nodes must be a non-empty list of blocks"}`, `a saved block holds at most 200 top-level blocks`, `unknown page type "<type>"`, or `{"error":"Not a list of blocks","issues":[...]}` when the nodes are not block nodes.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the id is unknown or belongs to another account.
- `409` `{"error":"A saved block with this name already exists"}`.
- `413` `The block is <n> KB; a saved block holds at most 256 KB.` when the serialized nodes exceed 256 KiB; a body over 512 KiB is refused before the route.
- `422` `{"error":"The block has errors to fix before it can be saved","issues":[...]}` when validation finds an error in the nodes (unknown block type, a block the page type does not offer, duplicate ids, a bad prop...).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Without new nodes or a new page type the stored nodes are not re-validated and issues is [].

##### `DELETE /v1/editor/saved-blocks/:id`

**Scope** `checkouts.write` - **Delete a saved block**

Deletes a saved block. Documents that inserted it keep their copy.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Saved block id. |

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` `{"error":"Invalid"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the id is unknown or belongs to another account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

#### Pages

The funnel pages (landing, offer and thank-you pages) and their documents.

##### `GET /v1/v5/funnels`

**Scope** `checkouts.read` - **List funnel pages**

Lists the account's funnel pages (landing, post-sell and thank-you) that are not archived, with a total for paging.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string | no | Case-insensitive search in the name, at most 200 characters. |
| `pageType` | enum | no | landing, post_sell or thank_you. |
| `status` | enum | no | published: published_version > 0. draft: pending_review is true (changes not yet published, including never-published items). |
| `limit` | integer; default `100` | no | 1-500. |
| `offset` | integer; default `0` | no | 0 or more. |

**Response** `200`

```json
{
  "items": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "name": "Spring landing",
      "page_type": "landing",
      "owner_affiliate_id": null,
      "visibility": "private",
      "draft_revision": 3,
      "published_version": 1,
      "pending_review": false,
      "updated_at": "2026-11-16T12:00:00.000Z",
      "created_at": "2026-11-16T12:00:00.000Z"
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `items[]` | object[] | id, name, page_type, owner_affiliate_id, visibility, draft_revision, published_version, pending_review, updated_at, created_at. Newest update first. Documents are not included: read one item for them. |
| `total` | integer | Count of every matching item, ignoring limit and offset. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: an unknown query key, q over 200 characters, an unknown enum value, or limit/offset out of bounds.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The query is strict: any other query key answers 400.
- status=draft is not 'never published': it selects every item with unpublished changes.
- Thank-you pages use the same document editor and publish, version and restore lifecycle as landing and post-sell pages.

##### `POST /v1/v5/funnels`

**Scope** `checkouts.write` - **Create a funnel page**

Creates a merchant-owned draft page of the given type with its default document. A new post_sell page starts from the PS-01 template with an automatic store-product offer policy (one eligible bestseller, no extra discount, active variants, quantity choices 1-10); landing and thank_you pages start from their default documents.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | 1-160 characters after trim. |
| `pageType` | enum | **yes** | landing, post_sell or thank_you. Required for pages (400 Choose a page type); it cannot change later. |

**Request body**

```json
{
  "name": "Receipt page",
  "pageType": "thank_you"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "11111111-1111-4111-8111-111111111111",
    "name": "Campaign funnel",
    "draft_revision": 0,
    "published_version": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.page_type` | string | landing, post_sell or thank_you. |
| `item.draft_document / item.draft_offer` | object \| null | Current draft builder document and draft offer configuration. |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: name missing, unknown pageType, or an unknown key.
- `400` {"error":"Enter a name of 1-160 characters."} (the code uses a U+2013 en dash between 1 and 160): the trimmed name is empty or too long.
- `400` {"error":"Choose a page type."}: pageType is missing.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The draft is not live: edit it with PUT /v1/v5/funnels/:id/document/draft, publish it with POST /v1/v5/funnels/:id/document/publish, then reference it from a flow node.
- A post_sell page is created with its document and its draft offer together. Smart selection uses the order's store, account and currency, excludes products already bought, and the page is skipped when nothing is eligible. Creating it starts no order or payment.

##### `GET /v1/v5/funnels/:id`

**Scope** `checkouts.read` - **Read a funnel page**

Reads one funnel page with its draft document, draft offer and revision counters. For the published document and the publication usage, read GET /v1/v5/funnels/:id/document.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Response** `200`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000001",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring landing",
    "page_type": "landing",
    "visibility": "private",
    "draft_document": {
      "format": 1,
      "pageType": "landing",
      "root": {
        "props": {}
      },
      "content": []
    },
    "draft_offer": null,
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.page_type` | string | landing, post_sell or thank_you. |
| `item.draft_document / item.draft_offer` | object \| null | Current draft builder document and draft offer configuration. |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `PATCH /v1/v5/funnels/:id`

**Scope** `checkouts.write` - **Rename a funnel page**

Changes the name only. The document, revisions and published versions are not touched.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | 1-160 characters after trim. The only accepted key. |

**Request body**

```json
{
  "name": "Spring offer"
}
```

**Response** `200`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000001",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring offer",
    "page_type": "landing",
    "visibility": "private",
    "draft_document": {
      "format": 1,
      "pageType": "landing",
      "root": {
        "props": {}
      },
      "content": []
    },
    "draft_offer": null,
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  },
  "funnel": {
    "id": "00000000-0000-4000-8000-000000000001",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring offer",
    "page_type": "landing",
    "visibility": "private",
    "draft_document": {
      "format": 1,
      "pageType": "landing",
      "root": {
        "props": {}
      },
      "content": []
    },
    "draft_offer": null,
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The stored row after the rename. |
| `funnel` | object | The same page as GET /v1/v5/funnels/:id returns it. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, name is missing, or another key was sent.
- `400` {"error":"Enter a name of 1-160 characters."} (U+2013 en dash in the code): the trimmed name is empty or too long.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `DELETE /v1/v5/funnels/:id`

**Scope** `checkouts.write` - **Archive a funnel page**

Archives the page: it leaves the list and can no longer be read or edited. Published versions stay stored so sessions already pinned to them keep working.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true once archived. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID (the default flow cannot be archived).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: already archived.
- `409` {"error":"Remove this page from the draft and published flows before archiving."}: a flow that is not archived references the page in its draft or published graph.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no restore endpoint: archiving is final for the API.
- Remove the page from every flow draft and republish those flows first.

##### `POST /v1/v5/funnels/:id/assets`

**Scope** `checkouts.write` - **Upload media for a funnel page**

Stores one image or video for an editable funnel page and returns its hosted URL, to place in native image, gallery or video blocks of the page document. The bytes are checked against the declared type and SVG is reduced to static vector artwork.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `contentType` | enum | **yes** | image/png, image/jpeg, image/webp, image/gif, image/avif, image/svg+xml, video/mp4 or video/webm. Must match the file signature (415). |
| `base64` | string | **yes** | The file as standard base64 (^[A-Za-z0-9+/]+={0,2}$: no data: prefix, no line breaks), 4 to 27970219 characters. Decoded size at most 20 MiB (SVG at most 512 KiB). |

**Request body**

```json
{
  "contentType": "image/png",
  "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg=="
}
```

**Response** `200`

```json
{
  "url": "https://media.example.com/storage/v1/object/public/shop-assets/storefront/00000000-0000-4000-8000-000000000001/funnel-1763294400000-a1b2c3d4.png",
  "path": "storefront/00000000-0000-4000-8000-000000000001/funnel-1763294400000-a1b2c3d4.png"
}
```

| response field | type | description |
|---|---|---|
| `url` | string | Public HTTPS URL of the stored file, to use in the page document. |
| `path` | string | Storage path: storefront/<page id>/funnel-<timestamp>-<random>.<ext>. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, contentType is not in the list, base64 is missing or too long, or an unknown key was sent.
- `400` {"error":"Invalid asset encoding."}: base64 is not canonical base64.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `413` {"error":"Asset must be 20 MB or smaller."} (decoded size), {"error":"SVG must be 512 KB or smaller."}, or {"error":"Request body is too large"} for a body over 27970219 bytes.
- `415` {"error":"Asset format does not match its content."}: the bytes do not carry the signature of contentType.
- `422` {"error":"SVG must contain static vector artwork without active content or external references."}: scripts, event handlers, external references or unsafe CSS in an SVG.
- `422` An MP4 whose index (moov) is at the end of the file is refused with a message asking to re-encode it with -movflags +faststart.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `502` {"error":"storage upload failed: <status> ..."}: the media storage refused the file; nothing was saved.

**Gotchas**

- No HTML, script or font upload. Fonts go through /v1/editor/fonts; font types are refused here.
- Upload the file and put the returned url in the document; never embed base64 media inside a builder document (the document budget is 2 MiB).
- Each upload stores a new file; uploading the same bytes twice gives two URLs.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `GET /v1/v5/funnels/:id/document`

**Scope** `checkouts.read` - **Read a funnel page document**

Returns what the page editor needs: the pending draft document, the current published document, the default document of the page type, the revision counters, the validation issues of the draft, and which published flows still serve an older version of this page.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Response** `200`

```json
{
  "funnel": {
    "id": "00000000-0000-4000-8000-000000000001",
    "name": "Spring upsell"
  },
  "publication": {
    "total": 1,
    "current": 0,
    "staleFlows": [
      {
        "id": "00000000-0000-4000-8000-000000000002",
        "name": "Spring flow"
      }
    ]
  },
  "draft": {
    "format": 1,
    "pageType": "post_sell",
    "root": {
      "props": {
        "contentWidth": 1080
      }
    },
    "content": [
      {
        "id": "offer-1",
        "type": "upsell.offer",
        "props": {
          "offerId": "primary"
        },
        "slots": {}
      }
    ]
  },
  "published": {
    "format": 1,
    "pageType": "post_sell",
    "root": {
      "props": {
        "contentWidth": 1080
      }
    },
    "content": [
      {
        "id": "offer-1",
        "type": "upsell.offer",
        "props": {
          "offerId": "primary"
        },
        "slots": {}
      }
    ]
  },
  "defaultDocument": {
    "format": 1,
    "pageType": "post_sell",
    "root": {
      "props": {
        "contentWidth": 1080
      }
    },
    "content": [
      {
        "id": "offer-1",
        "type": "upsell.offer",
        "props": {
          "offerId": "primary"
        },
        "slots": {}
      }
    ]
  },
  "draftRevision": 4,
  "publishedVersion": 2,
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `funnel` | object | id and name. |
| `publication` | object | Published flows using the page: total, current (flows pinned to the current published version) and staleFlows[] (id, name) still pinned to an older version. Republish those flows to serve the new version. |
| `draft` | object \| null | The draft document when it has unpublished changes or the page was never published; null when the draft equals the published version. |
| `published` | object \| null | Document of the latest published version, null when never published. |
| `defaultDocument` | object | Default document of the page type (the starting template). |
| `draftRevision / publishedVersion` | integer | Send draftRevision as baseRevision on save, publish, discard and restore. |
| `issues` | object[] | Validation issues of the draft: severity (error or warning), code, message, blockId?, field?. Any error blocks publication. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- When draft is null, edit from published: it is the current content.
- Valid page types are landing, post_sell and thank_you; a document must keep the page's type.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `PUT /v1/v5/funnels/:id/document/draft`

**Scope** `checkouts.write` - **Save a funnel page draft**

Saves the complete builder document of a landing, post-sell or thank-you page, and optionally its offer configuration, with optimistic revision control. The draft becomes pending review until published. Returns the new revision and the validation issues of the saved document.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the page, as last read. A different value answers 409. |
| `document` | object | **yes** | The complete format 1 builder document (format, pageType, root.props, content[] of blocks {id, type, props, slots}), with pageType equal to the page's type (400 The document has the wrong page type). Serialized at most 2 MiB (413), blocks nested at most 64 deep. Older documents are migrated on save. Read and keep the current protected blocks. |
| `offer` | object \| null | no | Commerce of the page. Omitted: the stored draft offer is kept (adapted when the document changes template). null: removes the draft offer. Otherwise one of three shapes, validated strictly: a single fixed offer (the offer.* fields below), a list {offers:[...], behavior?}, or automatic selection {offers:[], selection:{...}}. Post-sell pages need an offer to publish. Landing pages accept 1-10 explicit offers for pre-purchase selection (no selection, behavior, timer or shippingMinor: 422). |
| `offer.productId` | uuid | **yes** | Active product of the account. |
| `offer.variantId` | uuid | **yes** | Default variant of that product. |
| `offer.quantity` | integer | **yes** | 1-10. |
| `offer.unitPriceMinor` | integer | **yes** | 0-100000000, minor units. 0 only together with free: true. |
| `offer.currency` | enum | **yes** | USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS or ZAR. All offers of a list share one currency. |
| `offer.free` | boolean | no | Only the value true: a free offer, which needs unitPriceMinor 0 and shippingMinor 0. |
| `offer.compareAtMinor` | integer | no | 0-100000000, compare-at unit price shown with savings. |
| `offer.shippingMinor` | integer | no | 0-100000000, extra shipping of a post-sell offer. Refused on landing pages (422). |
| `offer.purchaseMode` | enum | no | one_time or subscription. subscription needs subscriptionProductId; one_time refuses it. |
| `offer.subscriptionProductId` | uuid | no | Subscription plan of the account, only with purchaseMode subscription. Landing pages only: an active owned simple fixed-price USD plan; its recurring terms are fingerprinted at publication. |
| `offer.initialShippingMinor` | integer | no | 0-100000000. Landing pages: shipping of the initial order when this offer is selected. |
| `offer.initialProtectionMinor` | integer | no | 0-100000000. Landing pages: shipping protection price of the initial order when this offer is selected. |
| `offer.initialInclusions` | object[] | no | Landing pages only: up to 4 free products added with this offer, distinct and different from the paid variant and its choices. |
| `offer.initialInclusions[].productId / variantId` | uuid | **yes** | Included product and variant of the account (not recurring). |
| `offer.initialInclusions[].quantity` | integer | **yes** | 1-10. |
| `offer.choices` | object | no | Buyer choices: variantIds (1-100 unique UUIDs including variantId), minQuantity and maxQuantity (1-10, bracketing quantity). Omitted: the buyer gets the default variant and quantity. |
| `offer.choices.variantIds / minQuantity / maxQuantity` | uuid[] / integer / integer | no | See choices. |
| `offer.timer` | object | no | Offer countdown: durationSeconds 1-86400, optional deadline (ISO UTC date-time), expiryBehavior hide-offer, auto-decline-and-continue, show-expired-text or keep-offer. Pinned per session and node; refused on landing pages (422). |
| `offer.offers` | object[] | no | Up to 20 explicit offers, each with an id and the offer.* fields; at least one unless selection is set, none when selection is set. |
| `offer.offers[].id` | string | **yes** | Offer id, ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$, unique in the list; product blocks reference it through offerId or offerIds. |
| `offer.offers[].productId` | uuid | **yes** | Active product of the account. |
| `offer.offers[].variantId` | uuid | **yes** | Default variant of that product. |
| `offer.offers[].quantity` | integer | **yes** | 1-10. |
| `offer.offers[].unitPriceMinor` | integer | **yes** | 0-100000000, minor units. 0 only together with free: true. |
| `offer.offers[].currency` | enum | **yes** | USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS or ZAR. All offers of a list share one currency. |
| `offer.offers[].free` | boolean | no | Only the value true: a free offer, which needs unitPriceMinor 0 and shippingMinor 0. |
| `offer.offers[].compareAtMinor` | integer | no | 0-100000000, compare-at unit price shown with savings. |
| `offer.offers[].shippingMinor` | integer | no | 0-100000000, extra shipping of a post-sell offer. Refused on landing pages (422). |
| `offer.offers[].purchaseMode` | enum | no | one_time or subscription. subscription needs subscriptionProductId; one_time refuses it. |
| `offer.offers[].subscriptionProductId` | uuid | no | Subscription plan of the account, only with purchaseMode subscription. Landing pages only: an active owned simple fixed-price USD plan; its recurring terms are fingerprinted at publication. |
| `offer.offers[].initialShippingMinor` | integer | no | 0-100000000. Landing pages: shipping of the initial order when this offer is selected. |
| `offer.offers[].initialProtectionMinor` | integer | no | 0-100000000. Landing pages: shipping protection price of the initial order when this offer is selected. |
| `offer.offers[].initialInclusions` | object[] | no | Landing pages only: up to 4 free products added with this offer, distinct and different from the paid variant and its choices. |
| `offer.offers[].initialInclusions[].productId / variantId` | uuid | **yes** | Included product and variant of the account (not recurring). |
| `offer.offers[].initialInclusions[].quantity` | integer | **yes** | 1-10. |
| `offer.offers[].choices` | object | no | Buyer choices: variantIds (1-100 unique UUIDs including variantId), minQuantity and maxQuantity (1-10, bracketing quantity). Omitted: the buyer gets the default variant and quantity. |
| `offer.offers[].choices.variantIds / minQuantity / maxQuantity` | uuid[] / integer / integer | no | See choices. |
| `offer.offers[].timer` | object | no | Offer countdown: durationSeconds 1-86400, optional deadline (ISO UTC date-time), expiryBehavior hide-offer, auto-decline-and-continue, show-expired-text or keep-offer. Pinned per session and node; refused on landing pages (422). |
| `offer.behavior` | enum | no | Only independent: each listed offer is accepted or declined on its own. Refused on landing pages. |
| `offer.selection` | object | no | Automatic product selection (post-sell). With selection, offers must be []. |
| `offer.selection.mode` | enum | **yes** | smart (store bestsellers) or quantity (more units of the purchased product). |
| `offer.selection.limit` | integer; default `3` | no | 1-6 products shown. |
| `offer.selection.discount.kind` | enum | **yes** | percent (value 0-90), fixed (minor units off) or exact (exact unit price, at least 1). |
| `offer.selection.discount.value` | integer | **yes** | 0-100000000, read per kind. |
| `offer.selection.quantities` | integer[]; default `[1,2,3]` | no | 1-6 unique quantities of 1-10 (quantity mode). |
| `offer.selection.choices` | object | no | Smart mode buyer choices: allowVariants (boolean) and maxQuantity (1-10). Omitted keeps the fixed legacy behavior. |
| `offer.selection.timer` | object | no | Same shape as offer.timer. |

**Request body**

```json
{
  "baseRevision": 7,
  "document": {
    "format": 1,
    "pageType": "post_sell",
    "root": {
      "props": {
        "contentWidth": 1080
      }
    },
    "content": [
      {
        "id": "products",
        "type": "upsell.products",
        "props": {
          "offerIds": [],
          "layout": "grid",
          "columns": 2,
          "cardsPerView": 3,
          "gap": 12,
          "peek": 32,
          "showArrows": true,
          "stackOnMobile": true,
          "preAddToCart": false,
          "allowSelection": false,
          "selectLabel": {
            "$localized": true,
            "values": {
              "en": "Add to cart",
              "fr": "Ajouter au panier",
              "es": "AÃ±adir al carrito",
              "it": "Add to cart",
              "pt": "Add to cart",
              "pl": "Add to cart"
            }
          }
        },
        "slots": {
          "content": [
            {
              "id": "fURkoqIuA5",
              "type": "upsell.offer",
              "props": {
                "offerId": "",
                "templateId": "",
                "layout": "bordered",
                "descriptionLabel": {
                  "$localized": true,
                  "values": {
                    "en": "Description",
                    "fr": "Description",
                    "es": "DescripciÃ³n",
                    "it": "Descrizione",
                    "pt": "DescriÃ§Ã£o",
                    "pl": "Opis"
                  }
                },
                "collapsibleDescription": false,
                "product": null,
                "productVariant": null,
                "allowedVariantIds": [],
                "minQuantity": 1,
                "maxQuantity": 1,
                "quantity": 1,
                "discountKind": "none",
                "discountValue": 0,
                "preAddToCart": false
              },
              "slots": {
                "header": [],
                "content": [
                  {
                    "id": "gnXDw1wVng",
                    "type": "upsell.media",
                    "props": {
                      "offerId": "",
                      "layout": "single",
                      "aspectRatio": "1/1",
                      "objectFit": "contain",
                      "thumbColumns": 4,
                      "thumbSize": 64,
                      "thumbInset": 0,
                      "thumbInsetEnd": null,
                      "thumbMarginTop": null,
                      "thumbRowGap": null,
                      "gap": 12,
                      "peek": 40,
                      "showBorder": false,
                      "includeMainThumbnail": true,
                      "thumbnailBorder": true,
                      "thumbAspectRatio": "square",
                      "thumbSizing": "fixed-width",
                      "thumbnailSources": [],
                      "allowZoom": false
                    },
                    "variant": "single"
                  },
                  {
                    "id": "l_dbY2mBRE",
                    "type": "content.heading",
                    "props": {
                      "text": "{offer.title}",
                      "level": "h2"
                    },
                    "variant": "plain"
                  },
                  {
                    "id": "BzOmANRB2P",
                    "type": "upsell.price",
                    "props": {
                      "offerId": "",
                      "currencyDisplay": "symbol",
                      "zeroLabel": {
                        "$localized": true,
                        "values": {
                          "en": "Free",
                          "fr": "Gratuit",
                          "es": "Gratis",
                          "it": "Gratis",
                          "pt": "GrÃ¡tis",
                          "pl": "BezpÅ‚atnie"
                        }
                      },
                      "separator": "space",
                      "trimZeroDecimals": false,
                      "appearance": "price-only",
                      "priceWeight": 700,
                      "compareWeight": 400,
                      "showSavings": true,
                      "savingsLabel": {
                        "$localized": true,
                        "values": {
                          "en": "Save {offer.savings_percent}",
                          "fr": "Ã‰conomisez {offer.savings_percent}",
                          "es": "Ahorra {offer.savings_percent}",
                          "it": "Risparmia {offer.savings_percent}",
                          "pt": "Economize {offer.savings_percent}",
                          "pl": "OszczÄ™dÅº {offer.savings_percent}"
                        }
                      },
                      "priceColor": null,
                      "compareColor": "#767676",
                      "savingsColor": null,
                      "chipColor": null,
                      "priceSize": 24,
                      "compareSize": 18,
                      "savingsSize": 14,
                      "amountAlignment": "baseline",
                      "amountGap": null,
                      "savingsGap": null,
                      "savingsWeight": null
                    },
                    "variant": "price-only"
                  },
                  {
                    "id": "180pIEfuHO",
                    "type": "upsell.variant",
                    "props": {
                      "offerId": "",
                      "controlPaddingX": null,
                      "controlTextColor": null,
                      "controlLabelColor": null,
                      "controlHeight": null,
                      "controlFontSize": null,
                      "labelSize": null,
                      "labelGap": null,
                      "controlRadius": null,
                      "controlBorderColor": null,
                      "controlIndicator": "chevron",
                      "appearance": "floating-select",
                      "label": {
                        "$localized": true,
                        "values": {
                          "en": "Variant",
                          "fr": "Variante",
                          "es": "Variante",
                          "it": "Variante",
                          "pt": "Variante",
                          "pl": "Wariant"
                        }
                      },
                      "optionName": "",
                      "combined": true,
                      "showLabel": false,
                      "columns": 1,
                      "swatchSize": 20,
                      "selectedSwatchSize": null,
                      "selectedSwatchBorderWidth": null,
                      "selectedSwatchRingWidth": null,
                      "swatchBorderWidth": null
                    },
                    "variant": "floating-select"
                  },
                  {
                    "id": "b7sAd-ZFxS",
                    "type": "upsell.quantity",
                    "props": {
                      "offerId": "",
                      "controlPaddingX": null,
                      "controlTextColor": null,
                      "controlLabelColor": null,
                      "controlHeight": null,
                      "controlFontSize": null,
                      "labelSize": null,
                      "labelGap": null,
                      "controlRadius": null,
                      "controlBorderColor": null,
                      "controlIndicator": "chevron",
                      "controlButtonSize": 20,
                      "controlButtonWidth": null,
                      "controlWidth": null,
                      "appearance": "labelled-select",
                      "label": {
                        "$localized": true,
                        "values": {
                          "en": "Quantity",
                          "fr": "QuantitÃ©",
                          "es": "Cantidad",
                          "it": "QuantitÃ ",
                          "pt": "Quantidade",
                          "pl": "IloÅ›Ä‡"
                        }
                      }
                    },
                    "variant": "labelled-select"
                  },
                  {
                    "id": "qKFfuAPOY9",
                    "type": "funnel.accept",
                    "props": {
                      "offerId": "",
                      "label": {
                        "$localized": true,
                        "values": {
                          "en": "Add to cart",
                          "fr": "Ajouter au panier",
                          "es": "AÃ±adir al carrito",
                          "it": "Add to cart",
                          "pt": "Add to cart",
                          "pl": "Add to cart"
                        }
                      },
                      "scope": "single",
                      "appearance": "solid",
                      "disclosurePlacement": "after-button",
                      "successLabel": {
                        "$localized": true,
                        "values": {
                          "en": "Added âœ“",
                          "fr": "AjoutÃ© âœ“",
                          "es": "AÃ±adido âœ“",
                          "it": "Aggiunto âœ“",
                          "pt": "Adicionado âœ“",
                          "pl": "Dodano âœ“"
                        }
                      },
                      "errorLabel": {
                        "$localized": true,
                        "values": {
                          "en": "Please try again",
                          "fr": "Veuillez rÃ©essayer",
                          "es": "IntÃ©ntalo de nuevo",
                          "it": "Riprova",
                          "pt": "Tente novamente",
                          "pl": "SprÃ³buj ponownie"
                        }
                      },
                      "icon": null,
                      "fullWidth": true,
                      "align": "center",
                      "height": null,
                      "continueAfterAccept": false
                    },
                    "variant": "solid"
                  }
                ],
                "footer": []
              },
              "variant": "split"
            }
          ]
        },
        "variant": "grid"
      },
      {
        "id": "cart",
        "type": "funnel.cart",
        "props": {
          "heading": "Upsell cart",
          "showPaid": false
        }
      },
      {
        "id": "confirm",
        "type": "funnel.confirm",
        "props": {
          "label": "Confirm order",
          "scope": "selected"
        }
      },
      {
        "id": "decline",
        "type": "funnel.decline",
        "props": {}
      }
    ],
    "catalog": 6
  },
  "offer": {
    "offers": [
      {
        "id": "travel-bottle",
        "productId": "11111111-1111-4111-8111-111111111111",
        "variantId": "22222222-2222-4222-8222-222222222222",
        "quantity": 1,
        "unitPriceMinor": 1000,
        "currency": "USD"
      },
      {
        "id": "travel-pack",
        "productId": "11111111-1111-4111-8111-111111111111",
        "variantId": "22222222-2222-4222-8222-222222222222",
        "quantity": 2,
        "unitPriceMinor": 950,
        "currency": "USD"
      }
    ]
  }
}
```

**Response** `200`

```json
{
  "draftRevision": 8,
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `draftRevision` | integer | New revision to use in the next save/publication. |
| `issues` | array | Document issues; an editable incomplete draft is not proof it can publish. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseRevision is missing or negative, an unknown key, or offer fails its strict schema (for example a free offer with a price, duplicate offer ids, mixed currencies, selection together with offers).
- `400` {"error":"The document has the wrong page type."} or {"error":"Invalid page document.","issues":[...]}: the document is not an object of the page type or fails the shape check.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `409` {"error":"This draft changed in another tab. Reload before saving."}: baseRevision is not the current draft revision.
- `413` {"error":"The document is <n> KB; a builder document holds at most 2048 KB."}, or {"error":"Request body is too large"} for a body over 2.5 MiB.
- `422` Landing page offers: {"error":"Pre-purchase pages require explicit products."}, {"error":"Select between one and ten pre-purchase products."}, {"error":"Use the checkout shipping and timer settings for pre-purchase products."}, {"error":"Choose an explicit purchase mode and subscription plan."}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Always read GET /v1/v5/funnels/:id/document first and send its draftRevision; the save answers the next revision.
- Saving never touches a published version or a buyer session: sessions keep their pinned page and offer versions.
- An incomplete draft can be saved (issues lists what blocks publication). The document must keep the page's pageType and pass the shape check.
- Publication checks every referenced offerId and needs a visible product block and a global decline. funnel.slider counts as a visible offer presentation; offers hidden by ancestors, disabled columns, conditions, popups or deferred content.slider slots do not.
- Manual offers support explicit choices.variantIds and minQuantity/maxQuantity from 1 to 10; free offers need free: true, zero unit price and zero extra shipping.
- Automatic selection: PS-01 picks one store bestseller, PS-02 up to three, PS-03 offers quantities 1/2/3 of the purchased product at its paid unit price; templates add no discount by default. An explicit offer always wins over a template default.
- Display controls (showVariantSelector, showQuantitySelector, showComparePrice, showSavings) change presentation only, never prices or choices.
- Native presentation blocks funnel.slider, funnel.originalOrder, funnel.originalConfirmation and funnel.savings change presentation only. Original-order blocks show the captured initial order; the final Thank-you summary includes every captured initial and upsell order.
- Add and Remove update the local upsell cart; only the Confirm block submits a signed whole-cart quote.
- Upload media with POST /v1/v5/funnels/:id/assets and reference its URL; never embed base64 media in the document.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `DELETE /v1/v5/funnels/:id/document/draft`

**Scope** `checkouts.write` - **Discard a funnel page draft**

Replaces the draft with the latest published version (document and offer), clears pending review and advances the draft revision. Needs a published version and the current baseRevision, so a newer draft saved meanwhile is never lost.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision. This DELETE takes a JSON body. |

**Request body**

```json
{
  "baseRevision": 5
}
```

**Response** `200`

```json
{
  "ok": true,
  "draftRevision": 6
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true. |
| `draftRevision` | integer | New draft revision. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseRevision missing, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."} (archived page) or {"error":"Published version not found."}.
- `409` {"error":"The draft changed. Reload before discarding.","draftRevision":<current>}: stale baseRevision (the body carries the current revision).
- `409` {"error":"Publish a version before discarding the draft."}: the page was never published.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Send Content-Type: application/json with the body; a DELETE without baseRevision answers 400.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/funnels/:id/document/links`

**Scope** `checkouts.write` - **Issue a signed page preview link**

Issues a signed link, valid two hours, that renders the page's draft or published document, either as a preview page or as the editor canvas. The link carries only page and preview claims, never customer, session or payment data.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum | **yes** | preview (a page to open) or canvas (the editor canvas, which needs an allowed Origin header). |
| `mode` | enum | **yes** | draft or published. |
| `storeId` | uuid \| null | no | Store whose context the preview uses, one of GET /v1/v5/funnels/:id/document/stores (403 Preview store is not available). null signs an explicit no-store context; omitted signs none. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Origin` | string | no | Required for kind canvas: must be one of the API's configured CORS origins (403 Editor origin is not allowed). Ignored for preview. |

**Request body**

```json
{
  "kind": "preview",
  "mode": "draft",
  "storeId": null
}
```

**Response** `200`

```json
{
  "url": "https://preview.example.com/preview/funnel/00000000-0000-4000-8000-000000000001?accountId=acc_0123456789abcdef&kind=preview&mode=draft&origin=&exp=1763301600&sig=<hex>&storeId=null",
  "origin": "https://preview.example.com",
  "expiresAt": "2026-11-16T14:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `url` | string | Signed URL (preview/funnel/<id> or editor/canvas/funnel/<id>) carrying accountId, kind, mode, origin, exp, sig and storeId when given. |
| `origin` | string | Origin of the preview host. |
| `expiresAt` | string | Expiry, two hours after issue. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, kind or mode missing or unknown, storeId not a UUID, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `403` {"error":"Preview store is not available."}: storeId is not a store of the account. {"error":"Editor origin is not allowed."}: kind canvas without an allowed Origin header.
- `404` {"error":"Not found."}: the page is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `503` {"error":"Editor preview is not configured."}: the preview host or its signing secret is not set on the server.

**Gotchas**

- Use kind preview from an API client; canvas is meant for the dashboard editor frame.
- Anyone holding the URL can view the page until it expires; share it like a secret.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/funnels/:id/document/publish`

**Scope** `checkouts.write` - **Publish a funnel page**

Publishes the current draft as a new immutable version under a row lock: validates the document (no error issue), the offer and every product block binding, and resolves each offer against the active products, variants, prices and subscription plans of the account. Flows keep serving the version they were published with until they are republished; the answer lists the published flows still on an older version.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the page, as last read. A different value answers 409. |

**Request body**

```json
{
  "baseRevision": 5
}
```

**Response** `200`

```json
{
  "publishedVersion": 3,
  "draftRevision": 5,
  "issues": [],
  "publication": {
    "total": 1,
    "current": 0,
    "staleFlows": [
      {
        "id": "00000000-0000-4000-8000-000000000002",
        "name": "Spring flow"
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `publishedVersion` | integer | The new version number. |
| `draftRevision` | integer | Echo of baseRevision (publishing does not change the draft revision). |
| `issues` | array | Always [] on success. |
| `publication` | object | total, current and staleFlows[] (id, name): flows still pinned to an older page version. Republish them (POST /v1/v5/flows/:id/publish) to serve this version. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseRevision missing, or an unknown key (this route takes no note).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `409` {"error":"This draft changed. Reload before publishing."}: stale baseRevision.
- `422` {"error":"Fix the page before publishing.","issues":[...]}: the document has error issues.
- `422` {"error":"Choose at least one valid product before publishing this post-sell.","issues":[{"severity":"error","code":"offer-required",...}]}: a post-sell without a valid offer.
- `422` {"error":"A product block references a removed offer. Select an available product."}: a block names an offer id that is not configured.
- `422` Offer and plan checks: {"error":"Select an active product and variant in the offer currency."}, {"error":"Allowed variants must belong to the offered product."}, {"error":"Variant offer price unavailable."}, {"error":"Default variant price unavailable."}, {"error":"Offer currency is unsupported."}, {"error":"Included products are available on pre-purchase pages only."}, {"error":"Recurring post-sell payments are not supported by the reusable-token adapter."}, subscription plan refusals (for example {"error":"Select an owned USD subscription plan."}), included product refusals (for example {"error":"Choose up to four distinct included products."}), and the landing offer refusals of the draft route.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Publishing a page does not change any flow: flows stay pinned to the page version they were published with. Republish each flow listed in publication.staleFlows.
- Existing buyer sessions keep their pinned version; the new version applies to sessions of flows published after it.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `GET /v1/v5/funnels/:id/document/stores`

**Scope** `checkouts.read` - **List stores for a page preview**

Lists the account's stores (id and name), the choices for storeId of POST /v1/v5/funnels/:id/document/links, used to preview the page in a store context.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Response** `200`

```json
{
  "stores": [
    {
      "id": "00000000-0000-4000-8000-000000000003",
      "name": "Demo Store"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `stores[]` | object[] | id and name (internal name, else the domain) of each store of the account, sorted by name. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `GET /v1/v5/funnels/:id/document/versions`

**Scope** `checkouts.read` - **List funnel page versions**

Lists the published versions of the page, newest first, with who published each and its note, plus the current published version number.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Response** `200`

```json
{
  "versions": [
    {
      "version": 2,
      "createdAt": "2026-11-16T12:00:00.000Z",
      "createdBy": "owner@example.com",
      "note": ""
    },
    {
      "version": 1,
      "createdAt": "2026-11-16T12:00:00.000Z",
      "createdBy": "owner@example.com",
      "note": ""
    }
  ],
  "publishedVersion": 2
}
```

| response field | type | description |
|---|---|---|
| `versions[]` | object[] | version, createdAt, createdBy (the publisher's e-mail, or the key owner's e-mail for an API key) and note (empty for pages). |
| `publishedVersion` | integer | Latest published version, 0 when never published. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the page is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Restoring a version (POST /v1/v5/funnels/:id/document/versions/:version/restore) copies it into the draft; history is never rewritten.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/funnels/:id/document/versions/:version/restore`

**Scope** `checkouts.write` - **Restore a funnel page version into the draft**

Copies the document and offer of a published version into the draft (pending review) with optimistic revision control. Nothing is published: publish the draft afterwards to make it live.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |
| `version` | integer | **yes** | Published version number, positive integer. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the page, as last read. A different value answers 409. |

**Request body**

```json
{
  "baseRevision": 5
}
```

**Response** `200`

```json
{
  "draftRevision": 6
}
```

| response field | type | description |
|---|---|---|
| `draftRevision` | integer | New draft revision. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, version is not a positive integer, baseRevision missing, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."} (archived page) or {"error":"Published version not found."}.
- `409` {"error":"The draft changed."}: stale baseRevision.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Buyer sessions keep their pinned version.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/funnels/:id/duplicate`

**Scope** `checkouts.write` - **Duplicate a funnel page**

Creates a new unpublished page with the source page's type, draft document and draft offer under a new name. The copy has its own revision history starting at 0.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Funnel page UUID (from GET /v1/v5/funnels). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Name of the copy, 1-160 characters after trim. The only accepted key. |

**Request body**

```json
{
  "name": "Spring landing copy"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000003",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring landing copy",
    "page_type": "landing",
    "visibility": "private",
    "draft_document": {
      "format": 1,
      "pageType": "landing",
      "root": {
        "props": {}
      },
      "content": []
    },
    "draft_offer": null,
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.page_type` | string | landing, post_sell or thank_you. |
| `item.draft_document / item.draft_offer` | object \| null | Current draft builder document and draft offer configuration. |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, name missing, or another key.
- `400` {"error":"Enter a name of 1-160 characters."} (U+2013 en dash in the code).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"pages"} when the plan excludes the pages tool.
- `403` {"error":"Forbidden"}: the page id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the source page is archived, or id is default (only flows have a default).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The copy is a draft: publish it before a flow can use it.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

#### Flows

The flows (post-purchase journeys): graph drafts, publication, assignment, saved links and previews.

##### `GET /v1/v5/flows`

**Scope** `checkouts.read` - **List flows**

Lists the account's flows that are not archived, with the number of saved offer links of each and a total for paging.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string | no | Case-insensitive search in the name, at most 200 characters. |
| `pageType` | enum | no | landing, post_sell or thank_you. Accepted for symmetry and ignored for flows. |
| `status` | enum | no | published: published_version > 0. draft: pending_review is true (changes not yet published, including never-published items). |
| `limit` | integer; default `100` | no | 1-500. |
| `offset` | integer; default `0` | no | 0 or more. |

**Response** `200`

```json
{
  "items": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "name": "Spring flow",
      "owner_affiliate_id": null,
      "visibility": "private",
      "draft_revision": 3,
      "published_version": 1,
      "pending_review": false,
      "updated_at": "2026-11-16T12:00:00.000Z",
      "created_at": "2026-11-16T12:00:00.000Z",
      "links_count": 2
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `items[]` | object[] | id, name, owner_affiliate_id, visibility, draft_revision, published_version, pending_review, updated_at, created_at, links_count (saved offer links of the flow that are not archived). Newest update first. Documents and graphs are not included: read one item for them. |
| `total` | integer | Count of every matching item, ignoring limit and offset. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: an unknown query key, q over 200 characters, an unknown enum value, or limit/offset out of bounds.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The query is strict: any other query key answers 400.
- status=draft is not 'never published': it selects every item with unpublished changes.

##### `POST /v1/v5/flows`

**Scope** `checkouts.write` - **Create a flow**

Creates a merchant-owned draft flow whose graph is Entry point -> Checkout -> Thank-you. Edit it with PUT /v1/v5/flows/:id/draft, publish it, then assign it to checkouts.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | 1-160 characters after trim. |
| `pageType` | enum | no | landing, post_sell or thank_you. Accepted and ignored for flows. |

**Request body**

```json
{
  "name": "Spring flow"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000002",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring flow",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "checkout",
          "kind": "checkout",
          "name": "Checkout",
          "position": {
            "x": 400,
            "y": 80
          }
        },
        {
          "id": "thank-you",
          "kind": "thank_you",
          "name": "Thank-you",
          "position": {
            "x": 720,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "checkout"
        },
        {
          "from": "checkout",
          "output": "next",
          "to": "thank-you"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.draft_graph` | object | Current draft graph (format 1, entry, nodes, edges). |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: name missing, unknown pageType value, or an unknown key.
- `400` {"error":"Enter a name of 1-160 characters."} (the code uses a U+2013 en dash between 1 and 160): the trimmed name is empty or too long.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The Entry point node is fixed: keep its id, position and graph.entry on every draft save.
- The default Checkout node names no checkout. A flow with a landing page or with several checkout nodes must name a checkout on every checkout node before it can publish.

##### `GET /v1/v5/flows/:id`

**Scope** `checkouts.read` - **Read a flow**

Reads one flow with its draft graph and revision counters. The id default returns the built-in read-only default flow (Checkout -> Thank-you) used by checkouts that have no assigned flow.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). Or the literal default for the built-in default flow. |

**Response** `200`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000002",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring flow",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "checkout",
          "kind": "checkout",
          "name": "Checkout",
          "position": {
            "x": 400,
            "y": 80
          }
        },
        {
          "id": "thank-you",
          "kind": "thank_you",
          "name": "Thank-you",
          "position": {
            "x": 720,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "checkout"
        },
        {
          "from": "checkout",
          "output": "next",
          "to": "thank-you"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.draft_graph` | object | Current draft graph (format 1, entry, nodes, edges). |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |
| `item.readOnly` | boolean | Only on id=default: true. The default flow has draft_revision 0 and published_version 0 and cannot be saved, published or archived. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is neither a UUID nor default.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the flow is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- GET /v1/v5/flows/default answers {"item":{"id":"default","name":"Default","draft_graph":<Checkout -> Thank-you>,"draft_revision":0,"published_version":0,"pending_review":false,"readOnly":true}}. Duplicate it to get an editable copy.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `PATCH /v1/v5/flows/:id`

**Scope** `checkouts.write` - **Rename a flow**

Changes the name only. The document, graph, revisions and published versions are not touched.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | 1-160 characters after trim. The only accepted key. |

**Request body**

```json
{
  "name": "Spring offer"
}
```

**Response** `200`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000002",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring offer",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "checkout",
          "kind": "checkout",
          "name": "Checkout",
          "position": {
            "x": 400,
            "y": 80
          }
        },
        {
          "id": "thank-you",
          "kind": "thank_you",
          "name": "Thank-you",
          "position": {
            "x": 720,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "checkout"
        },
        {
          "from": "checkout",
          "output": "next",
          "to": "thank-you"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  },
  "funnel": {
    "id": "00000000-0000-4000-8000-000000000002",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring offer",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "checkout",
          "kind": "checkout",
          "name": "Checkout",
          "position": {
            "x": 400,
            "y": 80
          }
        },
        {
          "id": "thank-you",
          "kind": "thank_you",
          "name": "Thank-you",
          "position": {
            "x": 720,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "checkout"
        },
        {
          "from": "checkout",
          "output": "next",
          "to": "thank-you"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The stored row after the rename. |
| `funnel` | object | The same flow (the key is named funnel for both kinds) as GET /v1/v5/flows/:id returns it. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, name is missing, or another key was sent.
- `400` {"error":"Enter a name of 1-160 characters."} (U+2013 en dash in the code): the trimmed name is empty or too long.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `DELETE /v1/v5/flows/:id`

**Scope** `checkouts.write` - **Archive a flow**

Archives the flow: it leaves the list and can no longer be read, edited or used for new links. Published versions stay stored for sessions already pinned to them.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true once archived. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID (the default flow cannot be archived).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: already archived.
- `409` {"error":"Remove this flow from its store and checkout assignments before archiving."}: a store routing or a checkout assignment still points to the flow.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no restore endpoint: archiving is final for the API.
- Unassign the flow first (POST /v1/v5/flows/default/assign with the checkout ids moves them back to the default flow) and remove it from store routing.

##### `POST /v1/v5/flows/:id/assign`

**Scope** `checkouts.write` - **Assign a flow to checkouts**

Checks 1-100 checkouts one by one against the flow's published version and, when preview is false, assigns the flow to every checkout that passes. id default moves the checkouts back to the built-in default flow (clears their assignment). The answer reports each checkout's result.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid \| default | **yes** | Published flow UUID, or default to clear the assignment. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutIds` | uuid[] | **yes** | 1-100 checkout UUIDs of the account (duplicates are merged). |
| `preview` | boolean | **yes** | true: report only, nothing is written. false: assign every checkout that passes. |

**Request body**

```json
{
  "checkoutIds": [
    "00000000-0000-4000-8000-000000000003"
  ],
  "preview": true
}
```

**Response** `200`

```json
{
  "preview": true,
  "report": [
    {
      "checkoutId": "00000000-0000-4000-8000-000000000003",
      "ok": true,
      "issues": []
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `preview` | boolean | Echo of the request. |
| `report[]` | object[] | checkoutId, ok, issues[] (code, message): for example assignment (the flow does not contain this checkout) or ownership (affiliate owner conflict). Only ok checkouts are assigned when preview is false. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id neither a UUID nor default, checkoutIds empty or over 100 or not UUIDs, preview missing, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow or one of the checkouts is unknown or belongs to another account (checked before any report).
- `404` {"error":"Not found."}: the flow is archived.
- `422` {"error":"Publish the flow before assigning it."}: the flow has no published version.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Assignment uses the PUBLISHED version; publish the draft first.
- A flow whose checkout nodes all name specific checkouts can only be assigned to those checkouts (issue assignment otherwise).
- Run with preview true first, then false; a false run writes only the checkouts that pass and reports the others.

##### `PUT /v1/v5/flows/:id/draft`

**Scope** `checkouts.write` - **Save a flow draft**

Saves the flow's draft graph with optimistic revision control. An incomplete graph can be saved as long as its shape is valid; the answer carries the full validation issues. The draft becomes pending review until published.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the flow, as last read. A different value answers 409. |
| `graph` | object | **yes** | The flow graph, strict: {format: 1, entry, nodes, edges}. Serialized at most 128 KiB. A draft may be incomplete but must have a valid shape (400 Invalid graph.). |
| `graph.format` | integer | **yes** | Always 1. |
| `graph.entry` | string | **yes** | Id of the Entry point node (^[A-Za-z0-9_-]{1,80}$). |
| `graph.nodes` | object[] | **yes** | 2 to 65 nodes: at most 64 content nodes plus the Entry point. |
| `graph.nodes[].id` | string | **yes** | Unique node id, ^[A-Za-z0-9_-]{1,80}$. |
| `graph.nodes[].kind` | enum | **yes** | entry, landing, checkout, post_sell, thank_you, ab_test or condition. |
| `graph.nodes[].name` | string | **yes** | 1-120 characters. The entry node is always named Entry point. |
| `graph.nodes[].position` | object | **yes** | {x, y}, finite numbers within +-100000 (canvas position). |
| `graph.nodes[].pageId` | uuid | no | Funnel page of the matching type; required on landing and post_sell nodes, optional on thank_you (omitted: the native default receipt), refused elsewhere. |
| `graph.nodes[].pageVersionId` | uuid | no | Set by publication (it pins the page version); never needed in a draft. |
| `graph.nodes[].checkoutId` | uuid | no | Checkout nodes only: the checkout of this branch. Required on every checkout node when the flow has a landing page or several checkout nodes. |
| `graph.nodes[].shortLinkId` | uuid | no | Checkout nodes of a standalone checkout only: a saved link of that checkout, to pin a saved offer revision. Sent together with shortLinkRevision. |
| `graph.nodes[].shortLinkRevision` | integer > 0 | no | The revision of that saved link. Sent together with shortLinkId. |
| `graph.nodes[].branches` | object[] | no | ab_test nodes only: 2-8 branches {id (^[A-Za-z0-9_-]{1,80}$), name (1-80), weight (1-10000)}, weights summing to at most 10000; outputs branch:<id>. |
| `graph.nodes[].condition` | object | no | condition nodes only: {mode: all\|any, rules: 1-16 rules}. Rules: {field: country\|store\|currency, operator: in\|not_in, values} (ISO2, store UUIDs or ISO currency codes, 1-100 unique), {field: products, operator: contains_any\|contains_all\|contains_none, values: product UUIDs}, {field: cart_amount\|aov, operator: eq\|gt\|gte\|lt\|lte\|between, value, upper?, currency} (integer minor units) or {field: item_count, operator, value, upper?}. upper only with between. |
| `graph.edges` | object[] | **yes** | At most 257 edges {from, output, to}. |
| `graph.edges[].from` | string | **yes** | Id of the node the edge leaves. |
| `graph.edges[].to` | string | **yes** | Id of the node the edge enters. |
| `graph.edges[].output` | string | **yes** | next (entry, landing, checkout), accepted, declined or payment_failed (post_sell; payment_failed optional, falls back to declined), matched or unmatched (condition), branch:<id> (ab_test). Thank-you nodes have no output. |

**Request body**

```json
{
  "baseRevision": 0,
  "graph": {
    "format": 1,
    "entry": "entry-point",
    "nodes": [
      {
        "id": "entry-point",
        "kind": "entry",
        "name": "Entry point",
        "position": {
          "x": 80,
          "y": 80
        }
      },
      {
        "id": "checkout",
        "kind": "checkout",
        "name": "Checkout",
        "position": {
          "x": 400,
          "y": 80
        }
      },
      {
        "id": "thank-you",
        "kind": "thank_you",
        "name": "Thank-you",
        "position": {
          "x": 720,
          "y": 80
        }
      }
    ],
    "edges": [
      {
        "from": "entry-point",
        "output": "next",
        "to": "checkout"
      },
      {
        "from": "checkout",
        "output": "next",
        "to": "thank-you"
      }
    ]
  }
}
```

**Response** `200`

```json
{
  "item": {
    "draft_revision": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The stored flow row after the save (draft_graph, draft_revision, published_version, pending_review...). |
| `item.issues` | object[] | Validation issues of the saved graph: code, message, nodeId?. Empty means the graph passes the draft rules (publication also checks pages, checkouts and ownership). |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseRevision missing, or an unknown top-level key.
- `400` {"error":"Invalid graph."}: malformed node or edge, not format 1, over 128 KiB, or nodes/edges missing.
- `400` {"error":"The Entry point cannot be changed or removed."} or {"error":"Invalid Entry point."}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the flow is archived.
- `409` {"error":"This draft changed in another tab. Reload before saving."}: stale baseRevision.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Publication rules: exactly one Entry point with no incoming edge; at least one checkout; every path passes one checkout before any post-sell or Thank-you and ends at Thank-you; no cycle, no orphan, every required output connected once; a paid path never returns to Entry, a landing page or a checkout; at most 10 post-sells per path; every referenced page published.
- A/B tests route with a stable hash over the session seed, the flow version and the node id. Conditions: unknown facts never match, negative rules included. Store facts come from the verified cart and 30-day order history; standalone carts have no store or AOV facts.
- Keep the Entry point node's id, position and graph.entry unchanged when saving a draft.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.
- New editable flows begin with one immutable entry node named Entry point. Keep its ID, position and graph.entry when saving. It has one next output and no incoming edge; it is not a checkout and never bypasses payment. Legacy published graphs and pinned sessions remain readable without rewriting versions.

##### `POST /v1/v5/flows/:id/duplicate`

**Scope** `checkouts.write` - **Duplicate a flow**

Creates a new unpublished flow with the source flow's draft graph (or the default graph for id default) under a new name. An Entry point is added when the source has none.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). Or default to copy the built-in default flow. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Name of the copy, 1-160 characters after trim. The only accepted key. |

**Request body**

```json
{
  "name": "Spring flow copy"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000003",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring flow copy",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "checkout",
          "kind": "checkout",
          "name": "Checkout",
          "position": {
            "x": 400,
            "y": 80
          }
        },
        {
          "id": "thank-you",
          "kind": "thank_you",
          "name": "Thank-you",
          "position": {
            "x": 720,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "checkout"
        },
        {
          "from": "checkout",
          "output": "next",
          "to": "thank-you"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item.id / name` | string | UUID and name. |
| `item.draft_graph` | object | Current draft graph (format 1, entry, nodes, edges). |
| `item.draft_revision` | integer | Optimistic revision: send it as baseRevision on the next draft save, publish or restore. |
| `item.published_version` | integer | Latest published version, 0 when never published. |
| `item.pending_review` | boolean | True when the draft has changes not yet published. |
| `item.visibility / owner_affiliate_id` | string / uuid \| null | Affiliate sharing (private, all_affiliates, selected_affiliates) and the affiliate owner, null for merchant assets. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is neither a UUID nor default, name missing, or another key.
- `400` {"error":"Enter a name of 1-160 characters."} (U+2013 en dash in the code).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."}: the source flow is archived.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- The copy is a draft with no assignment and no saved links.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/flows/:id/link-assets`

**Scope** `checkouts.write` - **Upload an image for a flow link**

Uploads a logo or product image for a saved offer link of a published flow and returns its HTTPS URL, to put in parameters.logo_url or parameters.productN_image. No catalogue product is created.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | UUID of a published flow (from GET /v1/v5/flows). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Saved link UUID of this flow: stores the image under that link's original checkout. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `contentType` | enum | **yes** | image/png, image/jpeg, image/webp or image/gif (no SVG). Must match the file signature. |
| `base64` | string | **yes** | Standard base64 of the image (^[A-Za-z0-9+/]+={0,2}$), 8 to 7340032 characters; decoded at most 5 MiB. |

**Request body**

```json
{
  "contentType": "image/png",
  "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg=="
}
```

**Response** `200`

```json
{
  "url": "https://media.example.com/storage/v1/object/public/shop-assets/storefront/00000000-0000-4000-8000-000000000003/standalone-link-1763294400000-a1b2c3d4.png",
  "path": "storefront/00000000-0000-4000-8000-000000000003/standalone-link-1763294400000-a1b2c3d4.png"
}
```

| response field | type | description |
|---|---|---|
| `url` | string | Public image URL to save in the link parameters; nothing changes on a link until it is saved. |
| `path` | string | Storage path: storefront/<checkout id>/standalone-link-<timestamp>-<random>.<ext>. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id or linkId is not a UUID, contentType not allowed, base64 too short or too long, or an unknown key.
- `400` {"error":"Invalid image"} (not canonical base64) or {"error":"Image format does not match its content"}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow or checkout id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Link not found"}: linkId is not a link of this flow.
- `409` The flow is not ready for links (same 409 sentences as GET /v1/v5/flows/:id/link-options), or {"error":"Publish and enable the checkout before uploading a logo"}.
- `413` {"error":"Image must be 5 MB or smaller"} (decoded), or {"error":"Request body is too large"} for a body over 7 MiB.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `502` {"error":"storage upload failed: <status> ..."}: the media storage refused the file.

**Gotchas**

- This call also creates or refreshes the link-only snapshot of the flow's store checkouts, like link-options.
- The flow chooses its checkouts: every checkout node of the published flow must name a checkout; never send a storeId or checkoutId.
- Every checkout of the flow must be published and active and serve the same verified domain; a store checkout also needs its payment routing configured (409 Configure payment routing for every checkout in this flow). Its layout is reused through an internal link-only commerce snapshot; its type and store assignment do not change.

##### `GET /v1/v5/flows/:id/link-options`

**Scope** `checkouts.read` - **Read saved-link options for a flow**

Returns what is needed to build a saved offer link for a published flow: the source checkout's published parameter defaults and content bindings, currency and shipping, brand name, locale and legal defaults, the account's configured 3DS integrations and enabled receipt e-mail senders (labels and ids only), and the checkout id to use for webhooks. Before answering it creates or refreshes the internal link-only commerce snapshot of the flow's store checkouts.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | UUID of a published flow (from GET /v1/v5/flows). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Saved link UUID when editing an existing link of this flow: the options of that link's original checkout are returned, even if the flow now starts at another checkout. |

**Response** `200`

```json
{
  "webhookCheckoutId": "00000000-0000-4000-8000-000000000003",
  "contentDefaults": {},
  "parameters": {
    "currency": "USD",
    "shipping_price": "0"
  },
  "bindings": [],
  "currency": "USD",
  "shippingPriceCents": 0,
  "brandName": "Demo Store",
  "allowPriceOverrides": false,
  "configVersion": 1,
  "locale": {
    "mode": "auto",
    "forced": null,
    "offered": [
      "en"
    ],
    "countries": []
  },
  "legal": {
    "terms": "",
    "privacy": "",
    "refund": ""
  },
  "threeDs": [],
  "emailProviders": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "name": "Receipts"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `webhookCheckoutId` | uuid | Source checkout UUID, for the checkout webhook endpoints. |
| `parameters` | object<string,string> | Published parameter defaults of the source checkout. |
| `bindings` | array | Content bindings of the published checkout document (key, nodeId, field, type, fallback). |
| `contentDefaults` | object | Presentation defaults read from the published document. |
| `currency / shippingPriceCents / brandName` | string / integer / string | Published currency, shipping in minor units and brand name. |
| `allowPriceOverrides` | boolean | settings.linkPolicy.allowPriceOverrides of the checkout, false when absent. Informational: saving a link does not check it. |
| `configVersion` | integer | Published configuration version of the source checkout. |
| `locale / legal` | object | Published locale settings (mode, forced, offered, countries) and legal URLs (terms, privacy, refund). |
| `threeDs[] / emailProviders[]` | object[] | Selectable 3DS integrations and enabled e-mail senders (id, name) for three_ds_integration_key and receipt_sender_id. No credential is returned. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id or linkId is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow or checkout id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Link not found"}: linkId is not a link of this flow.
- `409` {"error":"Publish a complete flow before adding a link."}, {"error":"Select a checkout for every checkout node."}, {"error":"Connect a verified domain before adding a flow link."}, {"error":"Publish and enable every checkout in this flow."}, {"error":"Configure payment routing for every checkout in this flow."}, {"error":"This checkout has a different commerce configuration."}, {"error":"Published checkout layout unavailable."}, {"error":"Link checkout unavailable"} or {"error":"Publish and enable the checkout before adding a link"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- This GET writes: it creates or refreshes the link-only snapshot of each store checkout of the flow (never the checkout itself).
- The flow chooses its checkouts: every checkout node of the published flow must name a checkout; never send a storeId or checkoutId.
- Every checkout of the flow must be published and active and serve the same verified domain; a store checkout also needs its payment routing configured (409 Configure payment routing for every checkout in this flow). Its layout is reused through an internal link-only commerce snapshot; its type and store assignment do not change.
- Each saved link revision pins the published flow version and the checkout configuration versions of every branch. Publishing the flow again does not change existing links: save the link again to create a new revision.
- For checkout webhooks of a flow link, use webhookCheckoutId from GET /v1/v5/flows/:id/link-options with the checkout webhook endpoints.
- The account comes from the credential; no request field can select another account.

##### `POST /v1/v5/flows/:id/preview`

**Scope** `checkouts.read` - **Issue a flow walk-through preview**

Checks access to the flow (draft for merchant flows), every referenced page and every checkout branch, then returns a signed ten-minute capability to open an inert walk-through of the flow: the checkout preview and the real page documents, with Continue, Pay, Accept, Decline and simulated failures only moving through the graph. No session, payment, order, pixel or event is created.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid \| default | **yes** | Flow UUID, or default for the built-in default flow. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout to preview the flow with; must be named by the flow (or the flow has an unnamed checkout node). |

**Request body**

```json
{
  "checkoutId": "00000000-0000-4000-8000-000000000003"
}
```

**Response** `200`

```json
{
  "url": "https://preview.example.com/preview/flow/start",
  "token": "<signed capability>",
  "expiresAt": "2026-11-16T12:10:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `url` | string | Preview start URL. |
| `token` | string | Signed capability, valid 10 minutes, bound to the flow revision. Send it only in a POST body. |
| `expiresAt` | string | Expiry of the token. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id neither a UUID nor default, checkoutId missing or not a UUID, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."} (archived flow) or {"error":"Preview unavailable."} (a checkout, page or saved link of the flow is unavailable).
- `409` {"error":"Choose the checkout named by this flow."} or {"error":"This shared checkout has no approved version."}.
- `422` {"error":"Fix the flow before previewing."}: the draft graph does not pass validation.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `503` {"error":"Editor preview is not configured."}: the preview host or signing secret is missing on the server.

**Gotchas**

- Submit token as application/x-www-form-urlencoded (field token) to url, in a browser tab; the storefront sets a Secure HttpOnly cookie scoped to /preview/flow and redirects to the clean preview URL.
- Save the draft first: the preview uses the saved draft, and saving again invalidates the token (409 This flow changed. Open a new preview. when it is used).
- Answered with Cache-Control: private, no-store.

##### `POST /v1/v5/flows/:id/publish`

**Scope** `checkouts.write` - **Publish a flow**

Publishes the draft graph as a new immutable version under a row lock: full topology validation, every referenced page pinned to its current published version, checkouts enrolled and checked, condition references and saved links checked, a single affiliate owner across checkout, flow and entry landing, and compatibility with every checkout already assigned to the flow. Only new sessions use the new version.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the flow, as last read. A different value answers 409. |
| `note` | string | no | Version note, at most 500 characters. |

**Request body**

```json
{
  "baseRevision": 1,
  "note": "Add upsell"
}
```

**Response** `200`

```json
{
  "version": 1
}
```

| response field | type | description |
|---|---|---|
| `version` | integer | The new published version. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, baseRevision missing, note over 500 characters, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow, or a page or checkout it references, is unknown or belongs to another account.
- `404` {"error":"Not found."}: the flow is archived.
- `409` {"error":"This draft changed. Reload before publishing."}: stale baseRevision.
- `422` {"error":"Fix the flow before publishing.","issues":[...]} or {"error":"Invalid published flow.","issues":[...]}: topology issues (codes such as missing_output, cycle, orphan, dead_end, checkout_path, initial_payment_required, page_version, landing_checkout).
- `422` {"error":"Publish the <node name> page first."}: a page node references a page that is unpublished, archived or of another type. {"error":"Checkout owner is unavailable."}: a checkout cannot be enrolled in the account.
- `422` Reference checks: {"error":"Publish an active checkout for <node name>."}, {"error":"A flow cannot mix store and standalone checkout paths."}, {"error":"Saved links are only available for standalone checkouts."}, {"error":"The selected link is unavailable to this flow owner."}, {"error":"Store and average order value conditions are unavailable for standalone checkouts."}, {"error":"Choose stores belonging to this account."}, {"error":"Choose active products belonging to this account."}, {"error":"Store-assigned flows require active, chargeable store checkouts."}, {"error":"This flow is assigned to a store; every payment path needs a store checkout."}.
- `422` {"error":"The flow conflicts with an assigned checkout.","issues":[...]}, or an affiliate owner conflict between the checkout, the flow and the entry landing.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Publish every referenced page first; the flow pins each page's current published version. Republishing a page later does not change this flow until it is republished.
- Existing buyer sessions keep the version they started with.
- Publication rules: exactly one Entry point with no incoming edge; at least one checkout; every path passes one checkout before any post-sell or Thank-you and ends at Thank-you; no cycle, no orphan, every required output connected once; a paid path never returns to Entry, a landing page or a checkout; at most 10 post-sells per path; every referenced page published.
- A/B tests route with a stable hash over the session seed, the flow version and the node id. Conditions: unknown facts never match, negative rules included. Store facts come from the verified cart and 30-day order history; standalone carts have no store or AOV facts.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `GET /v1/v5/flows/:id/short-links`

**Scope** `checkouts.read` - **List the saved links of a flow**

Lists every saved offer link of the flow, archived ones included, newest first: parameters, current revision and pinned configuration version, lifecycle, clicks, short and long URLs with their hosting readiness, captured sales by currency and the safe pixel configuration (never access tokens).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Response** `200`

```json
{
  "rows": [
    {
      "serving_domain": "kontrolcheckout.com",
      "id": "00000000-0000-4000-8000-000000000001",
      "checkout_id": "00000000-0000-4000-8000-000000000003",
      "name": "Linen shirt offer",
      "domain": "ktrl.ink",
      "slug": "aB3dE6g",
      "parameters": {
        "product1_name": "Linen shirt",
        "product1_price": "6798",
        "product1_quantity": "2",
        "currency": "USD"
      },
      "revision": 1,
      "active": true,
      "clicks": "12",
      "created_at": "2026-11-16T12:00:00.000Z",
      "updated_at": "2026-11-16T12:00:00.000Z",
      "archived_at": null,
      "offer_config_version": 1,
      "creator_affiliate_id": null,
      "creator_name": "Merchant",
      "url": "https://ktrl.ink/aB3dE6g",
      "shortUrl": "https://ktrl.ink/aB3dE6g",
      "longUrl": "https://kontrolcheckout.com/l/00000000-0000-4000-8000-000000000001",
      "hosting": {
        "short": "ready",
        "long": "ready"
      },
      "sales": {
        "orders": 3,
        "revenue": [
          {
            "currency": "USD",
            "amountMinor": "40788"
          }
        ]
      },
      "pixels": [
        {
          "id": "00000000-0000-4000-8000-000000000002",
          "name": "",
          "network": "facebook",
          "pixelId": "123456789012345",
          "serverEnabled": false,
          "hasAccessToken": false
        }
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].id / checkout_id / name / slug / domain` | string | Link UUID, its source checkout, name, 7-character slug and short-link domain. |
| `rows[].parameters` | object<string,string> | Stored offer parameters of the current revision. |
| `rows[].revision` | integer | Current revision: the baseRevision of the next edit or lifecycle change. |
| `rows[].active / archived_at` | boolean / string \| null | Lifecycle. Archived links are listed with archived_at set. |
| `rows[].offer_config_version / serving_domain` | integer / string | Pinned checkout configuration version and the domain that serves the checkout for this revision. |
| `rows[].clicks` | string | Click count (bigint as a string; preview crawlers are not counted). |
| `rows[].creator_affiliate_id / creator_name` | uuid \| null / string | Affiliate who created the link, or null and Merchant. |
| `rows[].shortUrl / url / longUrl` | string | Short URL (url is the same value), and the stable https://kontrolcheckout.com/l/<link id> URL. |
| `rows[].hosting` | object | short and long: ready or pending. Never distribute a pending URL. |
| `rows[].sales` | object | orders (captured initial orders) and revenue[] (currency, amountMinor as a string) of captured initial and upsell payments, tests excluded. |
| `rows[].pixels[]` | object[] | id, name, network, pixelId, events, enhancedConversions, serverEnabled, hasAccessToken. Tokens are never returned. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Unlike the other link routes, this read does not require the flow to be published.
- A link change appends an immutable revision; sessions already started keep the revision they opened.

##### `POST /v1/v5/flows/:id/short-links`

**Scope** `checkouts.write` - **Create or edit a saved link of a flow**

Creates a saved offer link for a published flow, or edits one with optimistic revision control (id + baseRevision). Each save appends an immutable revision that pins the parameters (free product names and prices in minor units, content, locale, legal, integrations), the encrypted pixel configuration, the published flow version and every branch checkout version. Returns the committed link with its short URL, long URL and hosting readiness.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | UUID of a published flow (from GET /v1/v5/flows). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | no | Link UUID to edit (a link of this flow); omit to create a link. |
| `baseRevision` | integer | no | Positive integer, required when editing: the current revision. A missing or stale value answers 409 Link changed. Reload before saving. |
| `name` | string | **yes** | 1-120 characters after trim (400 Name must contain 1-120 characters, with a U+2013 en dash in the code). |
| `active` | boolean | **yes** | Whether the link serves buyers. |
| `parameters` | object<string,string> | **yes** | Offer parameters, every value a string. Merged over the published defaults of the source checkout; sending any productN_* key drops every default productN_* key. The merged set must be at most 65536 bytes once encoded. Unknown keys answer 400 Unknown parameter; an invalid value answers 400 Invalid <key>; sig and kt answer 400 Links store parameters only; buyer prefill keys (email, first_name, last_name, address, address2, city, state, postal_code, phone, shipping_country) answer 400 Customer prefill requires POST. At least one product line is required (422 Add at least one product). |
| `parameters.productN_name` | string | no | N = 1..10. Product name, at most 255 characters. A line needs name and price; id is optional (autonomous offer). |
| `parameters.productN_price` | string | no | Unit price in minor units, integer 0-21691754. |
| `parameters.productN_quantity` | string | no | Integer 1-99. |
| `parameters.productN_compare_price` | string | no | Compare-at unit price, integer 0-2147483647, not below the price. |
| `parameters.productN_variant` | string | no | Variant label shown to the buyer, at most 255 characters. |
| `parameters.productN_image` | string | no | HTTPS image URL, at most 2048 characters (upload one with POST /v1/v5/flows/:id/link-assets). |
| `parameters.productN_id / productN_variant_id` | string | no | Optional legacy catalogue product and variant UUIDs; the product must belong to the account (422 Product N is unavailable for this account). |
| `parameters.currency` | string | no | One of USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS, ZAR (two-decimal currencies only). |
| `parameters.shipping_price` | string | no | Shipping in minor units, integer 0-2147483647. |
| `parameters.coupon` | string | no | Coupon code, ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$. |
| `parameters.shipping_protection_mode / shipping_protection_default_enabled / shipping_protection_price_cents / shipping_protection_label / shipping_protection_description` | string | no | Shipping protection: mode off, on or forced; default_enabled true or false; price integer minor units; label at most 120 and description at most 500 characters. |
| `parameters.country / allowed_countries` | string | no | country: initial ISO2 delivery country. allowed_countries: comma-separated ISO2 codes (max 250) or * for every country the checkout allows; it cannot add a country the checkout does not offer (422). |
| `parameters.offered_languages / lang` | string | no | offered_languages: comma-separated subset of en, fr, it, es, pt, pl (must include a forced checkout language, 422). lang: visitor language, unsigned. |
| `parameters.terms_url / privacy_url / refund_url` | string | no | Optional HTTPS legal URL overrides. |
| `parameters.three_ds_integration_key / receipt_sender_id` | string | no | Optional owner 3DS integration key and receipt e-mail sender UUID, chosen from threeDs[] and emailProviders[] of link-options (422 when not configured for the account). |
| `parameters.store_name / logo_url / favicon_url / cta_custom_image_url / cta_custom_image_width / primary_color / font_family / heading_font_family` | string | no | Branding: store_name at most 120; URLs HTTPS; cta_custom_image_width cta or full; primary_color #RRGGBB; fonts Inter, Manrope, Poppins, Roboto, Open Sans, Lato, Montserrat, Nunito, Raleway, DM Sans, Outfit or Source Sans 3. |
| `parameters.<switch>_enabled` | string | no | true or false for countdown_enabled, trustpilot_header_enabled, sales_points_header_enabled, cta_subtext_enabled, reassurance_secure_enabled, reassurance_refund_enabled, reassurance_tracking_enabled, support_help_enabled, support_chat_enabled, language_selector_enabled. |
| `parameters.checkout_tags / testimonials` | string | no | JSON arrays as strings: checkout_tags up to 20 {label} (120 chars); testimonials up to 12 {text (400), name (60), location? (60), rating? 1-5}. |
| `parameters.<binding key>` | string | no | Content bindings declared by the published checkout document (bindings[] of link-options): text up to 2000 characters or an HTTPS image URL. |
| `parameters.fb_pixel / tt_pixel / snap_pixel / pinterest_pixel / x_pixel / google_pixel / applovin_pixel / xN_<event> / googleN_<event> / googleN_enhanced` | string | no | Legacy URL pixel parameters (comma lists of up to 10 ids, X and Google event mappings for recipients 1..10). Prefer the pixels array; a conflict between both answers 400 Pixel configuration conflicts with this checkout. |
| `parameters.affid / subN / source_id / utm_* / click ids` | string | no | Tracking keys (sub1..sub10, source_id, utm_source, utm_medium, utm_campaign, utm_content, utm_term, utm_id, utm_ad, utm_adset, utm_source_platform, utm_creative_format, utm_marketing_tactic, dclid, twclid, epik, fbclid, ttclid, gclid, gbraid, wbraid, msclkid, ScCid, alart, _ef_transaction_id), at most 255 characters. Not needed: the entry captures them from the visitor URL. |
| `pixels` | object[] | no | Pixel recipients of this link revision. Omitted: the previous revision's pixels are copied. []: no pixel. The serialized list is at most 128 KiB (413). The same network + pixelId twice is refused (400 The same pixel is configured more than once); at most one AppLovin key. |
| `pixels[].id` | uuid | no | Id of an existing pixel of the previous revision, to keep its stored access token; omitted for a new pixel (an id is generated). |
| `pixels[].name` | string | no | Label, at most 120 characters after trim. |
| `pixels[].network` | enum | **yes** | facebook, tiktok, snapchat, google, pinterest, applovin or x. |
| `pixels[].pixelId` | string | **yes** | 1-255 characters in the network's format: facebook digits (5-30), tiktok and snapchat [A-Za-z0-9_-]{5,64}, google AW-<digits>, pinterest digits, applovin [A-Za-z0-9_-]{1,255}, x [a-z0-9]{1,32}. |
| `pixels[].events` | object<string,string> | no | Event mapping, x and google only and REQUIRED there with at least purchase. x: purchase, view_item, add_to_cart, begin_checkout, add_payment_info, each tw-<pixelId>-<id>. google: purchase, begin_checkout, add_to_cart, each a conversion label [A-Za-z0-9_-]{1,64}. |
| `pixels[].enhancedConversions` | boolean | no | Google enhanced conversions. |
| `pixels[].serverEnabled` | boolean; default `false` | no | Server-side Purchase events, facebook, tiktok and snapchat only; needs an access token (400 Add an access token to enable server purchase events). |
| `pixels[].accessToken` | string \| null | no | Write-only server token, at most 2048 characters, stored encrypted and never returned. Omitted keeps the token of the same pixel (same id, network and pixelId); null clears it. facebook, tiktok and snapchat only. |
| `pixels[].hasAccessToken` | boolean | no | Accepted (as returned by reads) and ignored. |

**Request body**

```json
{
  "name": "Linen shirt offer",
  "parameters": {
    "product1_name": "Linen shirt",
    "product1_price": "6798",
    "product1_quantity": "2",
    "product1_variant": "Blue / Large",
    "currency": "USD",
    "offered_languages": "en,fr"
  },
  "pixels": [
    {
      "network": "facebook",
      "pixelId": "123456789012345",
      "serverEnabled": false
    }
  ],
  "active": true
}
```

**Response** `200`

```json
{
  "link": {
    "id": "00000000-0000-4000-8000-000000000001",
    "checkout_id": "00000000-0000-4000-8000-000000000003",
    "name": "Linen shirt offer",
    "domain": "ktrl.ink",
    "slug": "aB3dE6g",
    "parameters": {
      "product1_name": "Linen shirt",
      "product1_price": "6798",
      "product1_quantity": "2",
      "currency": "USD"
    },
    "revision": 1,
    "active": true,
    "clicks": "12",
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z",
    "archived_at": null,
    "offer_config_version": 1,
    "creator_affiliate_id": null,
    "url": "https://ktrl.ink/aB3dE6g",
    "shortUrl": "https://ktrl.ink/aB3dE6g",
    "longUrl": "https://kontrolcheckout.com/l/00000000-0000-4000-8000-000000000001",
    "hosting": {
      "short": "ready",
      "long": "ready"
    },
    "pixels": [
      {
        "id": "00000000-0000-4000-8000-000000000002",
        "name": "",
        "network": "facebook",
        "pixelId": "123456789012345",
        "serverEnabled": false,
        "hasAccessToken": false
      }
    ],
    "account_id": "acc_0123456789abcdef",
    "created_by": "owner@example.com",
    "flow_id": null
  }
}
```

| response field | type | description |
|---|---|---|
| `link` | object | The committed link row (id, checkout_id, domain, slug, name, active, revision, parameters, offer_config_version, creator_affiliate_id, created_by, clicks, timestamps) plus url, shortUrl, longUrl, hosting and pixels (safe fields only). |
| `link.hosting` | object | short and long: ready or pending. Never distribute a pending URL. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id path or body id is not a UUID.
- `400` {"error":"Invalid link configuration"}: the body fails its strict schema (unknown key, wrong type, name over 120 characters, non-string parameter value).
- `400` Parameter refusals: {"error":"Unknown parameter"}, {"error":"Invalid <key>"}, {"error":"Customer prefill requires POST"}, {"error":"Link is too long. Use a short link"}, {"error":"Links store parameters only"}, {"error":"Name must contain 1-120 characters"} (U+2013 en dash in the code).
- `400` Pixel refusals: {"error":"Invalid pixel configuration"}, {"error":"The same pixel is configured more than once"}, {"error":"Add an access token to enable server purchase events"}, {"error":"AppLovin supports one event key per checkout page"}, {"error":"Pixel configuration conflicts with this checkout"}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow or checkout id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Link not found"}: id is not a link of this flow, or it is archived. {"error":"Checkout not found"}: the source checkout disappeared.
- `409` The flow is not ready for links (same sentences as GET /v1/v5/flows/:id/link-options); {"error":"Link changed. Reload before saving."}; {"error":"Use the flow link editor for this link"}; {"error":"Flow branch unavailable."}; {"error":"All flow checkout branches must use the same serving domain."}; {"error":"Link belongs to another flow."}; {"error":"Flow domain configuration unavailable"}.
- `413` {"error":"Pixel configuration exceeds the request size"} (pixels over 128 KiB), or {"error":"Request body is too large"} for a body over 256 KiB.
- `422` Offer refusals: {"error":"Add at least one product"}, {"error":"Product N requires a name, valid price and quantity"}, {"error":"Product N is unavailable for this account"}, {"error":"Product N compare price is below price"}, a checkout limit message, {"error":"Choose a valid country"}, {"error":"A country is not offered by this checkout"}, {"error":"Include the checkout language in offered languages"}, {"error":"Select a configured 3DS integration owned by this account"}, {"error":"Select an enabled email sender owned by this account"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `503` {"error":"Link hosting is not configured"} or {"error":"Could not allocate a short link"}: retry later; nothing was saved.

**Gotchas**

- productN_price is the unit price in minor units: the example is two units at 67.98 USD before shipping, discounts and tax. Only the two-decimal currencies listed are accepted.
- A stale baseRevision returns 409: read GET /v1/v5/flows/:id/short-links again and retry with the current revision; never overwrite blindly.
- Saving with no pixels key copies the previous revision's pixels; [] removes them. Access tokens are write-only.
- Pick three_ds_integration_key and receipt_sender_id only from link-options; never guess a provider key.
- New short URLs use ktrl.ink and long URLs https://kontrolcheckout.com/l/<link id>; distribute a URL only when hosting says ready.
- The flow chooses its checkouts: every checkout node of the published flow must name a checkout; never send a storeId or checkoutId.
- Every checkout of the flow must be published and active and serve the same verified domain; a store checkout also needs its payment routing configured (409 Configure payment routing for every checkout in this flow). Its layout is reused through an internal link-only commerce snapshot; its type and store assignment do not change.
- Each saved link revision pins the published flow version and the checkout configuration versions of every branch. Publishing the flow again does not change existing links: save the link again to create a new revision.
- For checkout webhooks of a flow link, use webhookCheckoutId from GET /v1/v5/flows/:id/link-options with the checkout webhook endpoints.

##### `PATCH /v1/v5/flows/:id/short-links/:linkId`

**Scope** `checkouts.write` - **Change the lifecycle of a flow link**

Enables, disables, archives or restores one saved link of the flow with optimistic revision control. Appends a new immutable revision that keeps the parameters, pixels, domain and flow pins of the previous one.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID. |
| `linkId` | uuid | **yes** | Saved link UUID of this flow. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | Positive integer: the link's current revision. |
| `active` | boolean | **yes** | Desired active state; ignored (forced false) when archived is true. |
| `archived` | boolean | **yes** | true archives and disables the link; false restores it (with the given active). |

**Request body**

```json
{
  "baseRevision": 3,
  "active": false,
  "archived": true
}
```

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true once committed; the new revision is baseRevision + 1 (read the list to confirm). |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id or linkId is not a UUID, or the body fails its strict schema (all three keys required).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow or checkout id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Link not found"}: linkId is not a link of this flow.
- `409` {"error":"Link changed or unavailable"}: baseRevision is stale.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Unlike the save route, this does not require the flow to be published.
- Archived and disabled links stop serving at once; sessions already open keep their revision.

##### `GET /v1/v5/flows/:id/versions`

**Scope** `checkouts.read` - **List flow versions**

Lists the published versions of the flow, newest first, with their id, publisher and note.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |

**Response** `200`

```json
{
  "versions": [
    {
      "id": "00000000-0000-4000-8000-000000000004",
      "version": 1,
      "created_at": "2026-11-16T12:00:00.000Z",
      "created_by": "owner@example.com",
      "note": "Add upsell"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `versions[]` | object[] | id (version UUID), version, created_at, created_by (publisher e-mail, or the key owner's e-mail for an API key), note. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An archived flow still lists its versions here, but cannot be restored or published.
- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `POST /v1/v5/flows/:id/versions/:version/restore`

**Scope** `checkouts.write` - **Restore a flow version into the draft**

Copies the graph of a published version into the draft (pending review, Entry point added when missing) with optimistic revision control. Nothing is published.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Flow UUID (from GET /v1/v5/flows). |
| `version` | integer | **yes** | Published version number, positive integer. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | 0 or more: the current draftRevision (draft_revision) of the flow, as last read. A different value answers 409. |

**Request body**

```json
{
  "baseRevision": 3
}
```

**Response** `200`

```json
{
  "item": {
    "id": "00000000-0000-4000-8000-000000000002",
    "account_id": "acc_0123456789abcdef",
    "owner_affiliate_id": null,
    "name": "Spring flow",
    "visibility": "private",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [],
      "edges": []
    },
    "draft_revision": 4,
    "published_version": 2,
    "pending_review": true,
    "archived_at": null,
    "created_at": "2026-11-16T12:00:00.000Z",
    "updated_at": "2026-11-16T12:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The stored flow row after the restore; item.draft_revision is the next baseRevision. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: id is not a UUID, version not a positive integer, baseRevision missing, or an unknown key.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `403` {"error":"Forbidden"}: the flow id is unknown or belongs to another account (asset access check; it answers 403, not 404).
- `404` {"error":"Not found."} (archived flow) or {"error":"Published version not found."}.
- `409` {"error":"The draft changed."}: stale baseRevision.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- An unknown id, or an id of another account, answers 403 {"error":"Forbidden"} from the asset access check, not 404. An archived page or flow answers 404 {"error":"Not found."}.

##### `GET /v1/v5/flows/options`

**Scope** `checkouts.read` - **Flow condition choices**

Lists the account's stores and active products (id and name) for the store and products rules of Conditions nodes.

*No parameters.*

**Response** `200`

```json
{
  "stores": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "name": "Demo Store"
    }
  ],
  "products": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "name": "Travel kit"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `stores[]` | object[] | id and name (internal name, else the domain) of each store of the account, sorted by name. |
| `products[]` | object[] | id and title (as name) of each active product owned by a store of the account, linked to one, or in the account catalogue, sorted by name. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Choices carry no customer or payment data. Publication rechecks ownership and availability: a saved id is not an authorization.

##### `POST /v1/v5/flows/validate`

**Scope** `checkouts.write` - **Validate a flow graph**

Runs the graph validator on a graph you send (shape, required nodes and outputs, reachability, cycles, payment path, post-sell bound) and answers ok with the list of issues. Nothing is stored; it does not check access to referenced pages or checkouts, nor that pages are published.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `graph` | object | **yes** | A graph in the same format as PUT /v1/v5/flows/:id/draft (format, entry, nodes, edges). Any value is accepted and reported on: a malformed graph answers 200 with ok false and a shape issue. |

**Request body**

```json
{
  "graph": {
    "format": 1,
    "entry": "entry-point",
    "nodes": [
      {
        "id": "entry-point",
        "kind": "entry",
        "name": "Entry point",
        "position": {
          "x": 80,
          "y": 80
        }
      },
      {
        "id": "checkout",
        "kind": "checkout",
        "name": "Checkout",
        "position": {
          "x": 400,
          "y": 80
        }
      },
      {
        "id": "thank-you",
        "kind": "thank_you",
        "name": "Thank-you",
        "position": {
          "x": 720,
          "y": 80
        }
      }
    ],
    "edges": [
      {
        "from": "entry-point",
        "output": "next",
        "to": "checkout"
      },
      {
        "from": "checkout",
        "output": "next",
        "to": "thank-you"
      }
    ]
  }
}
```

**Response** `200`

```json
{
  "ok": true,
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when no issue. |
| `issues[]` | object[] | code, message, nodeId?. Codes: shape, node_shape, edge_shape, page_reference, checkout_reference, page_version, duplicate_node, entry, entry_incoming, checkout_count, assignment, missing_node, duplicate_output, invalid_output, missing_output, cycle, backward, initial_payment_required, checkout_path, dead_end, step_limit, orphan, landing_checkout. |

**Errors**

- `400` {"error":"Invalid request.","details":<zod flatten>}: graph is missing or another key was sent.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"flows"} when the plan excludes the flows tool.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Publication rules: exactly one Entry point with no incoming edge; at least one checkout; every path passes one checkout before any post-sell or Thank-you and ends at Thank-you; no cycle, no orphan, every required output connected once; a paid path never returns to Entry, a landing page or a checkout; at most 10 post-sells per path; every referenced page published.
- A/B tests route with a stable hash over the session seed, the flow version and the node id. Conditions: unknown facts never match, negative rules included. Store facts come from the verified cart and 30-day order history; standalone carts have no store or AOV facts.

#### Standalone and embedded checkouts

Checkouts that live on their own link or inside an iframe on the merchant's site: settings, document, publication, short links and signed links. The runtime an integrator calls is under Headless checkout.

##### `GET /v1/checkouts/standalone`

**Scope** `checkouts.read` - **List standalone checkouts**

Lists the account's standalone (reusable) checkouts, newest edit first (up to 1000, archived ones excluded), each with its configuration, links_count (active non-flow short links) and sales. Draft and published documents are left out.

*No parameters.*

**Response** `200`

```json
{"rows": []}
```

| response field | type | description |
|---|---|---|
| `result` | object | Returns visible standalone checkout metadata, publication state and canonical captured sales, including currency-separated initial and upsell revenue. Native affiliate data is a positive projection and own-attribution metrics only. Each row includes links_count: current unarchived saved links, restricted to the authenticated creator for affiliates. |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- No account ID in a request can override authenticated ownership.
- Use docs/v5/generated/standalone-parameter-reference.md for complete per-field limits, canonical signature vector and Node/PHP/Python snippets.
- Revenue is captured initial plus upsell amounts by currency; orders count captured initial contexts. Rebill and all test classifications are excluded.

##### `POST /v1/checkouts/standalone`

**Scope** `checkouts.write` - **Create a standalone checkout**

Creates an inactive standalone checkout with its settings and a link signing secret. Publish it (document and settings) and enable it before creating links.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-200, trimmed) | **yes** | Checkout name. |
| `description` | string (max 2000); default `""` | no | Description. |
| `domain` | string (max 253) | **yes** | Serving domain: kontrolcheckout.com or a verified domain of the account (see GET /v1/checkouts/standalone/options). |
| `slug` | string (max 60) | **yes** | Lower-case letters, digits and hyphens, starting with a letter or digit. |
| `atriId` | uuid or "" | **yes** | Payment ATRI used to route the charges ("" = none yet; publishing needs one). |
| `baseRevision` | integer (>= 0); default `0` | no | Settings revision the edit is based on (update only; a stale value answers 409). |
| `threeDsIntegrationKey` | string (max 200) or null | no | A configured 3DS provider key of the account (from options.threeDs); null = none. |
| `applePay` | boolean | no | Offer Apple Pay. |
| `googlePay` | boolean | no | Offer Google Pay. |
| `settings` | object (strict) | **yes** | Checkout settings, validated as a whole (unknown keys refused; 422 `Invalid standalone settings` / `Invalid settings` when they do not validate). |
| `settings.currency` | string (one of the supported two-decimal checkout currencies) | **yes** | Checkout currency. |
| `settings.brand` | object | **yes** | {name (1-120), address (max 500), supportEmail (e-mail), supportPhone (max 64), supportIntegrationId (uuid or null)}. |
| `settings.locale` | object | no | {mode auto \| forced, forced (locale or null), offered (1-6 of en, fr, it, es, pt, pl; default [en]), countries (ISO-2 list, max 250; empty = all)}. |
| `settings.shipping` | object | **yes** | {priceCents (0-2147483647, default 0), label (1-120, default Shipping)}. |
| `settings.tax` | object | **yes** | {mode none, basisPoints 0} or {mode inclusive \| exclusive, basisPoints 1-10000}. |
| `settings.legal` | object | no | {terms, privacy, refund}: HTTPS URLs or empty strings. |
| `settings.thankYou` | object | **yes** | {kind internal \| url, url (HTTPS or null)}. |
| `settings.fulfillment` | object | **yes** | {mode none \| shopify \| medusa, connectorShopId (uuid or null)}. |
| `settings.receipts` | object | **yes** | {enabled, senderId (uuid or null), subject (1-160), replyTo (e-mail or null)}. |
| `settings.recovery` | object | **yes** | {email, sms}: each {enabled, providerId, templateId, delayMinutes 5-180, discountKind percent \| amount, discountValue, linkValidMinutes 5-1440, minCartCents, testModePct 0-100, quietHours, timezone, touchDelaysMinutes (up to 10 values 5-1440)}. |
| `settings.protection` | object | **yes** | {fraud, velocity, blacklist, bin: account; captcha: disabled} (fixed values). |
| `settings.limits` | object | **yes** | {enabled, maxItemsPerCart (1-990 or null), maxAmountCents (or null), message (max 300)}. |
| `settings.parameters` | object<string,string> | no | Default link parameters (keys max 64, values max 8192), the same catalogue as the short link parameters. |
| `settings.bindings` | array (max 100) | no | Content bindings {key ^[a-z][a-z0-9_]{0,63}$, nodeId, field, type text \| image, fallback} that link parameters may fill. |
| `settings.linkPolicy` | object | no | {allowPriceOverrides: boolean} (default false). |
| `settings.presentation` | object | no | {mode page \| iframe, allowedOrigins (up to 20 exact HTTPS origins)}. |
| `settings.presentation.mode` | enum: page \| iframe | no | page = a hosted checkout page; iframe = an embedded card checkout that a merchant server opens with POST /v5/standalone/iframe-session. |
| `settings.presentation.allowedOrigins` | string[] (<= 20) | no | iframe mode: the exact HTTPS origins (https://host, no path or trailing slash) of the websites allowed to embed the checkout. The parentOrigin of POST /v5/standalone/iframe-session must be one of them. |

**Request body**

```json
{"name": "Offer", "description": "", "domain": "pay.example.com", "slug": "offer", "atriId": "11111111-1111-4111-8111-111111111111", "settings": "<StandaloneSettingsData; see generated parameter reference and settings guide>", "baseRevision": 0}
```

**Response** `200`

```json
{"checkout": {"id": "11111111-1111-4111-8111-111111111111", "active": false}}
```

| response field | type | description |
|---|---|---|
| `result` | object | Creates a disabled standalone checkout, account-scoped configuration and signing key in one transaction. Uses a real catalog and verified domain; no synthetic store is created. Affiliates must duplicate a shared asset instead. |

**Errors**

- `400` `{"error":"Use a slug of up to 60 lowercase letters, numbers and hyphens"}` (create) or `{"error":"Invalid checkout slug"}` (update).
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the schema (missing name / domain / slug / atriId / settings, unknown field) (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `422` `{"error":"Select a configured 3DS provider owned by this account"}`; `{"error":"Invalid standalone settings"}` / `{"error":"Invalid settings"}`; `{"error":"Select a verified domain owned by this account"}`. Only the error text is returned (no issue list).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id`

**Scope** `checkouts.read` - **Read a standalone checkout**

Reads one standalone checkout with its settings, draft and published documents, revisions and publication state.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{"checkout": {"id": "11111111-1111-4111-8111-111111111111", "name": "Offer"}}
```

| response field | type | description |
|---|---|---|
| `result` | object | Returns one account-owned visible checkout. Merchant configuration includes settings and editor documents. Native affiliate projection omits routing, providers, prices and other affiliates’ identity. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `PATCH /v1/checkouts/standalone/:id`

**Scope** `checkouts.write` - **Update a standalone checkout**

Two forms: a body with only name renames the checkout; otherwise the full write body (as create, plus baseRevision) replaces the draft settings. Publication is a separate call.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-200, trimmed) | **yes** | Rename form: the only field. Checkout name. |
| `description` | string (max 2000); default `""` | no | Full form: Description. |
| `domain` | string (max 253) | no | Full form: required. Serving domain: kontrolcheckout.com or a verified domain of the account (see GET /v1/checkouts/standalone/options). |
| `slug` | string (max 60) | no | Full form: required. Lower-case letters, digits and hyphens, starting with a letter or digit. |
| `atriId` | uuid or "" | no | Full form: required. Payment ATRI used to route the charges ("" = none yet; publishing needs one). |
| `baseRevision` | integer (>= 0); default `0` | no | Full form: Settings revision the edit is based on (update only; a stale value answers 409). |
| `threeDsIntegrationKey` | string (max 200) or null | no | Full form: A configured 3DS provider key of the account (from options.threeDs); null = none. |
| `applePay` | boolean | no | Full form: Offer Apple Pay. |
| `googlePay` | boolean | no | Full form: Offer Google Pay. |
| `settings` | object (strict) | no | Full form: required. Checkout settings, validated as a whole (unknown keys refused; 422 `Invalid standalone settings` / `Invalid settings` when they do not validate). |
| `settings.currency` | string (one of the supported two-decimal checkout currencies) | no | Full form: required. Checkout currency. |
| `settings.brand` | object | no | Full form: required. {name (1-120), address (max 500), supportEmail (e-mail), supportPhone (max 64), supportIntegrationId (uuid or null)}. |
| `settings.locale` | object | no | Full form: {mode auto \| forced, forced (locale or null), offered (1-6 of en, fr, it, es, pt, pl; default [en]), countries (ISO-2 list, max 250; empty = all)}. |
| `settings.shipping` | object | no | Full form: required. {priceCents (0-2147483647, default 0), label (1-120, default Shipping)}. |
| `settings.tax` | object | no | Full form: required. {mode none, basisPoints 0} or {mode inclusive \| exclusive, basisPoints 1-10000}. |
| `settings.legal` | object | no | Full form: {terms, privacy, refund}: HTTPS URLs or empty strings. |
| `settings.thankYou` | object | no | Full form: required. {kind internal \| url, url (HTTPS or null)}. |
| `settings.fulfillment` | object | no | Full form: required. {mode none \| shopify \| medusa, connectorShopId (uuid or null)}. |
| `settings.receipts` | object | no | Full form: required. {enabled, senderId (uuid or null), subject (1-160), replyTo (e-mail or null)}. |
| `settings.recovery` | object | no | Full form: required. {email, sms}: each {enabled, providerId, templateId, delayMinutes 5-180, discountKind percent \| amount, discountValue, linkValidMinutes 5-1440, minCartCents, testModePct 0-100, quietHours, timezone, touchDelaysMinutes (up to 10 values 5-1440)}. |
| `settings.protection` | object | no | Full form: required. {fraud, velocity, blacklist, bin: account; captcha: disabled} (fixed values). |
| `settings.limits` | object | no | Full form: required. {enabled, maxItemsPerCart (1-990 or null), maxAmountCents (or null), message (max 300)}. |
| `settings.parameters` | object<string,string> | no | Full form: Default link parameters (keys max 64, values max 8192), the same catalogue as the short link parameters. |
| `settings.bindings` | array (max 100) | no | Full form: Content bindings {key ^[a-z][a-z0-9_]{0,63}$, nodeId, field, type text \| image, fallback} that link parameters may fill. |
| `settings.linkPolicy` | object | no | Full form: {allowPriceOverrides: boolean} (default false). |
| `settings.presentation` | object | no | Full form: {mode page \| iframe, allowedOrigins (up to 20 exact HTTPS origins)}. |
| `settings.presentation.mode` | enum: page \| iframe | no | page = a hosted checkout page; iframe = an embedded card checkout that a merchant server opens with POST /v5/standalone/iframe-session. |
| `settings.presentation.allowedOrigins` | string[] (<= 20) | no | iframe mode: the exact HTTPS origins (https://host, no path or trailing slash) of the websites allowed to embed the checkout. The parentOrigin of POST /v5/standalone/iframe-session must be one of them. |

**Request body**

```json
{
  "name": "Summer offer checkout"
}
```

**Response** `200`

```json
{"checkout": {"id": "11111111-1111-4111-8111-111111111111"}}
```

| response field | type | description |
|---|---|---|
| `result` | object | Merchant-only optimistic draft update. Accepts a name-only object or complete settings form with baseRevision. Publication requirements remain enforced by publish; invalid structural settings are rejected. |

**Errors**

- `400` `{"error":"Use a slug of up to 60 lowercase letters, numbers and hyphens"}` (create) or `{"error":"Invalid checkout slug"}` (update).
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or the full body fails the schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Settings changed in another tab. Reload before saving."}` when baseRevision is stale.
- `422` `{"error":"Select a configured 3DS provider owned by this account"}`; `{"error":"Invalid standalone settings"}` / `{"error":"Invalid settings"}`; `{"error":"Select a verified domain owned by this account"}`. Only the error text is returned (no issue list).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.
- Send baseRevision = the current draft_revision from GET /v1/checkouts/standalone/:id.

##### `DELETE /v1/checkouts/standalone/:id`

**Scope** `checkouts.write` - **Archive a standalone checkout**

Archives the checkout (catalog_archived): it leaves the list and stops serving. Nothing is erased.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response**

```json
{
  "deleted": true,
  "archived": true
}
```

| response field | type | description |
|---|---|---|
| `deleted` | boolean | True when the catalog entry has been removed. |
| `archived` | boolean | True: underlying historical records are retained. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/active`

**Scope** `checkouts.write` - **Enable or disable a standalone checkout**

Turns the checkout on or off for buyers.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `active` | boolean | **yes** | true enables, false disables. |

**Request body**

```json
{
  "active": true
}
```

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Merchant-only active toggle. Enabling requires a published version; pausing also blocks short-link resolution and new entry. Captured fulfillment remains eligible. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or active is missing (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Publish the checkout before enabling it"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id/document`

**Scope** `checkouts.read` - **Read the checkout document**

Reads the draft and published builder documents of the checkout with their revisions, the default document and the validation issues of the current draft.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{"checkout": {"id": "11111111-1111-4111-8111-111111111111", "name": "Offer", "sites": 0}, "draft": null, "published": null, "publishedVersion": 0, "draftRevision": 0, "issues": []}
```

| response field | type | description |
|---|---|---|
| `result` | object | Returns the same canonical checkout editor document, draft/publication revisions, default document and validator issues. The renderer and block catalog are shared with store checkouts. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `PUT /v1/checkouts/standalone/:id/document/draft`

**Scope** `checkouts.write` - **Save the document draft**

Saves the builder document as the new draft (compare-and-set on baseRevision) and returns the new revision with the validation issues. Documents with validation errors are still saved as drafts; publishing refuses them.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `document` | object (builder document) | **yes** | The whole document (format, pageType checkout, root, content) as in GET /v1/editor/catalog. |
| `baseRevision` | integer (>= 0) | **yes** | Current document draftRevision. |

**Request body**

```json
{
  "document": {
    "format": 1,
    "catalog": 5,
    "pageType": "checkout",
    "root": {
      "props": {}
    },
    "content": [
      {
        "id": "default-recovery-countdown",
        "type": "checkout.recoveryCountdown",
        "props": {}
      },
      {
        "id": "default-header",
        "type": "site.header",
        "props": {
          "align": "left",
          "trustpilot": true,
          "salesPoints": true
        }
      },
      {
        "id": "default-reservation-countdown",
        "type": "checkout.reservationCountdown",
        "props": {}
      },
      {
        "id": "default-summary-bar",
        "type": "checkout.summaryBar",
        "props": {},
        "slots": {
          "content": [
            {
              "id": "default-summary-bar-summary",
              "type": "checkout.orderSummary",
              "props": {},
              "slots": {
                "content": [
                  {
                    "id": "default-summary-bar-summary-lines",
                    "type": "checkout.summaryLines",
                    "props": {}
                  },
                  {
                    "id": "default-summary-bar-summary-protection",
                    "type": "checkout.shippingProtection",
                    "props": {}
                  },
                  {
                    "id": "default-summary-bar-summary-totals",
                    "type": "checkout.summaryTotals",
                    "props": {}
                  }
                ]
              }
            }
          ]
        },
        "visibility": {
          "desktop": false
        }
      },
      {
        "id": "default-layout",
        "type": "checkout.layout",
        "props": {},
        "slots": {
          "main": [
            {
              "id": "default-form",
              "type": "checkout.form",
              "props": {},
              "slots": {
                "fields": [
                  {
                    "id": "default-express-checkout",
                    "type": "checkout.expressCheckout",
                    "props": {}
                  },
                  {
                    "id": "default-contact",
                    "type": "checkout.section",
                    "props": {
                      "preset": "contact"
                    },
                    "slots": {
                      "content": [
                        {
                          "id": "default-email",
                          "type": "checkout.email",
                          "props": {}
                        }
                      ]
                    }
                  },
                  {
                    "id": "default-shipping-address",
                    "type": "checkout.section",
                    "props": {
                      "preset": "shipping"
                    },
                    "slots": {
                      "content": [
                        {
                          "id": "default-country",
                          "type": "checkout.country",
                          "props": {}
                        },
                        {
                          "id": "default-name",
                          "type": "checkout.name",
                          "props": {}
                        },
                        {
                          "id": "default-address",
                          "type": "checkout.address",
                          "props": {}
                        },
                        {
                          "id": "default-apartment",
                          "type": "checkout.apartment",
                          "props": {}
                        },
                        {
                          "id": "default-postal-row",
                          "type": "checkout.fieldRow",
                          "props": {},
                          "slots": {
                            "fields": [
                              {
                                "id": "default-postal-code",
                                "type": "checkout.postalCode",
                                "props": {}
                              },
                              {
                                "id": "default-state",
                                "type": "checkout.state",
                                "props": {}
                              }
                            ]
                          }
                        },
                        {
                          "id": "default-city",
                          "type": "checkout.city",
                          "props": {}
                        },
                        {
                          "id": "default-phone",
                          "type": "checkout.phone",
                          "props": {}
                        }
                      ]
                    }
                  },
                  {
                    "id": "default-shipping-method",
                    "type": "checkout.shippingMethod",
                    "props": {
                      "tags": []
                    }
                  },
                  {
                    "id": "default-payment",
                    "type": "checkout.payment",
                    "props": {}
                  },
                  {
                    "id": "default-pay-area",
                    "type": "checkout.payArea",
                    "props": {},
                    "slots": {
                      "content": [
                        {
                          "id": "default-mini-cart",
                          "type": "checkout.miniCart",
                          "props": {},
                          "slots": {
                            "content": [
                              {
                                "id": "default-mini-cart-summary",
                                "type": "checkout.orderSummary",
                                "props": {},
                                "slots": {
                                  "content": [
                                    {
                                      "id": "default-mini-cart-summary-lines",
                                      "type": "checkout.summaryLines",
                                      "props": {}
                                    },
                                    {
                                      "id": "default-mini-cart-summary-totals",
                                      "type": "checkout.summaryTotals",
                                      "props": {}
                                    }
                                  ]
                                }
                              }
                            ]
                          },
                          "visibility": {
                            "desktop": false
                          }
                        },
                        {
                          "id": "default-pay-button",
                          "type": "checkout.payButton",
                          "props": {}
                        },
                        {
                          "id": "default-cta-subtext",
                          "type": "checkout.ctaSubtext",
                          "props": {}
                        },
                        {
                          "id": "default-cta-image",
                          "type": "checkout.ctaImage",
                          "props": {
                            "src": "",
                            "width": "cta"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          ],
          "aside": [
            {
              "id": "default-summary",
              "type": "checkout.orderSummary",
              "props": {},
              "slots": {
                "content": [
                  {
                    "id": "default-summary-lines",
                    "type": "checkout.summaryLines",
                    "props": {}
                  },
                  {
                    "id": "default-summary-protection",
                    "type": "checkout.shippingProtection",
                    "props": {}
                  },
                  {
                    "id": "default-summary-totals",
                    "type": "checkout.summaryTotals",
                    "props": {}
                  }
                ]
              },
              "visibility": {
                "tablet": false,
                "mobile": false
              }
            }
          ]
        }
      },
      {
        "id": "default-footer",
        "type": "site.footer",
        "props": {
          "secure": true,
          "refund": true,
          "tracking": true,
          "help": true,
          "chat": true,
          "languageSelector": true,
          "disclaimer": true
        }
      },
      {
        "id": "default-coco-promo",
        "type": "checkout.cocoPromo",
        "props": {
          "theme": "light"
        }
      }
    ]
  },
  "baseRevision": 0
}
```

**Response** `200`

```json
{"kind": "saved", "draftRevision": 1, "issues": []}
```

| response field | type | description |
|---|---|---|
| `result` | object | Validates the shared document and performs revision-checked draft save. Native affiliate writes additionally pass the positive design-only guard and mark pending review; money, binding and security changes are denied. |

**Errors**

- `400` `{"error":"Not a checkout document"}` (or `Not a checkout document: its page type is "<type>"`); the issue list is not returned.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or baseRevision is missing (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Draft changed; reload before saving"}`.
- `413` The document passes the document size limit (GET /v1/editor/catalog validation.maxDocumentBytes).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `DELETE /v1/checkouts/standalone/:id/document/draft`

**Scope** `checkouts.write` - **Discard the document draft**

Discards the draft document and returns to the published one.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer (>= 0) | **yes** | Current document draftRevision (strict body). |

**Request body**

```json
{
  "baseRevision": 7
}
```

**Response** `200`

```json
{
  "ok": true,
  "draftRevision": 8
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Discards an editable draft within account and asset scope. It cannot publish or modify commercial configuration. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or the body fails the strict schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Not found"}` or `Checkout not found`.
- `409` `{"error":"The draft changed. Reload before discarding."}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/document/links`

**Scope** `checkouts.write` - **Create an editor or preview link**

Creates a signed short-lived link: kind canvas (the builder canvas, needs an allowed editor Origin header) or kind preview (draft or published render).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: canvas \| preview | **yes** | Link kind. |
| `mode` | enum: draft \| published; default `draft` | no | Which document to render (canvas always reads the draft). |
| `storeId` | null | no | Only null is accepted. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Origin` | string | no | Required for kind canvas: an origin on the API CORS list. |

**Request body**

```json
{
  "kind": "preview",
  "mode": "draft"
}
```

**Response** `200`

```json
{"url": "https://pay.example.com/preview/checkout/<id>?exp=<expiry>&sig=<capability>"}
```

| response field | type | description |
|---|---|---|
| `result` | object | Issues the existing signed editor canvas or preview capability. Canvas origin must be dashboard-allowlisted. Preview is inert: no charge credentials, live pixels, flow session or payment action. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or the body fails the schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `403` `{"error":"Editor origin is not allowed"}` for a canvas link without an allowed Origin.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Publish the checkout before previewing its published version"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` The preview link could not be signed (its error text).

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/document/publish`

**Scope** `checkouts.write` - **Publish the document**

Publishes the draft document together with the current draft settings (same as POST /v1/checkouts/standalone/:id/publish with the current settings revision).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer (>= 0) | **yes** | Current document draftRevision. |

**Request body**

```json
{
  "baseRevision": 7
}
```

**Response** `200`

```json
{
  "publishedVersion": 5,
  "draftRevision": 8,
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Uses the full standalone publication validator, not the legacy store document-only publisher. Saves immutable document/configuration versions together; merchant only. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or baseRevision is missing (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"The checkout changed. Reload before publishing."}`.
- `422` `Fix document errors before publishing` or `Fix publication requirements`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id/document/stores`

**Scope** `checkouts.read` - **List preview stores**

Always answers an empty list: a standalone checkout has no store to preview against.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{
  "stores": []
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Returns an empty list after checking asset visibility. Standalone preview never requires or creates a store. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id/document/versions`

**Scope** `checkouts.read` - **List published document versions**

Lists the published versions of the document (version, createdAt, createdBy, note) with the current published version.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{"publishedVersion": 1, "versions": []}
```

| response field | type | description |
|---|---|---|
| `result` | object | Lists account-scoped publication history; native affiliate responses hide publisher identity. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/document/versions/:version/restore`

**Scope** `checkouts.write` - **Restore a document version**

Copies a published version into the draft (compare-and-set on baseRevision). Publish afterwards to serve it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |
| `version` | integer (> 0) | **yes** | Published version number. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer (>= 0) | **yes** | Current document draftRevision. |

**Request body**

```json
{
  "baseRevision": 7
}
```

**Response** `200`

```json
{
  "draftRevision": 8,
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Merchant-only restore into the current revision-checked draft. Restoring does not publish or revert immutable historical configuration. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID, version is not a positive integer or baseRevision is missing (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Version unavailable or draft changed"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/duplicate`

**Scope** `checkouts.write` - **Duplicate a standalone checkout**

Copies a checkout (settings, payment routing, 3DS and wallet choices, current draft document) into a new inactive private checkout with the given name and a derived slug.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1-200, trimmed) | **yes** | Name of the copy. |

**Request body**

```json
{
  "name": "Summer offer checkout (copy)"
}
```

**Response** `200`

```json
{"checkout": {"id": "11111111-1111-4111-8111-111111111111", "active": false}}
```

| response field | type | description |
|---|---|---|
| `result` | object | Creates a disabled private copy with a fresh checkout ID and signing secret. Native affiliate duplicates become affiliate-owned, pending merchant review, with design-only editing. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or name is missing (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.
- The copy must be published and enabled before it can serve.

##### `POST /v1/checkouts/standalone/:id/link-assets`

**Scope** `checkouts.write` - **Upload a link image**

Uploads an image (logo or product picture) for links of this published, enabled checkout and returns its public URL.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `contentType` | enum: image/png \| image/jpeg \| image/webp \| image/gif | **yes** | Image type; must match the bytes. |
| `base64` | string (base64, 8 chars to 7 MiB) | **yes** | Image bytes in plain base64 (no data: prefix). |

**Request body**

```json
{
  "contentType": "image/png",
  "base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}
```

**Response** `200`

```json
{"url": "https://assets.example.com/standalone-link/logo.png"}
```

| response field | type | description |
|---|---|---|
| `url` | string | Public image URL to save as parameters.logo_url; no asset mutation occurs until the link is saved. |

**Errors**

- `400` `{"error":"Invalid image"}` (not base64) or `{"error":"Image format does not match its content"}`.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or the body fails the strict schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Publish and enable the checkout before uploading a logo"}`.
- `413` `{"error":"Image must be 5 MB or smaller"}`; a body over 7 MiB is refused before the route.
- `502` `{"error":"storage upload failed: <status> <start of the storage answer>","requestId":"..."}` when the media storage refuses the upload; nothing is stored, retry the same call.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id/link-options`

**Scope** `checkouts.read` - **Read link options**

What a short link of this published, enabled checkout may set: content defaults, default parameters, content bindings, currency, shipping price, brand name, price override policy, published config version, locale, legal URLs and the account 3DS and e-mail sender references usable on a link.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{
  "parameters": {},
  "bindings": [],
  "currency": "USD",
  "shippingPriceCents": 0,
  "brandName": "Merchant",
  "allowPriceOverrides": true,
  "configVersion": 1,
  "locale": {
    "mode": "auto",
    "forced": null,
    "offered": [
      "en"
    ],
    "countries": []
  },
  "legal": {
    "terms": "",
    "privacy": "",
    "refund": ""
  },
  "threeDs": [],
  "emailProviders": [],
  "webhooksEnabled": false,
  "contentDefaults": {}
}
```

| response field | type | description |
|---|---|---|
| `parameters` | object<string,string> | Published parameter defaults; product catalog is not returned. |
| `bindings` | array | Published document content bindings and their constraints. |
| `contentDefaults` | object | Published presentation defaults. Builder nodes remain the authority for visibility. |
| `allowPriceOverrides` | boolean | Always true for independent saved offers; legacy template price policy is not a prerequisite. |
| `configVersion` | integer | Current published checkout settings version, pinned when saving an offer revision. |
| `threeDs / emailProviders` | array | Configured owner choices with safe identifiers/labels only. Select an available three_ds_integration_key or receipt_sender_id; credentials are never returned. |
| `webhooksEnabled` | boolean | Whether this account enables checkout/link webhook configuration. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Publish and enable the checkout before adding a link"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.
- Effective account and creator are authenticated, never accepted from body.
- Published active checkout required. See the *Standalone checkouts and saved offer links* section of llm.md for the end-to-end agent workflow.

##### `POST /v1/checkouts/standalone/:id/publish`

**Scope** `checkouts.write` - **Publish settings and document**

Publishes the current draft settings and draft document together after validating both.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer (>= 0) | **yes** | Current settings draft_revision. |
| `documentRevision` | integer (>= 0) | **yes** | Current document_revision. |

**Request body**

```json
{
  "baseRevision": 3,
  "documentRevision": 7
}
```

**Response** `200`

```json
{
  "version": 2,
  "documentVersion": 5,
  "draftRevision": 3
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Atomically validates the editor document, owned verified domain/catalog/routing/provider references, legal/support contacts, tax/shipping, wallets and delivery combinations; writes immutable configuration and document versions. Affiliates require merchant review. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or the body fails the schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"The checkout changed. Reload before publishing."}`.
- `422` `{"error":"Fix document errors before publishing"}` or `{"error":"Fix publication requirements"}` (issues are not returned: read GET /v1/checkouts/standalone/:id/document for the document issues).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/rotate-secret`

**Scope** `checkouts.write` - **Rotate the link signing secret**

Rotates the secret that signs long links. Links signed with the previous secret stay valid until previousValidUntil.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{
  "rotatedAt": "2026-11-24T10:00:00.000Z",
  "previousValidUntil": "2026-11-25T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `result` | object | Merchant-only signing rotation: the previous secret remains accepted for exactly seven days. Existing short-link storage is unaffected. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `GET /v1/checkouts/standalone/:id/short-links`

**Scope** `checkouts.read` - **List short links**

Lists the checkout's short links (merchant and affiliate-created, newest first) with shortUrl, longUrl, hosting readiness, revision, clicks, sales and safe pixel metadata.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Response** `200`

```json
{"rows": []}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Lists saved offers with effective parameters, immutable revision, pinned checkout version, creator affiliate, URL, lifecycle, clicks and canonical currency-separated sales. Merchants see account links; affiliates see only links they created on a currently visible checkout. |
| `shortUrl` | string | Authoritative saved short URL; field is on link for POST, rows[] for GET. |
| `longUrl` | string | Stable kontrolcheckout.com/l/<UUID> resolver for the same saved link. |
| `hosting` | object | Short and long destinations are ready or pending. DNS/proxy readiness is separate from link active/archive state. New short links require their configured hosting destinations to be ready. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.
- No account ID in a request can override authenticated ownership.
- Use docs/v5/generated/standalone-parameter-reference.md for complete per-field limits, canonical signature vector and Node/PHP/Python snippets.
- Revenue is captured initial plus upsell amounts by currency; orders count captured initial contexts. Rebill and all test classifications are excluded.
- At least one independent product name and unit-price parameter is required to save an autonomous offer. Legacy catalog-backed IDs remain supported but are not required. Amount strings use integer minor units; never store sig or kt.
- Incoming link creator persists across checkout branches without transferring source products/prices. Creator precedes neutral/default ownership; distinct nonnull incoming/selected link creators or flow owners are rejected.
- The merchant owns logo sizing in the checkout builder. logo_height_override is no longer a public link parameter; legacy values are ignored while old URL HMAC bytes remain verifiable.

##### `POST /v1/checkouts/standalone/:id/short-links`

**Scope** `checkouts.write` - **Create or edit a short link**

Creates or CAS-edits an autonomous affiliate offer on a published active reusable checkout. Supply free product name, integer-minor-unit price, quantity, variant label and optional image; no product/store catalog dependency. Creator and account are forced from authentication. Prices, content, locale/legal and owner integration references are signed and pinned; pixels are encrypted in the same immutable revision. Returns shortUrl, longUrl and hosting readiness for the same saved offer; url remains the shortUrl compatibility alias. New short URLs use ktrl.ink and long URLs use kontrolcheckout.com/l/<link UUID>. Never distribute pending hosting links. Legacy URLs remain unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account-scoped checkout UUID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | no | Existing link UUID for edits; omit for a new link. |
| `baseRevision` | integer | no | Required for edit: exact current positive revision from inventory. |
| `name` | string (max 120) | **yes** | Link name, max 120 characters. |
| `active` | boolean | **yes** | Whether the saved public offer is enabled. |
| `parameters` | object<string,string> | **yes** | Free products product1..product10 require name and price without id. Money is integer minor units, quantity1..99, optional variant/image/compare_price. Legacy catalog IDs remain supported. Also currency, shipping/protection, configured content bindings, offered_languages (en,fr,it,es,pt,pl), allowed_countries (ISO2 CSV or * for all checkout-permitted), optional terms_url/privacy_url/refund_url HTTPS, three_ds_integration_key and receipt_sender_id from link-options. Countries cannot widen template restrictions. No manual acquisition setup is needed; supported UTM/click IDs are captured at entry. |
| `pixels` | array<object> | no | Repeatable {id?,name?,network,pixelId,events?,enhancedConversions?,serverEnabled?,accessToken?}. Seven browser networks: facebook,tiktok,snapchat,google,pinterest,applovin,x. X/Google require purchase mapping. accessToken is write-only (omit to retain on same pixel identity, null to clear). Server Purchase is Meta/TikTok/Snap only and requires a token. Undefined copies previous revision; [] clears. No fixed recipient-count cap; pixel JSON max128KiB, request max256KiB. Duplicate destination/mapping conflicts rejected. |

**Request body**

```json
{
  "name": "Linen shirt offer",
  "parameters": {
    "product1_name": "Linen shirt",
    "product1_price": "6798",
    "product1_quantity": "2",
    "product1_variant": "Blue / Large",
    "currency": "USD",
    "offered_languages": "en,fr"
  },
  "pixels": [
    {
      "network": "facebook",
      "pixelId": "123456789012345",
      "serverEnabled": false
    }
  ],
  "active": true
}
```

**Response** `200`

```json
{"link": {"id": "11111111-1111-4111-8111-111111111111", "slug": "aB3dE6g", "revision": 1, "active": true}}
```

| response field | type | description |
|---|---|---|
| `link` | object | Committed saved offer with id, slug, positive revision, configuration pin, parameters and safe pixel metadata. Affiliate View access permits only its own offers, independent products and prices. Edit with id/baseRevision; URL is retained and a new immutable revision is appended. Read inventory for the public URL. Secrets are never returned. |
| `shortUrl` | string | Authoritative saved short URL; field is on link for POST, rows[] for GET. |
| `longUrl` | string | Stable kontrolcheckout.com/l/<UUID> resolver for the same saved link. |
| `hosting` | object | Short and long destinations are ready or pending. DNS/proxy readiness is separate from link active/archive state. New short links require their configured hosting destinations to be ready. |

**Errors**

- `400` `{"error":"Invalid link configuration"}` when the body fails the strict schema; other 400s name the invalid parameter or pixel.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` The link revision changed, or the checkout is not published / enabled (`Publish and enable the checkout before adding a link`).
- `413` Body over 256 KiB.
- `422` Publication validation failed for the link parameters.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A blank template can be published and used with no catalog products. Product/price snapshots are used for payment, receipt and canonical report. Autonomous lines never synchronize to Shopify/Medusa, even if a legacy template had a connector.
- Builder nodes control visibility. Retired hardcoded Visible elements controls do not override the published document. Optional legal URLs may be empty on the template.
- API only supports the23two-decimal CHECKOUT_CURRENCIES. JPY/BHD are rejected; never divide their money by100.
- Pixel credentials are encrypted, omitted from all responses/public URLs/render data and route logs. Server CAPI follows the winning acquisition network, uses immutable link revision and existing order-ID dedup, captured non-test facts only. The elected API leader runs delivery when BACKGROUND_JOBS_ENABLED permits jobs.
- Choose optional owner 3DS/email references only from link-options; the minimal example inherits published defaults. Never use a guessed provider key.
- productN_price is the unit price. The example represents two USD 67.98 units before shipping, discounts and tax.
- The merchant owns logo sizing in the checkout builder. logo_height_override is no longer a public link parameter; legacy values are ignored while old URL HMAC bytes remain verifiable.

##### `PATCH /v1/checkouts/standalone/:id/short-links/:linkId`

**Scope** `checkouts.write` - **Change a short link state**

Activates, deactivates or archives a short link of the checkout, compare-and-set on its revision.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |
| `linkId` | uuid | **yes** | Short link id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer (> 0) | **yes** | Current link revision. |
| `active` | boolean | **yes** | Serve the link. |
| `archived` | boolean | **yes** | Archive the link. |

**Request body**

```json
{
  "baseRevision": 2,
  "active": false,
  "archived": false
}
```

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | True after committed CAS state/revision update. Reload the inventory to obtain the new revision. |

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when an id is not a UUID or the body fails the strict schema (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` The link revision changed (reload and resend with the new baseRevision).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.

##### `POST /v1/checkouts/standalone/:id/url`

**Scope** `checkouts.write` - **Build a signed long link**

Builds a signed public URL of the published checkout carrying the given link parameters (prices, products, content...). Prefer short links for anything sizable.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Standalone checkout id of the account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `parameters` | object<string,string> | **yes** | Link parameters from the checkout parameter catalogue (see GET /v1/checkouts/standalone/:id/link-options for the allowed keys and defaults). |

**Request body**

```json
{"parameters": {"currency": "USD", "sub1": "campaign"}}
```

**Response** `200`

```json
{"url": "https://pay.example.com/c/offer?currency=USD&sub1=campaign&sig=<signature>"}
```

| response field | type | description |
|---|---|---|
| `result` | object | Validates the machine-readable parameter schema and signs commercial, content and pixel overrides. Tracking is unsigned. Native affiliate input is tracking-only and its own public affiliate ID is forced. Customer prefill is POST-only. |

**Errors**

- `400` `{"error":"Link is too long. Use a short link"}` when the query passes the URL size limit.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the id is not a UUID or parameters is missing / not a string map (zod validation): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `404` `{"error":"Checkout not found"}` (or `Published checkout not found`) when the id is not a standalone checkout of the account.
- `409` `{"error":"Publish the checkout before creating a public link"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Checkout signing key unavailable"}`.

**Gotchas**

- A non-UUID path id or a body of the wrong shape answers 400 `Invalid request` with `details.issues` (one entry per problem: `path`, `code`, `message`; the path is empty for the path id). Fix the named field before retrying.
- No account ID in a request can override authenticated ownership.
- Use docs/v5/generated/standalone-parameter-reference.md for complete per-field limits, canonical signature vector and Node/PHP/Python snippets.
- Revenue is captured initial plus upsell amounts by currency; orders count captured initial contexts. Rebill and all test classifications are excluded.
- Public checkout URLs use the current published domain, slug and parameter bindings, including when an editable draft exists. Publication is required.
- Reusable checkout configuration may be published without a default basket; create a saved offer link with catalog products before sending buyers. Published settings.linkPolicy.allowPriceOverrides defaults to false.

##### `GET /v1/checkouts/standalone/options`

**Scope** `checkouts.read` - **Read standalone checkout options**

The choices a standalone checkout can use: serving domains (kontrolcheckout.com first, then the account verified domains), classic ATRIs, configured 3DS providers, enabled e-mail and SMS providers and recovery templates.

*No parameters.*

**Response** `200`

```json
{"domains": [], "atris": [], "catalog": [], "threeDs": [], "emailProviders": [], "smsProviders": [], "templates": [], "connections": []}
```

| response field | type | description |
|---|---|---|
| `result` | object | Returns merchant verified domains, classic ATRIs, configured 3DS integrations, enabled messaging senders and recovery templates. Catalog and connector choices are retired empty compatibility arrays; standalone offers do not depend on a store or product catalog. Affiliate template options are denied. |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"}` when the account's plan does not include the checkouts module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- catalog and connections are always [] (autonomous checkouts have no catalogue dependency).

#### Affiliates

The merchant side of affiliates: create and manage affiliates, share assets with them, generate their links and review their store checkouts. Affiliates themselves use the affiliate portal, which is not part of this API.

- The affiliate login link is composed in the browser: `<dashboard origin>/affiliate/login?account=<accountId>`, where accountId is `GET /v1/me` `accountId`.
- Sorting by revenue, cut or rule is done in the browser on `GET /v1/affiliates`.

##### `GET /v1/affiliates`

**Scope** `affiliates.read` - **List affiliates**

Lists the account's affiliates (archived ones excluded), sorted by name, with their identity, grants, latest cut rule, selected checkout shares and the period money: initial-order count, captured revenue and cuts per currency. Also returns the account's affiliate currency and commerce account ID.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | date or ISO-8601 timestamp; default `30 days before to` | no | Inclusive start of the money window (any value JavaScript Date can parse). Defaults to 30 days before `to`. The window may not exceed 366 days and `from` may not be after `to`. |
| `to` | date or ISO-8601 timestamp; default `now` | no | Inclusive end of the money window. |
| `tz` | IANA timezone; default `UTC` | no | Validated (an unknown zone is rejected) but not used: the window is read as the instants given. |
| `status` | active \| disabled | no | Only affiliates with this status. |
| `search` | string, at most 100 characters (trimmed) | no | Case-insensitive substring matched against name, username, email and public ID. |
| `page` | integer 1..100000; default `1` | no | One-based page. |
| `limit` | integer 1..100; default `25` | no | Page size. |

**Response**

```json
{
  "items": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "public_id": "partner-42",
      "name": "Example Partner",
      "username": "partner",
      "email": "partner@example.com",
      "status": "active",
      "notes": "Merchant only",
      "public_id_locked": false,
      "grants": {
        "dashboard": "view",
        "transactions": "view",
        "checkouts": "view",
        "funnels": "view",
        "flows": "view"
      },
      "checkoutIds": [
        "22222222-2222-4222-8222-222222222222"
      ],
      "rule": {
        "kind": "percent",
        "basisPoints": 3000
      },
      "orders": 1,
      "revenue": [
        {
          "currency": "USD",
          "amount_minor": "5499"
        }
      ],
      "cuts": [
        {
          "currency": "USD",
          "amount_minor": "1650"
        }
      ]
    }
  ],
  "total": 1,
  "currency": "USD",
  "accountId": "acc_0123456789abcdef"
}
```

| response field | type | description |
|---|---|---|
| `items` | object[] | One page of affiliates. |
| `items[].id` | uuid | Affiliate ID. |
| `items[].public_id` | string | Public affiliate ID used in tracking links. |
| `items[].name / username / email / status / notes` | string | Identity and directory fields as saved (email lowercased). |
| `items[].public_id_locked` | boolean | True once the public ID can no longer change. |
| `items[].grants` | object | Portal module grants: dashboard and transactions none\|view; checkouts, funnels and flows none\|view\|edit. |
| `items[].checkoutIds` | uuid[] | Checkouts shared with this affiliate through a selected-affiliates share (checkouts visible to all affiliates are not listed). |
| `items[].rule` | object \| null | Latest cut rule version: {kind:"percent",basisPoints} or {kind:"fixed",money:{amount,currency}}. |
| `items[].orders` | integer | Distinct initial orders with a captured, non-test payment in the window. |
| `items[].revenue` | {currency, amount_minor}[] | Captured initial and upsell payments in the window, per currency, integer minor units as strings. Rebills are excluded. |
| `items[].cuts` | {currency, amount_minor}[] | Signed sum of the cut ledger entries dated in the window (accruals minus reversals and corrections), per currency. |
| `total` | integer | Number of affiliates matching status and search. |
| `currency` | string \| null | Account affiliate currency used by fixed cut rules (set with PATCH /v1/affiliates/settings). |
| `accountId` | string | Commerce account ID (acc_ followed by 16 hex characters). |

**Errors**

- `400` `Choose a date range of up to one year` when from is after to, the window exceeds 366 days or a date cannot be read. `Invalid request` with `details.issues` (one {path, code, message} per problem) when a query value fails validation or an unknown query key is sent (the query is strict).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` `The request took too long and was cancelled` (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget, which includes the wait for a reporting connection. Retry or narrow the range.

**Gotchas**

- All money is integer minor units as strings, separated by currency; nothing is converted.
- Revenue counts captured initial and upsell payments only; rebills and test payments are excluded. Cuts are the signed ledger sum dated in the window, so a reversal can make a period negative.
- Money follows the caller's scope: only payments whose transaction is inside the effective account's tenancy and the caller's ATRI grants count, so a member restricted to some ATRIs sees smaller figures. The affiliate list itself is not narrowed.
- search and status are applied before the money is calculated; `total` counts the matching affiliates. To export everything, page with limit=100 until you have `total` rows.
- The read runs in one read-only snapshot with a 25-second budget (504 past it).
- No pixel configuration is returned.

##### `POST /v1/affiliates`

**Scope** `affiliates.write` - **Create an affiliate**

Creates an affiliate, its portal user, its first cut rule and its checkout shares in one transaction. Without a password, a 72-hour one-time invitation is e-mailed through the account's first enabled e-mail provider.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `publicId` | string matching ^[A-Za-z0-9_-]{1,32}$; default `random` | no | Public affiliate ID used in tracking links. Generated (16 hex characters) when omitted on create. Cannot change after the first attributed order. |
| `name` | string 1..200 (trimmed) | **yes** | Display name. |
| `username` | string matching ^[A-Za-z0-9_.-]{1,80}$ (trimmed) | **yes** | Portal username, unique in the account (case-insensitive). |
| `email` | e-mail, at most 254 characters | **yes** | Login and invitation address, stored lowercased, unique in the account. |
| `status` | active \| disabled; default `active` | no | Disabled blocks the portal and revokes sessions. |
| `notes` | string, at most 5000 characters | no | Merchant-only notes. |
| `rule` | object | **yes** | Cut rule. Percent: {"kind":"percent","basisPoints":0..10000} (3000 = 30%), applied to captured initial and upsell amounts net of tax. Fixed: {"kind":"fixed","money":{"amount":<integer minor units >= 0>,"currency":<the account affiliate currency>}}, accrued once on the first initial capture. No other key is allowed. Required: a missing rule fails the request. |
| `rule.kind` | percent \| fixed | **yes** | Rule type. |
| `rule.basisPoints` | integer 0..10000 | no | Percent rule only. |
| `rule.money.amount` | integer >= 0 (minor units) | no | Fixed rule only. |
| `rule.money.currency` | string | no | Fixed rule only: must equal the account affiliate currency (PATCH /v1/affiliates/settings), itself one of the supported two-decimal currencies. |
| `checkoutIds` | uuid[] (at most 1000, unique) | no | Account checkouts (see GET /v1/affiliates/checkouts) shared with this affiliate. Listed private checkouts become selected_affiliates; checkouts of a previous selection that are left out lose this affiliate's share; checkouts visible to all affiliates are untouched. Omit to keep the current shares. |
| `grants` | object; default `all view` | no | Portal module grants. On create: an object with all five keys (default all view). On update: any subset, merged into the current grants. dashboard and transactions: none \| view; checkouts, funnels and flows: none \| view \| edit. |
| `grants.dashboard` | none \| view | no | Portal dashboard. On create, a grants object must carry all five keys. |
| `grants.transactions` | none \| view | no | Portal transactions list. |
| `grants.checkouts` | none \| view \| edit | no | Checkouts: view shared ones; edit also duplicates and designs own store checkouts. |
| `grants.funnels` | none \| view \| edit | no | Funnel pages. |
| `grants.flows` | none \| view \| edit | no | Flows. |
| `password` | string 12..256 | no | Permanent portal password. Omit to send an invitation instead. It opens the affiliate portal only, never this account's API. |

**Request body**

```json
{
  "publicId": "partner-42",
  "name": "Example Partner",
  "username": "partner",
  "email": "partner@example.com",
  "status": "active",
  "notes": "Merchant only",
  "rule": {
    "kind": "percent",
    "basisPoints": 3000
  },
  "grants": {
    "dashboard": "view",
    "transactions": "view",
    "checkouts": "view",
    "funnels": "view",
    "flows": "view"
  },
  "checkoutIds": [
    "22222222-2222-4222-8222-222222222222"
  ]
}
```

**Response** `201`

```json
{
  "id": "11111111-1111-4111-8111-111111111111",
  "invitationSent": true,
  "passwordChangeRequired": false
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | New affiliate ID. |
| `invitationSent` | boolean | True when the invitation e-mail was accepted by the provider. |
| `passwordChangeRequired` | boolean | Always false. |

**Errors**

- `400` `Invalid affiliate settings` when the body fails the strict schema (an unknown key such as the retired `pixels`, a missing required field, a bad format or an empty password); `Invalid checkout selection` for duplicated checkoutIds; `Unknown checkout` for a checkout outside the account.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `409` `A record with these details already exists.` when the publicId, username or email is already used in the account.
- `422` `Fixed cuts require a supported two-decimal account currency` when a fixed rule is sent while the account currency or the rule currency is not a supported currency.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` when the rule is missing or invalid (for example a percent above 10000 or a fixed currency different from the account currency): those rule errors are not mapped to 400.
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Answers 201. invitationSent is false when a password was set, or when no enabled e-mail provider or HTTPS dashboard origin exists, or delivery failed; the invitation token is never returned (use POST /v1/affiliates/:id/invite later).
- passwordChangeRequired is always false in this response.
- Grants never override sharing: a module grant of none still hides shared assets, and a grant alone does not share anything.
- Pixels are no longer accepted (strict body).

##### `GET /v1/affiliates/:id`

**Scope** `affiliates.read` - **Get one affiliate**

Returns one affiliate of the account with the same fields and period money as the list. Archived affiliates are still returned here.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | date or ISO-8601 timestamp; default `30 days before to` | no | Inclusive start of the money window (any value JavaScript Date can parse). Defaults to 30 days before `to`. The window may not exceed 366 days and `from` may not be after `to`. |
| `to` | date or ISO-8601 timestamp; default `now` | no | Inclusive end of the money window. |
| `tz` | IANA timezone; default `UTC` | no | Validated (an unknown zone is rejected) but not used: the window is read as the instants given. |
| `status` | active \| disabled | no | Accepted for parity with the list and ignored. |
| `search` | string, at most 100 characters | no | Accepted and ignored. |
| `page` | integer 1..100000; default `1` | no | Accepted and ignored. |
| `limit` | integer 1..100; default `25` | no | Accepted and ignored. |

**Response**

```json
{
  "id": "11111111-1111-4111-8111-111111111111",
  "public_id": "partner-42",
  "name": "Example Partner",
  "username": "partner",
  "email": "partner@example.com",
  "status": "active",
  "notes": "Merchant only",
  "public_id_locked": false,
  "grants": {
    "dashboard": "view",
    "transactions": "view",
    "checkouts": "view",
    "funnels": "view",
    "flows": "view"
  },
  "checkoutIds": [
    "22222222-2222-4222-8222-222222222222"
  ],
  "rule": {
    "kind": "percent",
    "basisPoints": 3000
  },
  "orders": 1,
  "revenue": [
    {
      "currency": "USD",
      "amount_minor": "5499"
    }
  ],
  "cuts": [
    {
      "currency": "USD",
      "amount_minor": "1650"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | Affiliate ID. |
| `public_id` | string | Public affiliate ID used in tracking links. |
| `name / username / email / status / notes` | string | Identity and directory fields as saved (email lowercased). |
| `public_id_locked` | boolean | True once the public ID can no longer change. |
| `grants` | object | Portal module grants: dashboard and transactions none\|view; checkouts, funnels and flows none\|view\|edit. |
| `checkoutIds` | uuid[] | Checkouts shared with this affiliate through a selected-affiliates share (checkouts visible to all affiliates are not listed). |
| `rule` | object \| null | Latest cut rule version: {kind:"percent",basisPoints} or {kind:"fixed",money:{amount,currency}}. |
| `orders` | integer | Distinct initial orders with a captured, non-test payment in the window. |
| `revenue` | {currency, amount_minor}[] | Captured initial and upsell payments in the window, per currency, integer minor units as strings. Rebills are excluded. |
| `cuts` | {currency, amount_minor}[] | Signed sum of the cut ledger entries dated in the window (accruals minus reversals and corrections), per currency. |

**Errors**

- `400` `Choose a date range of up to one year`. `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID or a query value fails validation.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `404` `Affiliate not found` when the ID is not an affiliate of the effective account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` `The request took too long and was cancelled` (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget, which includes the wait for a reporting connection. Retry or narrow the range.

**Gotchas**

- Money follows the caller's tenancy and ATRI grants; the affiliate itself is found whatever the scope.
- All money is integer minor units as strings, per currency; revenue excludes rebills and test payments.

##### `PATCH /v1/affiliates/:id`

**Scope** `affiliates.write` - **Update an affiliate**

Updates any subset of the affiliate's identity, status, notes, cut rule, grants, checkout shares or password in one transaction. Omitted fields keep their value.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `publicId` | string matching ^[A-Za-z0-9_-]{1,32}$ | no | Public affiliate ID used in tracking links. Generated (16 hex characters) when omitted on create. Cannot change after the first attributed order. Omit to keep it. |
| `name` | string 1..200 (trimmed) | no | Display name. Omit to keep it. |
| `username` | string matching ^[A-Za-z0-9_.-]{1,80}$ (trimmed) | no | Portal username, unique in the account (case-insensitive). Omit to keep it. |
| `email` | e-mail, at most 254 characters | no | Login and invitation address, stored lowercased, unique in the account. A change revokes the affiliate's sessions and pending links. |
| `status` | active \| disabled | no | Disabled blocks the portal and revokes sessions. Omit to keep it. |
| `notes` | string, at most 5000 characters | no | Merchant-only notes. Omit to keep them. |
| `rule` | object | no | Cut rule. Percent: {"kind":"percent","basisPoints":0..10000} (3000 = 30%), applied to captured initial and upsell amounts net of tax. Fixed: {"kind":"fixed","money":{"amount":<integer minor units >= 0>,"currency":<the account affiliate currency>}}, accrued once on the first initial capture. No other key is allowed. Omit to keep the current rule; a different rule is recorded as a new version. |
| `rule.kind` | percent \| fixed | no | Rule type. |
| `rule.basisPoints` | integer 0..10000 | no | Percent rule only. |
| `rule.money.amount` | integer >= 0 (minor units) | no | Fixed rule only. |
| `rule.money.currency` | string | no | Fixed rule only: must equal the account affiliate currency (PATCH /v1/affiliates/settings), itself one of the supported two-decimal currencies. |
| `checkoutIds` | uuid[] (at most 1000, unique) | no | Account checkouts (see GET /v1/affiliates/checkouts) shared with this affiliate. Listed private checkouts become selected_affiliates; checkouts of a previous selection that are left out lose this affiliate's share; checkouts visible to all affiliates are untouched. Omit to keep the current shares. |
| `grants` | object | no | Portal module grants. On create: an object with all five keys (default all view). On update: any subset, merged into the current grants. dashboard and transactions: none \| view; checkouts, funnels and flows: none \| view \| edit. |
| `grants.dashboard` | none \| view | no | Portal dashboard. |
| `grants.transactions` | none \| view | no | Portal transactions list. |
| `grants.checkouts` | none \| view \| edit | no | Checkouts: view shared ones; edit also duplicates and designs own store checkouts. |
| `grants.funnels` | none \| view \| edit | no | Funnel pages. |
| `grants.flows` | none \| view \| edit | no | Flows. |
| `password` | string 12..256 | no | Permanent portal password. Omit to keep the current credential. Setting it revokes sessions and pending links. It opens the affiliate portal only, never this account's API. |

**Request body**

```json
{
  "status": "active",
  "rule": {
    "kind": "percent",
    "basisPoints": 2500
  },
  "grants": {
    "checkouts": "edit"
  },
  "checkoutIds": [
    "22222222-2222-4222-8222-222222222222"
  ]
}
```

**Response**

```json
{
  "id": "11111111-1111-4111-8111-111111111111"
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | The updated affiliate. |

**Errors**

- `400` `Invalid affiliate settings` when the body fails the strict schema (an unknown key such as the retired `pixels`, a missing required field, a bad format or an empty password); `Invalid checkout selection` for duplicated checkoutIds; `Unknown checkout` for a checkout outside the account. `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `404` `Affiliate not found` when the ID is not an affiliate of the account or is archived.
- `409` `Affiliate ID is locked after its first attributed order` when publicId changes after attribution; `A record with these details already exists.` for a username, email or publicId already used in the account.
- `422` `Fixed cuts require a supported two-decimal account currency`.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` for a missing or invalid cut rule (those rule errors are not mapped to 400).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Setting status disabled, changing the email or setting a password revokes the affiliate's sessions; an email change or a password also invalidates pending invitation and reset links.
- A rule identical to the current one records nothing; a different one becomes a new version for future payments only.
- grants are merged key by key with the current grants.
- Pixels are no longer accepted (strict body).

##### `DELETE /v1/affiliates/:id`

**Scope** `affiliates.write` - **Archive an affiliate**

Removes the affiliate from the directory: marks it archived and disabled and revokes all its portal sessions. Attributed orders, commissions, cut history and owned assets are kept.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Response**

```json
{
  "deleted": true,
  "archived": true
}
```

| response field | type | description |
|---|---|---|
| `deleted` | boolean | Always true. |
| `archived` | boolean | Always true: history is retained. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `404` `Affiliate not found` when the ID is not an affiliate of the account or is already archived.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- There is no un-archive: an archived affiliate answers 404 to update and invite, is excluded from the list, but GET /v1/affiliates/:id still returns it.
- No body. Bulk callers repeat this call per affiliate.

##### `GET /v1/affiliates/:id/cuts`

**Scope** `affiliates.read` - **List affiliate cut entries**

Returns every cut ledger entry of one affiliate dated in the window, oldest first: accruals and their refund, chargeback and correction reversals.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | date or ISO-8601 timestamp; default `30 days before to` | no | Inclusive start of the money window (any value JavaScript Date can parse). Defaults to 30 days before `to`. The window may not exceed 366 days and `from` may not be after `to`. |
| `to` | date or ISO-8601 timestamp; default `now` | no | Inclusive end of the money window. |
| `tz` | IANA timezone; default `UTC` | no | Validated (an unknown zone is rejected) but not used: the window is read as the instants given. |
| `status` | captured \| failed \| pending \| unknown \| rejected | no | Accepted and ignored. |
| `kind` | initial \| upsell \| rebill | no | Accepted and ignored. |
| `search` | string, at most 100 characters | no | Accepted and ignored. |
| `page` | integer 1..100000; default `1` | no | Accepted and ignored: the whole window is returned. |
| `limit` | integer 1..100; default `25` | no | Accepted and ignored. |

**Response**

```json
{
  "items": [
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "order_context_id": "22222222-2222-4222-8222-222222222222",
      "entry_kind": "accrual",
      "amount_minor": "1650",
      "currency": "USD",
      "occurred_at": "2026-10-29T10:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `items[].id` | uuid | Ledger entry ID. |
| `items[].order_context_id` | uuid | Order context the entry belongs to. |
| `items[].entry_kind` | accrual \| refund \| chargeback \| correction | Entry type. |
| `items[].amount_minor` | string | Signed amount in minor units. |
| `items[].currency` | string | Currency. |
| `items[].occurred_at` | ISO-8601 | Event date of the entry. |

**Errors**

- `400` `Choose a date range of up to one year`. `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID or a query value fails validation (the query is strict).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` `The request took too long and was cancelled` (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget, which includes the wait for a reporting connection. Retry or narrow the range.

**Gotchas**

- An unknown affiliate ID answers 200 with an empty list, not 404.
- amount_minor is a signed integer string (reversals are negative). Entries follow the caller's tenancy and ATRI grants.

##### `POST /v1/affiliates/:id/invite`

**Scope** `affiliates.write` - **Resend an affiliate invitation**

Issues a new 72-hour one-time invitation for an active affiliate and e-mails it through the account's first enabled e-mail provider. Earlier unused invitation and reset links stop working.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Response**

```json
{
  "invitationSent": true
}
```

| response field | type | description |
|---|---|---|
| `invitationSent` | boolean | True when the e-mail provider accepted the message. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `404` `Affiliate not found` when the affiliate is missing, archived or disabled.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- invitationSent is false when no enabled e-mail provider or HTTPS dashboard origin exists or delivery failed; the new link is still issued and the old ones are still invalidated. The token is never returned.
- No body is read.

##### `POST /v1/affiliates/:id/reset-mfa`

**Scope** `affiliates.write` - **Reset affiliate two-step verification**

Recovers an affiliate who lost their authenticator: clears the enrolled and pending TOTP secrets, revokes every session and unused authentication link, and writes the audit entry, in one transaction.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Affiliate ID in the effective account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | empty object | no | No body, or exactly {}. Any key is refused. |

**Request body**

```json
{}
```

**Response**

```json
{
  "reset": true
}
```

| response field | type | description |
|---|---|---|
| `reset` | boolean | True when a TOTP secret was removed. |

**Errors**

- `400` `Invalid request` when the body is not empty. `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `404` `Affiliate not found` when the ID is not an affiliate of the account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` when the transaction (audit included) fails; nothing is committed then.
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- reset is false when two-step verification was not enabled; nothing is revoked then.
- Password, grants, status and ownership are kept. No e-mail is sent; send a fresh invitation with POST /v1/affiliates/:id/invite if needed. Verify the affiliate's identity first.
- No secret or token is returned.

##### `POST /v1/affiliates/assets/:kind/:id/links`

**Scope** `affiliates.write` - **Generate published asset distribution links**

Returns the current public entry URLs of a published checkout, landing page (funnel) or flow, with validated tracking parameters appended, for distribution (ads, affiliates). A standalone checkout answers its /c/<slug> or /funnel/<pageId> URL on its verified domain; a store checkout needs an existing real cart checkout URL (checkoutUrl) and answers a /api/v5/store-entry URL on the store domain. Answers with Cache-Control: private, no-store.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | "checkout" \| "funnel" \| "flow" | **yes** | Asset type: a checkout, a landing page, or a flow. Post-sell pages have no distribution URL. Any other value fails validation (answered 400, see errors). |
| `id` | uuid | **yes** | Asset id in the caller's account. Not a uuid fails validation (400). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `tracking` | object of string values (each <= 2048); default `{}` | no | Tracking parameters to append, as {name: value}. Only parameters of the tracking class (for example sub1..sub5, source_id, utm_*, click ids) and lang are allowed; keys must match [A-Za-z_][A-Za-z0-9_]{0,63}. Commercial parameters, customer data, sig and kt are refused (400). affid: a public id of one of the account's active affiliates, matched without case (returned in its canonical case; unknown = 400 "Affiliate unavailable"). For a store link, the tracking already in checkoutUrl is validated and kept, and these entries replace keys with the same name. |
| `checkoutUrl` | string <= 16000 | no | Store checkouts only: an existing cart checkout URL, https://<verified store domain>/checkout/<token>, where <token> is the base64url JSON {shopUrl, cartToken, ...} of a real cart routed to this checkout (or flow). No user, password or fragment. Without it a store asset answers requiresCart:true and urls:[]. Session and recovery parameters (sid, recover, order, wallet handoffs...) are stripped from the result. |

**Request body**

```json
{
  "tracking": {
    "sub1": "spring-campaign",
    "source_id": "partner-12"
  }
}
```

**Response**

```json
{
  "checkoutType": "standalone",
  "requiresCart": false,
  "urls": [
    "https://shop.example.com/c/summer-offer?sub1=spring-campaign&source_id=partner-12"
  ]
}
```

| response field | type | description |
|---|---|---|
| `checkoutType` | "standalone" \| "store" | standalone = a checkout with its own published domain and slug; store = a checkout attached to a store cart. |
| `requiresCart` | boolean | true when the asset is a store checkout and no checkoutUrl was sent: urls is then empty. |
| `urls` | string[] | The distribution URLs. Standalone: https://<domain>/c/<slug>?<tracking> or https://<domain>/funnel/<pageId>?<tracking> (one per assigned standalone checkout when the flow branches). Store: https://<store domain>/api/v5/store-entry?return=<cart path and tracking>&shared=1[&landing=<pageId>]. |

**Errors**

- `400` {"error":"<message>"}: a tracking parameter refused ("Only tracking parameters and visitor language may be appended", "Unknown parameter", "Invalid parameter key", "Duplicate parameter", "Parameter requires a value", "Invalid <name>"), {"error":"Affiliate unavailable"} (affid not an active affiliate of the account), {"error":"Use a valid HTTPS store checkout URL"}, {"error":"Use a valid store cart entry token"}, {"error":"Store checkout domain unavailable"} (the cart's store is not a verified store of the account or not routed to this checkout), {"error":"Cart is not assigned to this flow"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the path or body fails validation (kind not checkout|funnel|flow, id not a uuid, an unknown body field, a tracking value that is not a string or longer than 2048, checkoutUrl longer than 16000): one issue per problem with its dotted `path` (empty for a path id or an unknown key), the zod `code` and its `message`.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"affiliates.write"} when the key's scopes lack affiliates.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"affiliates"} when the account's plan lacks the affiliates module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin; {"error":"Forbidden"} when the funnel, flow or a checkout it references is not visible to the account (another account's id included).
- `409` {"error":"<message>"}: "No published entry point", "Landing page starts more than one published flow", "Published flow unavailable", "Published landing unavailable", "Published landing is unavailable or ambiguous", "Flow is not assigned to this checkout", "Published checkout domain unavailable" (no published version on a verified domain).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: a kind=checkout id that is not a checkout of the account, or another unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- For kind=checkout the checkout is first attached to the account's commerce account (one-time, no visible change), then the links are built.
- Only current published entries are used: an unpublished, archived or ambiguous entry fails closed (409). Editor previews, customer data, payment routing and flow session ids are never returned.
- A store request without checkoutUrl is not an error: it answers requiresCart:true and urls:[]. Send the URL of a real cart of that store to get a link.
- A branched flow (A/B test or condition) never picks a branch here: the links enter the assigned source checkouts, and the runtime pins the visitor's branch.
- Store landing links validate the real cart, pin the published landing flow and set the cookies before rendering, then redirect to the clean flow route.

##### `GET /v1/affiliates/assets/:kind/:id/sharing`

**Scope** `affiliates.read` - **Read asset sharing**

Returns who can see one checkout, funnel page or flow of the account in the affiliate portal: its visibility and, for selected_affiliates, the affiliate IDs it is shared with.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | checkout \| funnel \| flow | **yes** | Asset kind. |
| `id` | uuid | **yes** | Checkout ID, funnel page ID or flow ID in the effective account. |

**Response**

```json
{
  "visibility": "selected_affiliates",
  "affiliateIds": [
    "11111111-1111-4111-8111-111111111111"
  ]
}
```

| response field | type | description |
|---|---|---|
| `visibility` | private \| all_affiliates \| selected_affiliates | Current visibility. |
| `affiliateIds` | uuid[] | Affiliates of a selected share. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when kind or id fails validation.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie. `Forbidden` when the funnel page or flow is not in the effective account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` with a `requestId` when a checkout ID does not belong to the account (that scope check is not mapped to 404).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- visibility is private (default), all_affiliates or selected_affiliates. affiliateIds (sorted) lists the selected shares and is normally empty unless visibility is selected_affiliates.
- For a checkout, the first read attaches a legacy checkout of the account owner to the commerce account (a one-time write).

##### `PATCH /v1/affiliates/assets/:kind/:id/sharing`

**Scope** `affiliates.write` - **Update asset sharing**

Sets the portal visibility of one checkout, funnel page or flow of the account and replaces its selected affiliate shares atomically.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | checkout \| funnel \| flow | **yes** | Asset kind. |
| `id` | uuid | **yes** | Checkout ID, funnel page ID or flow ID in the effective account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `visibility` | private \| all_affiliates \| selected_affiliates | **yes** | private: no affiliate; all_affiliates: every affiliate with the module grant; selected_affiliates: only affiliateIds. |
| `affiliateIds` | uuid[] (at most 1000, unique); default `[]` | no | Affiliates of the account to share with. Stored only with selected_affiliates; existing shares are always replaced. |

**Request body**

```json
{
  "visibility": "selected_affiliates",
  "affiliateIds": [
    "11111111-1111-4111-8111-111111111111"
  ]
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |

**Errors**

- `400` `Invalid sharing` for duplicated affiliateIds; `Unknown affiliate` when an ID is not an affiliate of the account. `Invalid request` with `details.issues` (one {path, code, message} per problem) when kind, id or the body (strict: visibility and affiliateIds only) fails validation.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie. `Forbidden` when the funnel page or flow is not in the effective account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` with a `requestId` when a checkout ID is outside the account (that scope check is not mapped to 404).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Sharing does not grant module access or publication rights: the affiliate still needs the matching grant.
- Archived affiliates are accepted in affiliateIds but cannot sign in.

##### `GET /v1/affiliates/checkouts`

**Scope** `affiliates.read` - **List checkout choices for affiliate access**

Lists every checkout owned by the account (any type), sorted by name, with its current sharing visibility and owning affiliate. These are the IDs accepted in `checkoutIds` when creating or updating an affiliate.

*No parameters.*

**Response**

```json
{
  "items": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "name": "Main store checkout",
      "type": "store",
      "visibility": "selected_affiliates",
      "ownerAffiliateId": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `items[].id` | uuid | Checkout ID. |
| `items[].name` | string | Checkout name. |
| `items[].type` | string | Checkout type (for example store or standalone). |
| `items[].visibility` | private \| all_affiliates \| selected_affiliates | Current sharing visibility. |
| `items[].ownerAffiliateId` | uuid \| null | Affiliate that owns the checkout, if any. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- visibility is private, all_affiliates or selected_affiliates. A checkout visible to all affiliates is inherited by everyone: it cannot be removed through an affiliate's checkoutIds.
- ownerAffiliateId is set for a checkout an affiliate created (for example a duplicated store checkout).

##### `PATCH /v1/affiliates/settings`

**Scope** `affiliates.write` - **Set the affiliate account currency**

Sets the account currency used by fixed-amount cut rules. It can change freely until the first fixed rule exists; after that only the same value is accepted.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `currency` | string (enum) | **yes** | One of USD, EUR, GBP, CAD, AUD, NZD, CHF, SEK, NOK, DKK, PLN, CZK, HUF, RON, BGN, BRL, MXN, SGD, HKD, AED, SAR, ILS, ZAR (two-decimal currencies). The body is strict: no other key. |

**Request body**

```json
{
  "currency": "USD"
}
```

**Response**

```json
{
  "currency": "USD"
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the body fails validation (missing or unsupported currency, extra key).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `409` `Currency is locked after the first fixed cut rule` when the value differs from the current one and a fixed rule was recorded.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- No conversion or rescaling is performed; JPY, BHD and other unsupported currencies are refused.
- Percent rules do not depend on this setting; fixed rules must use exactly this currency.

##### `GET /v1/v5/affiliates/store-checkouts/reviews`

**Scope** `affiliates.read` - **List store checkouts and their review status**

Lists the account's store checkouts with the pending-review flag set when an affiliate duplicated or edited the design of one. The merchant approves by publishing the checkout document with the existing checkout editor endpoints.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "name": "Partner store checkout",
      "owned": false,
      "pendingReview": true,
      "publishedVersion": 0,
      "updatedAt": "2026-10-29T08:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].id` | uuid | Store checkout ID. |
| `rows[].name` | string | Checkout name. |
| `rows[].owned` | boolean | Always false for this merchant view. |
| `rows[].pendingReview` | boolean | True when an affiliate change awaits merchant publication. |
| `rows[].publishedVersion` | integer | Current published version, 0 when never published. |
| `rows[].updatedAt` | ISO-8601 | Last change. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `affiliates`) when the plan lacks the affiliates module; `Forbidden` when the request carries an affiliate portal cookie.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- owned is always false here (it means owned by the calling affiliate on the portal side).
- publishedVersion 0 means the checkout has never been published; a pending duplicate stays inactive until a merchant publishes it.

#### Domains

The domain of each store: diagnose, verify, set up DNS, move between services, and the background domain operations.

##### `POST /v1/checkouts/:shopId/domain/check`

**Scope** `checkouts.write` - **Diagnose the store domain connection**

Read-only connection check across three sources: what Render expects and knows (custom domain registered? verified? expected record), what the account's Cloudflare zone holds for that exact host (account integration first, platform token as fallback), and what public DNS resolves right now - merged into one verdict and a list of human-readable issues. Nothing is written.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "domain": "shop.example.com",
  "expected": {
    "type": "CNAME",
    "target": "checkout-web.onrender.com"
  },
  "render": {
    "configured": true,
    "serviceId": "srv-d7nnfebeo5us73fecth0",
    "serviceHost": "checkout-web.onrender.com",
    "registered": true,
    "id": "cd-d2k1a3b4c5d6e7f8g9h0",
    "verificationStatus": "verified",
    "dnsRecordType": "CNAME",
    "dnsRecordValue": "checkout-web.onrender.com",
    "error": null
  },
  "cloudflare": {
    "source": "account",
    "zone": "example.com",
    "records": [
      {
        "type": "CNAME",
        "name": "shop.example.com",
        "content": "checkout-web.onrender.com",
        "proxied": false
      }
    ],
    "matches": true,
    "proxied": false,
    "error": null
  },
  "publicDns": {
    "cname": "checkout-web.onrender.com",
    "a": [],
    "matches": true,
    "error": null
  },
  "verdict": "connected",
  "issues": []
}
```

| response field | type | description |
|---|---|---|
| `domain` | string | The store host checked. |
| `expected` | object | { type: A or CNAME, target } the DNS should carry. |
| `render` | object | configured, serviceId, serviceHost, registered, id, verificationStatus, dnsRecordType, dnsRecordValue, error, otherService (the domain is on another service: { name, id, verificationStatus }), retryAfterMs (Render rate limit), storefront (served by the storefront service). |
| `cloudflare` | object | source (account, platform, one-shot or null), zone, zoneId, records[] { type, name, content, proxied }, matches, proxied, error, canFix (credentials and zone found). |
| `publicDns` | object | cname, a[], matches, error. |
| `openCloudflare` | object | { zoneName, onCloudflare, nameserversKnown, url, steps[], tokenUrl, tokenScopes[] }. |
| `verdict` | string | connected, dns_mismatch, not_registered, pending or unknown. |
| `issues[]` | string[] | Actionable messages. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).
- `503` {"error":"Domain check timed out","requestId":"<id>"} (Retry-After: 1) when the bounded read budget expires, or the database is unavailable; retry.

**Gotchas**

- Cloudflare lookups use the STORE OWNER's integration, not the caller's - relevant for super_admin.
- Public DNS is resolved from the cocoapi server; a freshly changed record may still show the old value for the TTL.
- :shopId is not format-validated by the route; a non-UUID value is passed straight into the checkout-database filter and surfaces as a 500, not a 404.
- Takes no body. Answers with Cache-Control no-store.
- openCloudflare gives a credential-free path: a deep link to the zone DNS page (or to add the site), the exact record, and tokenUrl / tokenScopes for a token to paste into POST /v1/checkouts/:shopId/domain/setup-cloudflare.

##### `POST /v1/checkouts/:shopId/domain/fix-cloudflare`

**Scope** `checkouts.write` - **Queue domain fix-cloudflare**

Queue a durable domain job to write the expected DNS record in the account Cloudflare zone, verify on Render and re-check. Answers 202 { jobId, job } once the job is committed; poll GET /v1/checkouts/domain/jobs/:jobId. Equivalent to POST /v1/checkouts/domain/jobs with this action; never retry a lost answer blindly, reuse the same requestId instead.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Idempotency key. Absent = a random one (a retry then creates a new job). Other body keys are ignored. |

**Request body**

```json
{
 "requestId": "55555555-5555-4555-8555-555555555555"
}
```

**Response** `202`

```json
{
 "jobId": "66666666-6666-4666-8666-666666666666",
 "job": {
  "id": "66666666-6666-4666-8666-666666666666",
  "status": "queued"
 }
}
```

**Errors**

- `400` Invalid input
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: requestId in the body is not a UUID (checked before the background-operations check below).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` Current permission or ownership changed; API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store not visible in the caller's account
- `409` Hostname reservation or request identity conflict, or another domain operation already holds this host
- `422` Configuration changed or is unavailable
- `429` Too many unfinished domain jobs
- `503` {"error":"Background domain operations are unavailable"}; worker, schema or bounded control unavailable

**Gotchas**

- Confirmed effects remain after a cancel. An unknown outcome is never retried or expired automatically.
- The answer carries Cache-Control no-store.

##### `POST /v1/checkouts/:shopId/domain/move-service`

**Scope** `checkouts.write` - **Queue a store move between services**

Queue a durable job that moves the store domain between the checkout service and the storefront service. Deliberate and never automatic: the host does not serve between the old registration being released and the new certificate being issued. Answers 202 { jobId, job }; poll GET /v1/checkouts/domain/jobs/:jobId.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key of the move. |
| `to` | string | **yes** | checkout or storefront: the destination service. |

**Request body**

```json
{
 "requestId": "55555555-5555-4555-8555-555555555555",
 "to": "storefront"
}
```

**Response** `202`

```json
{
 "jobId": "66666666-6666-4666-8666-666666666666",
 "job": {
  "id": "66666666-6666-4666-8666-666666666666",
  "status": "queued"
 }
}
```

**Errors**

- `400` {"error":"Choose a destination and a UUID requestId"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Current principal or owner no longer authorized; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store or operation unavailable in the caller's account
- `409` Conflicting hostname, identity, reservation or routing ownership
- `422` Configuration changed or explicit provider selection required
- `429` Too many unfinished domain jobs
- `503` {"error":"Background service moves are unavailable"}; worker, migration or control budget unavailable

**Gotchas**

- No automatic compensation or repeat of unknown provider outcomes.
- The answer carries Cache-Control no-store.

##### `POST /v1/checkouts/:shopId/domain/remove`

**Scope** `checkouts.write` - **Queue domain remove**

Queue a durable domain job to release the store domain from Render. Answers 202 { jobId, job } once the job is committed; poll GET /v1/checkouts/domain/jobs/:jobId. Equivalent to POST /v1/checkouts/domain/jobs with this action; never retry a lost answer blindly, reuse the same requestId instead.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Idempotency key. Absent = a random one (a retry then creates a new job). Other body keys are ignored. |

**Request body**

```json
{
 "requestId": "55555555-5555-4555-8555-555555555555"
}
```

**Response** `202`

```json
{
 "jobId": "66666666-6666-4666-8666-666666666666",
 "job": {
  "id": "66666666-6666-4666-8666-666666666666",
  "status": "queued"
 }
}
```

**Errors**

- `400` Invalid input
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: requestId in the body is not a UUID (checked before the background-operations check below).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` Current permission or ownership changed; API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store not visible in the caller's account
- `409` Hostname reservation or request identity conflict, or another domain operation already holds this host
- `422` Configuration changed or is unavailable
- `429` Too many unfinished domain jobs
- `503` {"error":"Background domain operations are unavailable"}; worker, schema or bounded control unavailable

**Gotchas**

- Confirmed effects remain after a cancel. An unknown outcome is never retried or expired automatically.
- The answer carries Cache-Control no-store.

##### `POST /v1/checkouts/:shopId/domain/setup-cloudflare`

**Scope** `checkouts.write` - **Configure the store domain in Cloudflare**

Writes the DNS record Render expects into the store's Cloudflare zone using a token supplied IN THIS REQUEST, then registers the domain on Render if absent, asks Render to verify, and returns a fresh domain check. Exists because Cloudflare's dashboard cannot be driven by a URL - there is no link that creates a DNS record - so the operator makes a token from a prefilled template (the `openCloudflare.tokenUrl` of the check response) and pastes it once. The token is used for this call and discarded: never written to `integrations`, never logged, never echoed back.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `apiToken` | string | **yes** | A Cloudflare API token for this call only (never stored, logged or returned). Needs DNS:Edit, plus Zone:Read unless zoneId is given. |
| `zoneId` | string | no | Optional Cloudflare zone ID: skips the zone lookup, so a token that may only edit DNS is enough. |

**Request body**

```json
{
 "apiToken": "<a Cloudflare API token>",
 "zoneId": "<optional zone id>"
}
```

**Response**

```json
{
  "fix": {
    "applied": true,
    "created": true,
    "updated": false,
    "removed": 0,
    "error": null,
    "renderStatus": "verified"
  },
  "check": { "domain": "pay.example.com", "verdict": "connected", "expected": { "type": "CNAME", "target": "checkout-63p6.onrender.com" } }
}
```

| response field | type | description |
|---|---|---|
| `fix.applied` | boolean | The record now matches what Render expects. False when anything above it failed; read `fix.error`. |
| `fix.created` | boolean | A record was added (there was none for this host). |
| `fix.updated` | boolean | An existing record was corrected - retargeted, or un-proxied. |
| `fix.removed` | integer | How many conflicting records for the same host were deleted. |
| `fix.error` | string\|null | Why nothing was applied: no zone for this domain under the token, Render gave no target, or Cloudflare refused. |
| `fix.renderStatus` | string\|null | What Render answered when asked to verify, e.g. 'verified' or 'unverified'. |
| `check` | object | A FRESH domain check taken after the write - the same shape as POST /domain/check. Read `check.verdict`, not `fix.applied`, to decide whether the store is live. |

**Errors**

- `400` {"error":"apiToken required"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: unknown store, archived store, or a store of another account
- `409` {"error":"Domain work already exists; open its saved progress before changing this host"} (with jobId); {"error":"A domain operation or unresolved remote write already holds this host"}
- `500` Internal Server Error with a requestId, including checkout-database failures (for example a shopId that is not a UUID).
- `503` {"error":"Domain jobs migration is unavailable"}

**Gotchas**

- The token is NOT persisted. Every setup asks for a new one; that is deliberate, so cocoapi never becomes a store of other people's Cloudflare credentials.
- A 200 does not mean the domain is live. Render issues the certificate asynchronously, so `check.verdict` is often 'pending' on the first call and 'connected' a minute later - call POST /domain/check again rather than trusting `fix.applied`.
- The record is written DNS-only (proxy off) on purpose, and an existing proxied record is REWRITTEN. Proxied, Render can neither verify the domain nor issue TLS.
- Conflicting records for the same host are deleted, not merged. If the zone held an A record for this host pointing somewhere else, it is gone.
- The token needs Zone:Read as well as DNS:Edit - the zone is found by name before the record is written, so a DNS-only token fails with 'no zone for this domain'.
- Only the one host is touched. The apex and www are left alone, which is what keeps a Shopify store working on the same domain.

##### `POST /v1/checkouts/:shopId/domain/verify`

**Scope** `checkouts.write` - **Queue domain verify**

Queue a durable domain job to register and verify the store domain on Render. Answers 202 { jobId, job } once the job is committed; poll GET /v1/checkouts/domain/jobs/:jobId. Equivalent to POST /v1/checkouts/domain/jobs with this action; never retry a lost answer blindly, reuse the same requestId instead.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Idempotency key. Absent = a random one (a retry then creates a new job). Other body keys are ignored. |

**Request body**

```json
{
 "requestId": "55555555-5555-4555-8555-555555555555"
}
```

**Response** `202`

```json
{
 "jobId": "66666666-6666-4666-8666-666666666666",
 "job": {
  "id": "66666666-6666-4666-8666-666666666666",
  "status": "queued"
 }
}
```

**Errors**

- `400` Invalid input
- `400` {"error":"Invalid request","details":{"issues":[{"path","code","message"}]}}: requestId in the body is not a UUID (checked before the background-operations check below).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` Current permission or ownership changed; API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` Store not visible in the caller's account
- `409` Hostname reservation or request identity conflict, or another domain operation already holds this host
- `422` Configuration changed or is unavailable
- `429` Too many unfinished domain jobs
- `503` {"error":"Background domain operations are unavailable"}; worker, schema or bounded control unavailable

**Gotchas**

- Confirmed effects remain after a cancel. An unknown outcome is never retried or expired automatically.
- The answer carries Cache-Control no-store.

##### `GET /v1/checkouts/domain/job-capabilities`

**Scope** `checkouts.read` - **Read domain job availability**

Says whether background domain operations (enabled) and service moves (moves) are available on this deployment: they need background workers, the local checkout database and the domain job tables. localOnly is always true.

*No parameters.*

**Response**

```json
{
  "enabled": true,
  "localOnly": true,
  "moves": true
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Required storage for domain jobs is unavailable. Complete the current database migrations."}` (or `... for domain moves ...`) when workers are on but the tables are missing.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- When enabled is false, POST /v1/checkouts/domain/jobs answers 503 `Background domain operations are unavailable`.

##### `GET /v1/checkouts/domain/jobs`

**Scope** `checkouts.read` - **List domain operations of a store**

Lists the caller's last 20 domain operations of one store (the one matching requestId first, then unfinished ones, then newest) and any legacy reservation still holding the store's hostname.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store id. |
| `requestId` | uuid | no | Puts the job with this request id first (to recover a lost create answer). |

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000701",
      "request_id": "00000000-0000-4000-8000-000000000702",
      "shop_id": "00000000-0000-4000-8000-000000000201",
      "hostname": "shop.example.com",
      "action": "register",
      "status": "queued",
      "phase": "render",
      "total": 4,
      "move_pending": false,
      "result": null,
      "processed": 0,
      "succeeded": 0,
      "failed": 0,
      "errors": [],
      "skipped": 0,
      "effects": 0,
      "cancel_requested": false,
      "error": null,
      "created_at": "2026-11-24T10:00:00.000Z",
      "updated_at": "2026-11-24T10:00:00.000Z",
      "finished_at": null
    }
  ],
  "reservation": null
}
```

**Errors**

- `400` `{"error":"Choose a store"}` when shopId is missing or not a UUID; `{"error":"Invalid saved request identity"}` when requestId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `403` `{"error":"Store access changed"}` when the store is not routed to this account; `Import API key or account access changed` when the key was revoked or its owner changed.
- `404` `{"error":"Store not found"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- reservation is {hostname, uncertain, live} when an older synchronous domain call still holds the hostname; uncertain true needs POST /v1/checkouts/domain/reconcile-legacy. jobs is [] when the domain tables are missing.
- A job is visible only to the caller that created it (the same API key) with the same role and permissions; another caller of the same account gets 404 `Domain operation not found or permissions changed`.

##### `POST /v1/checkouts/domain/jobs`

**Scope** `checkouts.write` - **Start a domain operation**

Admits a background operation on a store's domain and answers 202 with the job: register (attach the hostname to the serving service), verify (check DNS and certificate), remove (detach it), fix-cloudflare (repair the Cloudflare custom hostname with the account's Cloudflare integration) or move-service (move the store between the legacy checkout service and the storefront service). Follow it with GET /v1/checkouts/domain/jobs/:jobId.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key. The same requestId with the same shopId / action / to returns the same job; with different values, 409. |
| `shopId` | uuid | **yes** | Store (shop) id routed to this account; its domain is the hostname operated on. |
| `action` | enum: register \| verify \| remove \| fix-cloudflare \| move-service | **yes** | Operation to run. |
| `to` | enum: checkout \| storefront | no | Destination service. Required when action is move-service (`checkout` = legacy checkout service, `storefront` = Kontrol storefront service); ignored otherwise. |

**Request body**

```json
{
  "requestId": "00000000-0000-4000-8000-000000000702",
  "shopId": "00000000-0000-4000-8000-000000000201",
  "action": "move-service",
  "to": "storefront"
}
```

**Response** `202`

```json
{
  "jobId": "00000000-0000-4000-8000-000000000701",
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "request_id": "00000000-0000-4000-8000-000000000702",
    "shop_id": "00000000-0000-4000-8000-000000000201",
    "hostname": "shop.example.com",
    "action": "move-service",
    "status": "queued",
    "phase": "render",
    "total": 4,
    "move_pending": true,
    "result": null,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "errors": [],
    "skipped": 0,
    "effects": 0,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "destination": "storefront"
  }
}
```

**Errors**

- `400` `{"error":"Invalid domain operation"}` when the body fails the schema (strict, at most 4 KiB); `{"error":"Choose a destination service"}` for move-service without to; `Medusa requires the Kontrol storefront service`.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `403` `{"error":"Store access changed"}` when the store is not routed to this account; `Import API key or account access changed` when the key was revoked or its owner changed.
- `404` `{"error":"Store not found"}`.
- `409` `Request identity was already used with different parameters or permissions`; `{"error":"A domain operation already holds this hostname; open its saved progress","jobId":"..."}`; `A legacy domain operation or unresolved write holds this hostname`; for a move: `This store uses a checkout flow and requires the Kontrol storefront service...`, `Store routing and payment provider ownership disagree; resolve this before moving`.
- `413` Body over 4 KiB.
- `422` Move preconditions: `Configure a store owner before moving its service`, `The destination Render service is not configured`, `Remove the storefront environment override before moving this store to checkout`, `This store has no legacy checkout provider reference. Keep it on the storefront service.`, `Configure the store payment routing key before moving to the legacy checkout`.
- `429` `{"error":"This account already has 25 unfinished domain operations"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Background domain operations are unavailable"}`, `Background domains require the local checkout database`, or `Service move migration or destination is unavailable`.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- One unfinished operation per hostname, 25 per account. If the answer is lost, resend the same requestId (or find it with GET /v1/checkouts/domain/jobs?shopId=...&requestId=...).
- An uncertain remote write is never replayed automatically: the job stays uncertain and holds the hostname until POST /v1/checkouts/domain/jobs/:jobId/reconcile proves its outcome.
- A job is visible only to the caller that created it (the same API key) with the same role and permissions; another caller of the same account gets 404 `Domain operation not found or permissions changed`.

##### `GET /v1/checkouts/domain/jobs/:jobId`

**Scope** `checkouts.read` - **Read a domain operation**

Returns one domain operation: status (queued, running, success, partial, failed, cancelled, uncertain), phase, counters, effects, move state and error. No provider credential or request body is exposed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Domain job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "request_id": "00000000-0000-4000-8000-000000000702",
    "shop_id": "00000000-0000-4000-8000-000000000201",
    "hostname": "shop.example.com",
    "action": "register",
    "status": "success",
    "phase": "done",
    "total": 4,
    "move_pending": false,
    "result": null,
    "processed": 4,
    "succeeded": 4,
    "failed": 0,
    "errors": [],
    "skipped": 0,
    "effects": 2,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": "2026-11-24T10:01:10.000Z"
  }
}
```

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"","code":"invalid_string","message":"Invalid uuid"}]}}` when :jobId is not a UUID (zod validation of the path parameter; the issue path is empty).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `404` `{"error":"Domain operation not found or permissions changed"}` when the job is unknown, another account's, or was created by another caller or under other permissions.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- A non-UUID jobId answers 400 `Invalid request` with `details.issues` (the issue path is empty: it is the path parameter).
- A job is visible only to the caller that created it (the same API key) with the same role and permissions; another caller of the same account gets 404 `Domain operation not found or permissions changed`.

##### `POST /v1/checkouts/domain/jobs/:jobId/cancel`

**Scope** `checkouts.write` - **Cancel a domain operation**

Stops a domain operation: a queued job without a pending remote write is cancelled at once; a running job stops before its next effect (confirmed changes remain); a move already past a confirmed stage becomes partial and keeps the hostname reserved until resumed; a job with an unknown remote effect keeps its reservation.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Domain job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "request_id": "00000000-0000-4000-8000-000000000702",
    "shop_id": "00000000-0000-4000-8000-000000000201",
    "hostname": "shop.example.com",
    "action": "register",
    "status": "cancelled",
    "phase": "render",
    "total": 4,
    "move_pending": false,
    "result": null,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "errors": [],
    "skipped": 0,
    "effects": 0,
    "cancel_requested": true,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null
  }
}
```

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"","code":"invalid_string","message":"Invalid uuid"}]}}` when :jobId is not a UUID (zod validation of the path parameter; the issue path is empty).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `404` `{"error":"Domain operation not found or permissions changed"}` when the job is unknown, another account's, or was created by another caller or under other permissions.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- A finished job is returned unchanged.
- A non-UUID jobId answers 400 `Invalid request` with `details.issues` (the issue path is empty: it is the path parameter).

##### `POST /v1/checkouts/domain/jobs/:jobId/reconcile`

**Scope** `checkouts.write` - **Reconcile an uncertain domain operation**

Re-queues an uncertain domain operation for a read-only reconciliation of its saved remote intent and answers 202. The unknown write is not repeated. A job that is not uncertain is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Domain job id returned by the create call. |

**Response** `202`

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "request_id": "00000000-0000-4000-8000-000000000702",
    "shop_id": "00000000-0000-4000-8000-000000000201",
    "hostname": "shop.example.com",
    "action": "register",
    "status": "queued",
    "phase": "render",
    "total": 4,
    "move_pending": false,
    "result": null,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "errors": [],
    "skipped": 0,
    "effects": 0,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null
  }
}
```

**Errors**

- `400` `{"error":"Invalid request","details":{"issues":[{"path":"","code":"invalid_string","message":"Invalid uuid"}]}}` when :jobId is not a UUID (zod validation of the path parameter; the issue path is empty).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `404` `{"error":"Domain operation not found or permissions changed"}` when the job is unknown, another account's, or was created by another caller or under other permissions.
- `409` `{"error":"This job has no remote intent to reconcile"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Enable the domain worker to reconcile this saved intent"}`.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

**Gotchas**

- A non-UUID jobId answers 400 `Invalid request` with `details.issues` (the issue path is empty: it is the path parameter).

##### `POST /v1/checkouts/domain/jobs/:jobId/resume`

**Scope** `checkouts.write` - **Resume a paused service move**

Re-queues a service move that was stopped after a confirmed stage (status partial, move pending, no unresolved remote write), after checking that the store, service and ownership did not change.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Domain job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000701",
    "request_id": "00000000-0000-4000-8000-000000000702",
    "shop_id": "00000000-0000-4000-8000-000000000201",
    "hostname": "shop.example.com",
    "action": "move-service",
    "status": "queued",
    "phase": "render",
    "total": 4,
    "move_pending": true,
    "result": null,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "errors": [],
    "skipped": 0,
    "effects": 0,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "destination": "storefront"
  }
}
```

**Errors**

- `400` `{"error":"Invalid operation identity"}` when :jobId is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `404` `{"error":"Domain operation not found or permissions changed"}` when the job is unknown, another account's, or was created by another caller or under other permissions.
- `409` `Only a paused, fully reconciled move can resume` or `The hostname reservation changed; investigate before resuming`.
- `422` `Store, service or ownership changed. This move cannot resume.` and the move preconditions of the create call.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Service moves are unavailable"}` or `Service moves are disabled`.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 10-second budget.

##### `GET /v1/checkouts/domain/preview`

**Scope** `checkouts.read` - **Preview the DNS record a domain needs**

Tells what DNS record a store domain must carry to reach the checkout's Render service: an apex domain (two labels) needs an A record to Render's anycast IP, a subdomain needs a CNAME to the checkout service hostname (read from Render unless CHECKOUT_RENDER_SERVICE_HOSTNAME is set). No store needed, nothing written.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `domain` | string | **yes** | Trimmed, 3..253 chars. Hostname only. |

**Response**

```json
{
 "dnsRecordType": "CNAME",
 "dnsRecordValue": "checkout-web.onrender.com"
}
```

| response field | type | description |
|---|---|---|
| `dnsRecordType` | enum: A\|CNAME | A for apex (<= 2 labels, e.g. example.com), CNAME otherwise. |
| `dnsRecordValue` | string | The IP (216.24.57.1) or the Render service hostname. |

**Errors**

- `400` {"error":"domain required"}: missing, shorter than 3 or longer than 253 characters
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `502` {"error":"<message>"}: Render API failure, Render not configured, or the service hostname could not be resolved

**Gotchas**

- Label counting is naive: 'example.co.uk' counts as 3 labels and is treated as a subdomain (CNAME) although it is an apex - verify with your registrar.
- Nothing is registered by this call; use PUT /v1/checkouts/:shopId (domain) or POST .../domain/verify for that.

##### `POST /v1/checkouts/domain/reconcile-legacy`

**Scope** `checkouts.write` - **Reconcile a legacy domain write**

Read-only check of an unresolved write left by the older synchronous domain calls on this store's hostname: it reads the saved service or Cloudflare zone and, if the effect is proven, clears the reservation. It never repeats the write.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store id. |

**Request body**

```json
{
  "shopId": "00000000-0000-4000-8000-000000000201"
}
```

**Response**

```json
{
  "confirmed": false,
  "message": "The remote effect is still unconfirmed. The hostname remains reserved; no write was sent."
}
```

**Errors**

- `400` `{"error":"Choose a store"}` when shopId is missing or not a UUID, or the body has another field (strict).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"}` when the account's plan does not include the stores module.
- `403` `{"error":"Store access changed"}` when the store is not routed to this account; `Import API key or account access changed` when the key was revoked or its owner changed.
- `404` `{"error":"Store not found"}`.
- `409` `No unresolved legacy write is available to reconcile`; `The legacy request may still be running. Wait for its reservation to expire before reconciling.`; `Store or integration changed during reconciliation`; `The domain reservation changed during reconciliation`.
- `422` `Configure the account Cloudflare integration before reconciling this write` or `This legacy intent has no zone identity`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `A complete DNS inventory is unavailable` or `Background domains require the local checkout database`.
- `504` The 25-second read budget expired.

**Gotchas**

- confirmed false is a normal 200 answer: the hostname stays reserved; retry later.

#### Pixels and tracking

Account and store pixels (Meta, TikTok, Snapchat, Google), their server-side tokens and the pixel audit.

- Pixel audit: the Total row and the total Fired % are computed in the browser from `GET /v1/checkouts/pixels-audit`: Fired % = sum(fired_7d) / sum(approved_7d).

##### `GET /v1/checkouts/:shopId/google-ads`

**Scope** `checkouts.read` - **List a store's Google Ads tags**

The store's Google Ads conversion tags: per tag the conversion ID, the label of each browser event, the Google Ads customer and the Import from clicks conversion action the server uploads paid orders to, enhanced conversions, enabled. The caller's account's tags only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID of a store of the caller's account. Translated to Kontrol's own store row (by id, else by domain); a store not in Kontrol's database yet is 409. |

**Response**

```json
{
 "rows": [
  {
   "id": "0b6f3c1e-2d4a-4c8b-9e7f-1a2b3c4d5e6f",
   "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
   "product_id": null,
   "owner_email": "owner@example.com",
   "name": "Main account",
   "conversion_id": "AW-123456789",
   "labels": {
    "purchase": "AbC-D_efG-h12",
    "begin_checkout": "XyZ-0_beg"
   },
   "ads_customer_id": "1234567890",
   "purchase_action_id": "987654321",
   "enhanced": true,
   "enabled": true,
   "created_at": "2026-10-01T10:00:00.000Z",
   "created_by": "owner@example.com",
   "updated_at": "2026-10-01T10:00:00.000Z"
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | Store tag first, then product overrides, by conversion ID and name. |
| `rows[].id` | uuid | The tag. |
| `rows[].shop_id` | uuid | cocoapi's own store row (public.shops) - the dashboard's id translated; equal to it for every store created since the mirror carries primary keys. |
| `rows[].product_id` | uuid\|null | null = the store's tag. A product id = an OVERRIDE: for an order holding that product, its tag(s) replace the store's (the pixels' rule, per network). |
| `rows[].owner_email` | string | The account whose payment route serves the store at write time (checkout_routing.owner_email): the ONLY account whose Google Ads integration ever uploads for this tag. |
| `rows[].name` | string | 1..120, a label. |
| `rows[].conversion_id` | string | The Google tag's conversion ID, 'AW-' + digits (upper-cased). |
| `rows[].labels` | object | { purchase?, begin_checkout?, add_to_cart? } - the conversion label of each event for the BROWSER tag: gtag send_to = '<conversion_id>/<label>'. Unset events are absent. |
| `rows[].ads_customer_id` | string\|null | The Google Ads customer (10 digits, no dashes) that owns purchase_action_id - the uploadClickConversions customer. null = a browser-only tag. |
| `rows[].purchase_action_id` | string\|null | That customer's conversion action of type UPLOAD_CLICKS (" Import from clicks ") - the server upload target. Both or neither with ads_customer_id. |
| `rows[].enhanced` | boolean | Enhanced conversions: the sha256 of the normalised e-mail and E.164 phone ride each upload (never the values). |
| `rows[].enabled` | boolean | Off = no new upload is queued and queued ones are skipped. |
| `rows[].created_at / created_by / updated_at` | string | Timestamps; created_by = the operator e-mail. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); {"error":"No account"} (no account selected); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.
- `409` {"error":"This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync"}
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- No secret is ever returned: a tag holds none.
- What a tag drives: every approved sale of the store carrying a gclid, gbraid or wbraid click id is queued once per (order, tag) and uploaded to Google Ads by a background job with the account's Google Ads integration; credentials never live on the tag.

##### `POST /v1/checkouts/:shopId/google-ads`

**Scope** `checkouts.write` - **Add a Google Ads tag to a store**

Create a Google Ads tag for the store. Its owner is the caller's account, which must route the store (its payment route serves it): the only account whose Google Ads credentials will upload for it. 201 with the row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID of a store of the caller's account. Translated to Kontrol's own store row (by id, else by domain); a store not in Kontrol's database yet is 409. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters. |
| `conversion_id` | string | **yes** | AW- followed by 1 to 20 digits; trimmed and upper-cased (aw-123 is accepted). |
| `labels` | object | no | Strict object { purchase, begin_checkout, add_to_cart }: any other key is a 400. When sent it replaces the whole label set. |
| `labels.purchase` | string\|null | no | Conversion label of the purchase event for the browser tag: 1 to 64 letters, digits, - or _; "" or null = none. |
| `labels.begin_checkout` | string\|null | no | Same format, for begin_checkout. |
| `labels.add_to_cart` | string\|null | no | Same format, for add_to_cart. |
| `ads_customer_id` | string\|null | no | Google Ads customer ID: ten digits, dashes and spaces stripped (123-456-7890 accepted); "" or null = none. Both or neither with purchase_action_id. |
| `purchase_action_id` | string\|null | no | Numeric ID (1 to 20 digits) of that customer's UPLOAD_CLICKS conversion action (listed by POST /v1/integrations/google_ads/conversion-actions); "" or null = none. |
| `enhanced` | boolean; default `true` | no | Enhanced conversions (hashed e-mail and phone ride each upload). |
| `enabled` | boolean; default `true` | no | Off = no new upload is queued and queued ones are skipped. |
| `product_id` | uuid\|null | no | A product owned by or linked to this store (Kontrol's catalogue copy): an override whose tags replace the store tag for orders holding it. "" or null = the store tag. |

**Request body**

```json
{
 "name": "Main account",
 "conversion_id": "AW-123456789",
 "labels": {
  "purchase": "AbC-D_efG-h12",
  "begin_checkout": "XyZ-0_beg",
  "add_to_cart": ""
 },
 "ads_customer_id": "123-456-7890",
 "purchase_action_id": "987654321",
 "enhanced": true,
 "enabled": true,
 "product_id": null
}
```

**Response**

```json
{
 "id": "0b6f3c1e-2d4a-4c8b-9e7f-1a2b3c4d5e6f",
 "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
 "product_id": null,
 "owner_email": "owner@example.com",
 "name": "Main account",
 "conversion_id": "AW-123456789",
 "labels": {
  "purchase": "AbC-D_efG-h12",
  "begin_checkout": "XyZ-0_beg"
 },
 "ads_customer_id": "1234567890",
 "purchase_action_id": "987654321",
 "enhanced": true,
 "enabled": true,
 "created_at": "2026-10-01T10:00:00.000Z",
 "created_by": "owner@example.com",
 "updated_at": "2026-10-01T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | The google_ads_tags row (see GET). |

**Errors**

- `400` {"error":"invalid payload","details":...} for a bad or missing field or an unknown key; {"error":"invalid payload","details":{"fieldErrors":{"<field>":["<message>"]},"formErrors":[]}} for: name is required; conversion_id must be AW- followed by digits; the upload target needs both the customer ID and the conversion action ID (or neither); {"error":"product not in this store"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role, nothing written); {"error":"No account"}; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.
- `409` {"error":"This store has no payment route of your account: a Google Ads tag belongs to the account that routes the store"}; {"error":"This store already has a tag for this conversion ID (and product)"}; the store is not in Kontrol's own database yet
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- A tag without ads_customer_id and purchase_action_id is a browser tag only: its sales are queued as skipped.
- What a tag drives: every approved sale of the store carrying a gclid, gbraid or wbraid click id is queued once per (order, tag) and uploaded to Google Ads by a background job with the account's Google Ads integration; credentials never live on the tag.
- Enhanced conversions require the Google Ads account to have accepted the customer data terms, otherwise uploads retry with CUSTOMER_NOT_ACCEPTED_CUSTOMER_DATA_TERMS.

##### `PUT /v1/checkouts/:shopId/google-ads/:id`

**Scope** `checkouts.write` - **Edit a Google Ads tag**

Update one of the caller's tags of the store. The body is partial: only the keys it carries change (labels, when sent, replace the whole object). The upload target stays both-or-neither.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID of a store of the caller's account. Translated to Kontrol's own store row (by id, else by domain); a store not in Kontrol's database yet is 409. |
| `id` | uuid | **yes** | Tag ID (a non-UUID is 400 "bad id"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed, 1 to 120 characters. |
| `conversion_id` | string | no | AW- followed by 1 to 20 digits; trimmed and upper-cased (aw-123 is accepted). |
| `labels` | object | no | Strict object { purchase, begin_checkout, add_to_cart }: any other key is a 400. When sent it replaces the whole label set. |
| `labels.purchase` | string\|null | no | Conversion label of the purchase event for the browser tag: 1 to 64 letters, digits, - or _; "" or null = none. |
| `labels.begin_checkout` | string\|null | no | Same format, for begin_checkout. |
| `labels.add_to_cart` | string\|null | no | Same format, for add_to_cart. |
| `ads_customer_id` | string\|null | no | Google Ads customer ID: ten digits, dashes and spaces stripped (123-456-7890 accepted); "" or null = none. Both or neither with purchase_action_id. |
| `purchase_action_id` | string\|null | no | Numeric ID (1 to 20 digits) of that customer's UPLOAD_CLICKS conversion action (listed by POST /v1/integrations/google_ads/conversion-actions); "" or null = none. |
| `enhanced` | boolean | no | Enhanced conversions (hashed e-mail and phone ride each upload). Absent keeps the stored value. |
| `enabled` | boolean | no | Off = no new upload is queued and queued ones are skipped. Absent keeps the stored value. |
| `product_id` | uuid\|null | no | A product owned by or linked to this store (Kontrol's catalogue copy): an override whose tags replace the store tag for orders holding it. "" or null = the store tag. |

**Request body**

```json
{
 "enabled": false,
 "labels": {
  "purchase": "AbC-D_efG-h12"
 }
}
```

**Response**

```json
{
 "id": "0b6f3c1e-2d4a-4c8b-9e7f-1a2b3c4d5e6f",
 "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
 "product_id": null,
 "owner_email": "owner@example.com",
 "name": "Main account",
 "conversion_id": "AW-123456789",
 "labels": {
  "purchase": "AbC-D_efG-h12"
 },
 "ads_customer_id": "1234567890",
 "purchase_action_id": "987654321",
 "enhanced": true,
 "enabled": false,
 "created_at": "2026-10-01T10:00:00.000Z",
 "created_by": "owner@example.com",
 "updated_at": "2026-10-02T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | The updated google_ads_tags row. |

**Errors**

- `400` {"error":"bad id"}; {"error":"invalid payload","details":...}; {"error":"invalid payload","details":{"fieldErrors":{"<field>":["<message>"]},"formErrors":[]}} for: name is required; conversion_id must be AW- followed by digits; the upload target needs both the customer ID and the conversion action ID (or neither); {"error":"product not in this store"} (a changed product_id only)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required; {"error":"No account"}; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.; {"error":"Not found"}: unknown tag or another account's tag
- `409` {"error":"This store already has a tag for this conversion ID (and product)"}; the store is not in Kontrol's own database yet
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- Turning enabled off stops new uploads and skips the queued ones at their next pass.

##### `DELETE /v1/checkouts/:shopId/google-ads/:id`

**Scope** `checkouts.write` - **Delete a Google Ads tag**

Delete one of the caller's tags of the store, and with it (cascade) its upload queue rows; the send log keeps their journal for its retention.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID of a store of the caller's account. Translated to Kontrol's own store row (by id, else by domain); a store not in Kontrol's database yet is 409. |
| `id` | uuid | **yes** | Tag ID (a non-UUID is 400 "bad id"). |

**Response**

```json
{
 "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true. |

**Errors**

- `400` {"error":"bad id"}
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required; {"error":"No account"}; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.; {"error":"Not found"}: unknown tag or another account's tag
- `409` The store is not in Kontrol's own database yet
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- Conversions Google already recorded stay recorded: deleting a tag never retracts an upload.

##### `GET /v1/checkouts/:shopId/pixels`

**Scope** `tracking.read` - **List a store's pixels**

The store's pixels: store-level rows first (product_id null), then product overrides, by supplier and name; server tokens masked; product titles resolved for overrides. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Response**

```json
{
  "rows": [
    {
      "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Meta main",
      "supplier": "facebook",
      "pixel_front": "1234567890123",
      "pixel_back": "EAABsb...Zx2Q",
      "product_id": null,
      "created_at": "2026-07-01T10:00:00.000Z",
      "updated_at": "2026-07-01T10:00:00.000Z",
      "product_title": null
    },
    {
      "id": "2b3c4d5e-6f70-4a8b-9c0d-1e2f3a4b5c6d",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "TikTok PCP",
      "supplier": "tiktok",
      "pixel_front": "C9ABCDEFGHIJKLMNOP",
      "pixel_back": null,
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "created_at": "2026-07-01T10:00:00.000Z",
      "updated_at": "2026-07-01T10:00:00.000Z",
      "product_title": "Posture Corrector Pro"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].supplier` | string | tiktok, facebook, snapchat, google, pinterest, applovin or x. |
| `rows[].pixel_front` | string | Browser pixel id, in clear. |
| `rows[].pixel_back` | string\|null | Server token masked (first 6, ellipsis, last 4); null = none. |
| `rows[].google_ads / x_ads` | object\|null | Network configuration for google and x pixels. |
| `rows[].product_id / product_title` | uuid\|null / string\|null | Set on product overrides. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- The server token is masked here and the in-clear reveal route refuses API keys: keep your own copy.
- google, pinterest, applovin and x pixels are browser-only: they are kept in Kontrol's own database and never carry a server token.
- Account pixels (GET /v1/checkouts/pixels) also apply to the store and are not listed here.

##### `POST /v1/checkouts/:shopId/pixels`

**Scope** `tracking.write` - **Add a pixel to a store**

Add a pixel to the store (store-level or product override), then refresh the storefront pixel cache. Returns the row with the server token masked, 201.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters. Label only. |
| `supplier` | string | **yes** | One of tiktok, facebook, snapchat, google, pinterest, applovin, x. |
| `pixel_front` | string | **yes** | Trimmed, 1 to 255. Browser pixel id. google: AW- followed by 1 to 20 digits; pinterest: 1 to 30 digits; applovin: letters, digits, - and _; x: lower-case letters and digits. |
| `pixel_back` | string\|null | no | Optional server (CAPI) token for facebook, tiktok, snapchat; trimmed, max 2048; masked in every response. Forced to null for browser-only networks. "" or null = none. |
| `product_id` | uuid\|null | no | null = store-level pixel. A product id makes an override that replaces the store pixels of that network for carts containing the product. On create the product must be owned by this store (a product only linked to it is refused). |
| `google_ads` | object\|null | no | Required for supplier google: strict { labels: { purchase (required), begin_checkout, add_to_cart }, enhanced (default true) }; each label 1 to 64 letters, digits, - or _. |
| `google_ads.labels.purchase` | string | no | Required inside google_ads: the purchase conversion label, 1 to 64 letters, digits, - or _. |
| `google_ads.labels.begin_checkout` | string \| null | no | Optional begin_checkout conversion label, same format. |
| `google_ads.labels.add_to_cart` | string \| null | no | Optional add_to_cart conversion label, same format. |
| `google_ads.enhanced` | boolean | no | Enhanced conversions; default true. |
| `x_ads` | object\|null | no | Required for supplier x: strict { purchase (required), view_item, add_to_cart, begin_checkout, add_payment_info }, each tw-<pixel_front>-<event> from X Events Manager. |
| `x_ads.purchase` | string | no | Required inside x_ads: the purchase event ID (tw-<pixel_front>-<event>). |
| `x_ads.view_item` | string \| null | no | Optional event ID, same format. |
| `x_ads.add_to_cart` | string \| null | no | Optional event ID, same format. |
| `x_ads.begin_checkout` | string \| null | no | Optional event ID, same format. |
| `x_ads.add_payment_info` | string \| null | no | Optional event ID, same format. |

**Request body**

```json
{
 "name": "Meta main",
 "supplier": "facebook",
 "pixel_front": "1234567890123",
 "pixel_back": "EAAexample0000",
 "product_id": null
}
```

**Response**

```json
{
 "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
 "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
 "name": "Meta main",
 "supplier": "facebook",
 "pixel_front": "1234567890123",
 "pixel_back": "EAAexa...0000",
 "product_id": null,
 "created_at": "2026-07-01T10:00:00.000Z",
 "updated_at": "2026-07-01T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | pixels row: id, shop_id, name, supplier, pixel_front, pixel_back (masked), product_id, created_at, updated_at. |

**Errors**

- `400` {"error":"invalid payload","details":...}: missing or invalid field, unknown supplier; {"error":"product not in this checkout"}: product_id does not exist or belongs to another store; Google Ads requires an AW- conversion ID and a purchase conversion label; Enter a numeric Pinterest tag ID; Enter the Axon event key; Enter the X pixel ID and event IDs belonging to this pixel (tw-pixel-event)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.
- `409` {"error":"AppLovin requires one event key per store, including product overrides"}; This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync (browser-only networks only)
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- 201 on success.
- Several pixels of the same network are allowed and all fire; there is no uniqueness on (store, supplier).
- pixel_back is only masked on output: send the full token.
- google, pinterest, applovin and x pixels are browser-only: they are kept in Kontrol's own database and never carry a server token.
- The storefront cache refresh is best effort: if it fails, the storefront may serve the old pixels for a couple of minutes; the write itself is committed.

##### `PUT /v1/checkouts/:shopId/pixels/:id`

**Scope** `tracking.write` - **Update a pixel**

Partial update of one pixel of the store (every field optional). A masked pixel_back echoed back keeps the token; "" clears it. Refreshes the storefront pixel cache and returns the masked row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `id` | uuid | **yes** | Pixel ID; must belong to :shopId. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed, 1 to 120 characters. Label only. |
| `supplier` | string | no | One of tiktok, facebook, snapchat, google, pinterest, applovin, x. |
| `pixel_front` | string | no | Trimmed, 1 to 255. Browser pixel id. google: AW- followed by 1 to 20 digits; pinterest: 1 to 30 digits; applovin: letters, digits, - and _; x: lower-case letters and digits. |
| `pixel_back` | string\|null | no | Optional server (CAPI) token for facebook, tiktok, snapchat; trimmed, max 2048; masked in every response. Forced to null for browser-only networks. On update: a value containing the ellipsis character (the masked value echoed back) or null keeps the stored token; "" clears it. |
| `product_id` | uuid\|null | no | null = store-level pixel. A product id makes an override that replaces the store pixels of that network for carts containing the product. Not re-validated on update. |
| `google_ads` | object\|null | no | Required for supplier google: strict { labels: { purchase (required), begin_checkout, add_to_cart }, enhanced (default true) }; each label 1 to 64 letters, digits, - or _. |
| `google_ads.labels.purchase` | string | no | Required inside google_ads: the purchase conversion label, 1 to 64 letters, digits, - or _. |
| `google_ads.labels.begin_checkout` | string \| null | no | Optional begin_checkout conversion label, same format. |
| `google_ads.labels.add_to_cart` | string \| null | no | Optional add_to_cart conversion label, same format. |
| `google_ads.enhanced` | boolean | no | Enhanced conversions; default true. |
| `x_ads` | object\|null | no | Required for supplier x: strict { purchase (required), view_item, add_to_cart, begin_checkout, add_payment_info }, each tw-<pixel_front>-<event> from X Events Manager. |
| `x_ads.purchase` | string | no | Required inside x_ads: the purchase event ID (tw-<pixel_front>-<event>). |
| `x_ads.view_item` | string \| null | no | Optional event ID, same format. |
| `x_ads.add_to_cart` | string \| null | no | Optional event ID, same format. |
| `x_ads.begin_checkout` | string \| null | no | Optional event ID, same format. |
| `x_ads.add_payment_info` | string \| null | no | Optional event ID, same format. |

**Request body**

```json
{
 "name": "Meta main (renamed)",
 "pixel_back": "EAAexa...0000"
}
```

**Response**

```json
{
 "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
 "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
 "name": "Meta main (renamed)",
 "supplier": "facebook",
 "pixel_front": "1234567890123",
 "pixel_back": "EAAexa...0000",
 "product_id": null,
 "created_at": "2026-07-01T10:00:00.000Z",
 "updated_at": "2026-07-02T10:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `(row)` | object | Updated pixels row, pixel_back masked. |

**Errors**

- `400` {"error":"bad id"}: id is not a UUID; {"error":"invalid payload","details":...}; Google Ads requires an AW- conversion ID and a purchase conversion label; Enter a numeric Pinterest tag ID; Enter the Axon event key; Enter the X pixel ID and event IDs belonging to this pixel (tw-pixel-event) (checked against the merged row when supplier, pixel_front, google_ads or x_ads change)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.; {"error":"Not found"}: no pixel with that id on this store
- `409` {"error":"AppLovin requires one event key per store, including product overrides"}; This store is not in cocoapi's own database yet (<domain>) - save it once so the copy is created, then sync (browser-only networks only)
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- A pixel_back containing the ellipsis character is ignored (kept): that is how the masked value round-trips.
- product_id is not validated against the store on update (only on create).
- google, pinterest, applovin and x pixels are browser-only: they are kept in Kontrol's own database and never carry a server token.

##### `DELETE /v1/checkouts/:shopId/pixels/:id`

**Scope** `tracking.write` - **Delete a pixel**

Delete one pixel of the store and refresh the storefront pixel cache.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `id` | uuid | **yes** | Pixel ID; must belong to :shopId. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"bad id"}: id is not a UUID
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.; {"error":"Not found"}: no pixel with that id on this store
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- Deleting the last pixel of a network stops that network on the store (account pixels still apply).

##### `GET /v1/checkouts/:shopId/pixels/:id/secrets`

**Scope** `checkouts.write` - **Read a pixel's CAPI token (in clear)**

Reveal the stored server (CAPI) token of one pixel of the store in clear, "" when none. Every list masks it. An API key holding checkouts.write reads it too.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `shopId` | uuid | **yes** | Store ID (shops.id) of a store of the caller's account. A value that is not a UUID answers 500, not 404. |
| `id` | uuid | **yes** | Pixel ID of that store. |

**Response**

```json
{
 "pixel_back": "EAAexample0000"
}
```

| response field | type | description |
|---|---|---|
| `pixel_back` | string | The CAPI token in clear, "" when the pixel has none. |

**Errors**

- `400` {"error":"Invalid id"}: the pixel id is not a UUID.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.write"}: the key lacks checkouts.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Checkout not found"}: Checkout not found: unknown store, archived store, or a store of another account.; {"error":"Not found"}: no such pixel on this store.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- The answer carries a live secret: Cache-Control no-store and Pragma no-cache.
- A reveal that returns a value writes one view_secret audit row naming the field (never the value).
- An API key reads the values back here when it holds checkouts.write; a key that only holds the read scope gets 403.

##### `GET /v1/checkouts/pixels`

**Scope** `tracking.read` - **List every pixel of the caller's stores**

Every pixel of every store the caller sees, plus the account pixels of the caller's account, server tokens masked. The writes are the per-store routes and the account pixel routes.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Snap main",
      "supplier": "snapchat",
      "pixel_front": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
      "pixel_back": "snapTk...9f2a",
      "product_id": null,
      "created_at": "2026-10-05T10:00:00.000Z",
      "updated_at": "2026-10-05T10:00:00.000Z",
      "product_title": null
    },
    {
      "id": "2b3c4d5e-6f70-4a8b-9c0d-1e2f3a4b5c6d",
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Snap second account",
      "supplier": "snapchat",
      "pixel_front": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
      "pixel_back": null,
      "product_id": null,
      "created_at": "2026-10-05T10:05:00.000Z",
      "updated_at": "2026-10-05T10:05:00.000Z",
      "product_title": null
    },
    {
      "id": "3c4d5e6f-7081-4b9c-8d1e-2f3a4b5c6d7e",
      "shop_id": "7e2a1c0d-4b3f-4d6e-9a8b-1c2d3e4f5a6b",
      "name": "Meta PCP",
      "supplier": "facebook",
      "pixel_front": "1234567890123",
      "pixel_back": "EAABsb...Zx2Q",
      "product_id": "7d0a2c14-3b5e-4f61-9a8c-2e4b6d8f0a13",
      "created_at": "2026-07-01T10:00:00.000Z",
      "updated_at": "2026-07-01T10:00:00.000Z",
      "product_title": "Posture Corrector Pro"
    }
  ],
  "shops": [
    {
      "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Brand US",
      "domain": "shop.example.com"
    },
    {
      "id": "7e2a1c0d-4b3f-4d6e-9a8b-1c2d3e4f5a6b",
      "name": "Brand FR",
      "domain": "shop.example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | Store pixels: id, shop_id, name, supplier (tiktok, facebook, snapchat, google, pinterest, applovin, x), pixel_front, pixel_back (masked; null = none), google_ads, x_ads, product_id / product_title (override), created_at, updated_at. Then account pixels (shop_id "", product_id null, owner_email, supplier may also be whop). |
| `shops[]` | object[] | { id, name (internal name), domain } of the visible stores; a store with no pixel is listed too. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- No count limit: several pixels per store and per network.
- A caller without an account gets {"rows":[],"shops":[]}.
- Account pixels have shop_id "" and product_id null and carry owner_email; store pixels carry the store id.
- The server token is never in clear here; the reveal routes (GET /v1/checkouts/:shopId/pixels/:id/secrets and GET /v1/checkouts/pixels/:id/secrets) refuse API keys.

##### `POST /v1/checkouts/pixels`

**Scope** `tracking.write` - **Add an account pixel**

Add an account pixel. Account pixels apply to every store routed to the caller's account, beside the store and product pixels. Networks: facebook, tiktok, snapchat (browser id plus optional server token), google (AW- conversion ID plus google_ads labels), pinterest (numeric tag ID), applovin (Axon event key), x (pixel ID plus x_ads event IDs) and whop (the existing platform connection, no id). The storefront caches of every store of the account are refreshed.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters. Label only. |
| `supplier` | string | **yes** | One of tiktok, facebook, snapchat, google, pinterest, applovin, x, whop. |
| `pixel_front` | string | no | Trimmed, max 255, default "". Required for every network but whop. google: AW- followed by 1 to 20 digits; pinterest: 1 to 30 digits; applovin: letters, digits, - and _ (1 to 255); x: lower-case letters and digits. |
| `pixel_back` | string\|null | no | Optional server (CAPI) token, trimmed, max 2048. Responses mask it (first 6 characters, an ellipsis, last 4). Always stored as null for whop. "" or null = none. |
| `google_ads` | object\|null | no | Required when supplier is google, ignored otherwise. Strict object: labels (required) and enhanced. |
| `google_ads.labels.purchase` | string | no | Required inside google_ads: the purchase conversion label, 1 to 64 letters, digits, - or _. |
| `google_ads.labels.begin_checkout` | string\|null | no | Optional begin_checkout conversion label, same format. |
| `google_ads.labels.add_to_cart` | string\|null | no | Optional add_to_cart conversion label, same format. |
| `google_ads.enhanced` | boolean; default `true` | no | Enhanced conversions. |
| `x_ads` | object\|null | no | Required when supplier is x, ignored otherwise. Strict object of X event IDs, each tw-<pixel_front>-<event> copied from X Events Manager. |
| `x_ads.purchase` | string | no | Required inside x_ads: the purchase event ID (tw-<pixel>-<event>). |
| `x_ads.view_item` | string\|null | no | Optional event ID, same format. |
| `x_ads.add_to_cart` | string\|null | no | Optional event ID, same format. |
| `x_ads.begin_checkout` | string\|null | no | Optional event ID, same format. |
| `x_ads.add_payment_info` | string\|null | no | Optional event ID, same format. |
| `product_id` | any | no | Accepted and ignored: an account pixel applies to every store of the account (the dashboard sends null). Unknown keys are dropped, never refused. For a product-level pixel, use a store pixel (POST /v1/checkouts/:shopId/pixels with product_id). |

**Request body**

```json
{
 "name": "Meta main",
 "supplier": "facebook",
 "pixel_front": "1234567890123",
 "pixel_back": "EAAexample0000"
}
```

**Response**

```json
{
 "pixel": {
  "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
  "owner_email": "owner@example.com",
  "name": "Meta main",
  "supplier": "facebook",
  "pixel_front": "1234567890123",
  "pixel_back": "EAAexa...0000",
  "google_ads": null,
  "x_ads": null,
  "created_at": "2026-10-01T10:00:00.000Z",
  "updated_at": "2026-10-01T10:00:00.000Z",
  "shop_id": "",
  "product_id": null
 }
}
```

**Errors**

- `400` {"error":"Invalid pixel","details":...}: validation messages in details: Pixel id required; Google Ads requires an AW- conversion ID and a purchase conversion label; Enter a numeric Pinterest tag ID; Enter the Axon event key; Enter the X pixel ID and event IDs belonging to this pixel (tw-pixel-event).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); No account (no account selected); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `409` {"error":"AppLovin requires one event key per account; use a store override for another key"}: another account AppLovin pixel already uses a different key.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Answers 200 (not 201) with { pixel }. Account pixels have shop_id "" and product_id null.
- The server token is only masked on output: send the full token.
- The in-clear token is read with GET /v1/checkouts/pixels/:id/secrets, which refuses API keys.

##### `GET /v1/checkouts/pixels-audit`

**Scope** `tracking.read` - **Audit pixels configuration vs firing**

Per visible store: what is configured per ad network (store pixels, product overrides, account pixels applied to the store, rows missing a server token) and what actually fired in the last 7 days (pixel_purchase_fired events, approved orders, fire ratio, last fire, SDK-blocked events). One row per visible store, even without pixels. Read-only.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "shop_id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "networks": [
        {
          "network": "facebook",
          "shop_pixels": 1,
          "product_pixels": 1,
          "missing_capi": 0
        },
        {
          "network": "tiktok",
          "shop_pixels": 1,
          "product_pixels": 0,
          "missing_capi": 1
        }
      ],
      "total": 3,
      "missing_capi": 1,
      "fired_24h": 14,
      "fired_7d": 118,
      "approved_7d": 121,
      "fired_pct_7d": 98,
      "last_fired_at": "2026-09-19T09:14:05.300Z",
      "sdk_blocked_7d": 4
    }
  ],
  "shops": [
    {
      "id": "5b1f0d2e-9c3a-4e7b-8a21-3f6d9c0e7a11",
      "name": "Brand US",
      "domain": "shop.example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[].networks[]` | object[] | { network (supplier: facebook, tiktok, snapchat, google, pinterest, applovin, x, whop), shop_pixels (rows without product), product_pixels (overrides), missing_capi }. |
| `rows[].total / missing_capi` | integer | Totals across networks (account pixels applied to the store included). |
| `rows[].fired_24h / fired_7d` | integer | pixel_purchase_fired events in the last 24 h / 7 days. |
| `rows[].approved_7d` | integer | Approved checkout orders in the last 7 days. |
| `rows[].fired_pct_7d` | integer\|null | fired_7d / approved_7d x 100, rounded; null without approvals. |
| `rows[].last_fired_at` | string\|null | Newest pixel_purchase_fired event in the window. |
| `rows[].sdk_blocked_7d` | integer | Fire events whose metadata reports fbq and ttq absent and none of snaptr, gtag, pintrk, axon or twq present (ad blocker or webview without SDKs). |
| `shops[]` | object[] | { id, name, domain } of the visible stores. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- A product-scoped pixel replaces the store pixels of that network for carts containing the product.
- missing_capi only counts networks that use a server token (facebook, tiktok): snapchat, google, pinterest, applovin, x and whop rows never count as missing.
- fired_pct_7d can exceed 100 (several fires per order): it is a health signal, not a conversion rate.
- Windows are fixed (24 h and 7 d back from now); there is no from/to. At most 10 000 fire events and 20 000 approved orders are read.

##### `PUT /v1/checkouts/pixels/:id`

**Scope** `tracking.write` - **Update an account pixel**

Replace an account pixel (the whole body is required, not a partial patch). Account pixels apply to every store routed to the caller's account, beside the store and product pixels. Networks: facebook, tiktok, snapchat (browser id plus optional server token), google (AW- conversion ID plus google_ads labels), pinterest (numeric tag ID), applovin (Axon event key), x (pixel ID plus x_ads event IDs) and whop (the existing platform connection, no id).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account pixel ID. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters. Label only. |
| `supplier` | string | **yes** | One of tiktok, facebook, snapchat, google, pinterest, applovin, x, whop. |
| `pixel_front` | string | no | Trimmed, max 255, default "". Required for every network but whop. google: AW- followed by 1 to 20 digits; pinterest: 1 to 30 digits; applovin: letters, digits, - and _ (1 to 255); x: lower-case letters and digits. |
| `pixel_back` | string\|null | no | Optional server (CAPI) token, trimmed, max 2048. Responses mask it (first 6 characters, an ellipsis, last 4). Always stored as null for whop. On update: absent, or a value containing the ellipsis character (the masked value echoed back), keeps the stored token when the supplier is unchanged (a supplier change drops it); "" or null clears it. |
| `google_ads` | object\|null | no | Required when supplier is google, ignored otherwise. Strict object: labels (required) and enhanced. |
| `google_ads.labels.purchase` | string | no | Required inside google_ads: the purchase conversion label, 1 to 64 letters, digits, - or _. |
| `google_ads.labels.begin_checkout` | string\|null | no | Optional begin_checkout conversion label, same format. |
| `google_ads.labels.add_to_cart` | string\|null | no | Optional add_to_cart conversion label, same format. |
| `google_ads.enhanced` | boolean; default `true` | no | Enhanced conversions. |
| `x_ads` | object\|null | no | Required when supplier is x, ignored otherwise. Strict object of X event IDs, each tw-<pixel_front>-<event> copied from X Events Manager. |
| `x_ads.purchase` | string | no | Required inside x_ads: the purchase event ID (tw-<pixel>-<event>). |
| `x_ads.view_item` | string\|null | no | Optional event ID, same format. |
| `x_ads.add_to_cart` | string\|null | no | Optional event ID, same format. |
| `x_ads.begin_checkout` | string\|null | no | Optional event ID, same format. |
| `x_ads.add_payment_info` | string\|null | no | Optional event ID, same format. |
| `product_id` | any | no | Accepted and ignored: an account pixel applies to every store of the account (the dashboard sends null). Unknown keys are dropped, never refused. For a product-level pixel, use a store pixel (POST /v1/checkouts/:shopId/pixels with product_id). |

**Request body**

```json
{
 "name": "Meta main (renamed)",
 "supplier": "facebook",
 "pixel_front": "1234567890123",
 "pixel_back": "EAAexa...0000"
}
```

**Response**

```json
{
 "pixel": {
  "id": "9a1b2c3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d",
  "owner_email": "owner@example.com",
  "name": "Meta main",
  "supplier": "facebook",
  "pixel_front": "1234567890123",
  "pixel_back": "EAAexa...0000",
  "google_ads": null,
  "x_ads": null,
  "created_at": "2026-10-01T10:00:00.000Z",
  "updated_at": "2026-10-01T10:00:00.000Z",
  "shop_id": "",
  "product_id": null
 }
}
```

**Errors**

- `400` {"error":"Invalid pixel"} (no details): id is not a UUID or the body fails the same validation as the create.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required (a read-only member role); No account; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Not found"}: no pixel with that id in the caller's account.
- `409` {"error":"AppLovin requires one event key per account; use a store override for another key"}: another account AppLovin pixel already uses a different key.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- name and supplier are required on every update.
- Echo the masked pixel_back (or omit it) to keep the stored token; "" or null clears it.

##### `DELETE /v1/checkouts/pixels/:id`

**Scope** `tracking.write` - **Delete an account pixel**

Delete an account pixel; the storefront caches of the account's stores are refreshed.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account pixel ID. |

**Response**

```json
{
 "ok": true
}
```

**Errors**

- `400` {"error":"Invalid pixel"}: id is not a UUID.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required; No account; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `404` {"error":"Not found"}: no pixel with that id in the caller's account.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- Deleting the last pixel of a network stops that network on every store that relied on the account pixel.

##### `GET /v1/checkouts/pixels/:id/secrets`

**Scope** `tracking.write` - **Read an account pixel token (in clear)**

Reveal the stored server (CAPI) token of one account pixel in clear, "" when none. Every list masks it. An API key holding tracking.write reads it too.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Account pixel ID. |

**Response**

```json
{
 "pixel_back": "EAAexample0000"
}
```

**Errors**

- `400` {"error":"Invalid pixel"}: id is not a UUID.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Admin role required for a read-only member role; Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"tracking.write"}: the key lacks tracking.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Not found"}: no such pixel in the caller's account.
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The answer carries a live secret: Cache-Control no-store and Pragma no-cache.
- A reveal that returns a value writes one view_secret audit row naming the field (never the value).
- An API key reads the values back here when it holds tracking.write; a key that only holds the read scope gets 403.

#### Discounts

Discount codes and what they can target.

- The export holds only the page on screen of `GET /v1/discounts`; page through the list for a complete file.

##### `GET /v1/discounts`

**Scope** `checkouts.read` - **List discount codes**

Ecommerce -> Discounts: one page of the account's discount codes (migration 188), with the total of the whole list, each row with its target's name and its redemption counts (applied, reservations still holding a place, released). Server-sorted and server-paged.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string <= 120 | no | Contains, on the code or the note (case-insensitive; % and _ are literal). |
| `active` | true \| false | no | Only the codes switched on / off. |
| `archived` | false \| true \| all; default `false` | no | false = not archived; true = only the archived ones; all = both. |
| `scope` | CSV of account \| checkout \| shop (<= 60 chars) | no | The scopes to keep. |
| `checkoutId` | uuid | no | Only the codes of this checkout. |
| `shopId` | uuid | no | Only the codes of this store. |
| `sort` | code \| scope \| target \| value \| min_subtotal \| starts_at \| ends_at \| max_redemptions \| max_per_customer \| redemptions \| active \| created_at \| updated_at; default `created_at` | no | Sort column. An unknown key is a 400 {"error":"unknown sort \"<key>\"","sortKeys":[...]}; value sorts by kind, then by its value. Ties: created_at desc, then id. Omitted = created_at. |
| `dir` | asc \| desc; default `desc` | no | Sort direction (nulls last). |
| `offset` | integer 0..10000000; default `0` | no | Rows to skip. |
| `limit` | integer 1..10000; default `50` | no | Page size. |

**Response**

```json
{
  "rows": [
    {
      "id": "7c2f0a51-3d1e-4b8a-9f00-1a2b3c4d5e6f",
      "owner_email": "ops@example.com",
      "scope": "checkout",
      "checkout_id": "11111111-1111-4111-8111-111111111111",
      "shop_id": null,
      "code": "SAVE10",
      "kind": "percent",
      "percent_bp": 1000,
      "amount_cents": null,
      "currency": null,
      "min_subtotal_cents": 2000,
      "starts_at": "2026-10-05T00:00:00.000Z",
      "ends_at": null,
      "max_redemptions": 500,
      "max_per_customer": 1,
      "active": true,
      "archived_at": null,
      "note": "October launch",
      "created_at": "2026-10-05T09:00:00.000Z",
      "created_by": "ops@example.com",
      "updated_at": "2026-10-05T09:00:00.000Z",
      "checkout_name": "Main checkout",
      "shop_name": null,
      "shop_domain": null,
      "applied_count": 42,
      "reserved_count": 1,
      "released_count": 3
    }
  ],
  "total": 1,
  "offset": 0,
  "limit": 50
}
```

| response field | type | description |
|---|---|---|
| `rows[].applied_count` | integer | Redemptions confirmed on an approved charge. |
| `rows[].reserved_count` | integer | Reservations younger than 30 minutes (they hold a place against the limits). |
| `total` | integer | Every code matching the filters (all pages). |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): an unknown query parameter (the query is strict), limit outside 1..10000, an unknown scope ("unknown scope \"x\""), a bad uuid, q over 120 characters. {"error":"unknown sort \"x\"","sortKeys":[...]} for an unknown sort key.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.read"} when the key's scopes lack checkouts.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

##### `POST /v1/discounts`

**Scope** `checkouts.write` - **Add a discount code**

Adds a code. The cross-field rules are named in the answer: the scope names its target and only it, a percent code carries basis points and nothing else, a fixed code an amount (USD by default), a window that starts before it ends. The code belongs to its target's account (a checkout's, a store's route owner), else to the caller's.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `code` | string | **yes** | Letters, digits, - and _, starting with a letter or a digit, <= 64, no space. Stored as typed; unique per (account, scope, target) ignoring case, among the codes not archived. |
| `kind` | enum: percent \| fixed | **yes** | percent = percentBp; fixed = amountCents (+ currency). |
| `percentBp` | integer 1..10000 | no | Percent codes: basis points (1500 = 15 %). Refused on a fixed code. |
| `amountCents` | integer >= 1 | no | Fixed codes: the amount off, in cents. Refused on a percent code. |
| `currency` | string (3 letters); default `USD` | no | Fixed codes only; upper-cased. |
| `scope` | enum: account \| checkout \| shop; default `account` | no | account = every checkout of the account; checkout = checkoutId; shop = shopId (a store the account routes - GET /v1/discounts/targets). |
| `checkoutId` | uuid \| null | no | The checkout of a checkout code: one of the account's checkouts (GET /v1/discounts/targets). Required with scope checkout, refused otherwise. |
| `shopId` | uuid \| null | no | The store of a store code: a local store id the account routes (GET /v1/discounts/targets). Required with scope shop, refused otherwise. |
| `minSubtotalCents` | integer >= 0 \| null | no | The cart subtotal below which the code does not apply (checked by the storefront's validation, before the reservation). |
| `startsAt` | ISO instant \| null | no | Not valid before. |
| `endsAt` | ISO instant \| null | no | Not valid from this instant; must come after startsAt. |
| `maxRedemptions` | integer >= 1 \| null | no | Total uses: applied + reservations younger than 30 minutes. |
| `maxPerCustomer` | integer >= 1 \| null | no | Uses per customer (sha256 of the lower-cased e-mail). |
| `active` | boolean; default `true` | no | Off = refused at checkout (inactive). |
| `note` | string <= 500 \| null | no | For the team; never shown to a customer. |

**Request body**

```json
{
  "code": "SAVE10",
  "kind": "percent",
  "percentBp": 1000,
  "scope": "checkout",
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "minSubtotalCents": 2000,
  "maxRedemptions": 500,
  "maxPerCustomer": 1,
  "note": "October launch"
}
```

**Response** `201`

```json
{
  "discount": {
    "id": "7c2f0a51-3d1e-4b8a-9f00-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "scope": "checkout",
    "checkout_id": "11111111-1111-4111-8111-111111111111",
    "shop_id": null,
    "code": "SAVE10",
    "kind": "percent",
    "percent_bp": 1000,
    "amount_cents": null,
    "currency": null,
    "min_subtotal_cents": 2000,
    "starts_at": "2026-10-05T00:00:00.000Z",
    "ends_at": null,
    "max_redemptions": 500,
    "max_per_customer": 1,
    "active": true,
    "archived_at": null,
    "note": "October launch",
    "created_at": "2026-10-05T09:00:00.000Z",
    "created_by": "ops@example.com",
    "updated_at": "2026-10-05T09:00:00.000Z",
    "checkout_name": "Main checkout",
    "shop_name": null,
    "shop_domain": null,
    "applied_count": 42,
    "reserved_count": 1,
    "released_count": 3
  }
}
```

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): an unknown key (the body is strict), code or kind missing, a bad code, a value out of range or of the wrong type. A cross-field rule answers {"error":"<field>: <message>","details":{"fieldErrors":{"<field>":["<message>"]}}}, for example "percentBp: a percent code needs its percentage", "checkoutId: a checkout code needs its checkout", "endsAt: the end must come after the start".
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.write"} when the key's scopes lack checkouts.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin ({"error":"Admin role required"} is the handler's own refusal for the same case).
- `409` {"error":"A code with these letters already exists for this scope (codes ignore upper / lower case)"}
- `422` {"error":"Unknown checkout"} (field checkoutId), {"error":"Unknown store (a code can target a store of the account that routes it)"} (field shopId), or {"error":"No account on this session"} (field scope), with details.fieldErrors.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- A code's REDEMPTIONS are the storefront's: reserve_discount_redemption(code_id, order_ref, customer_key, amount_cents, currency) before the charge, confirm_discount_redemption(id, transaction_id) on approval, release_discount_redemption(id) on decline (migration 188 - atomic under the code's row lock; the reserve raises P0001 with the typed reason as its message: not_found · inactive · not_started · expired · exhausted · customer_limit). Nothing here moves one.
- Several codes may share their letters across scopes: the storefront applies the most specific (shop, then checkout, then account).
- Answers 201 with {"discount": <row>} (the same row shape as the list, with zero redemption counts).

##### `GET /v1/discounts/:id`

**Scope** `checkouts.read` - **One discount code**

The code with its redemption counts by status and its latest redemption.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The row id. |

**Response**

```json
{
  "discount": {
    "id": "7c2f0a51-3d1e-4b8a-9f00-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "scope": "checkout",
    "checkout_id": "11111111-1111-4111-8111-111111111111",
    "shop_id": null,
    "code": "SAVE10",
    "kind": "percent",
    "percent_bp": 1000,
    "amount_cents": null,
    "currency": null,
    "min_subtotal_cents": 2000,
    "starts_at": "2026-10-05T00:00:00.000Z",
    "ends_at": null,
    "max_redemptions": 500,
    "max_per_customer": 1,
    "active": true,
    "archived_at": null,
    "note": "October launch",
    "created_at": "2026-10-05T09:00:00.000Z",
    "created_by": "ops@example.com",
    "updated_at": "2026-10-05T09:00:00.000Z",
    "checkout_name": "Main checkout",
    "shop_name": null,
    "shop_domain": null,
    "applied_count": 42,
    "reserved_count": 1,
    "released_count": 3
  },
  "redemptions": {
    "reserved": 1,
    "live_reserved": 1,
    "applied": 42,
    "released": 3,
    "total": 46
  },
  "lastRedemption": {
    "id": "9d8c7b6a-0000-4000-8000-000000000001",
    "status": "applied",
    "order_ref": "b1c2d3e4-...",
    "amount_cents": 600,
    "currency": "USD",
    "transaction_id": "...",
    "at": "2026-10-05T10:12:00.000Z"
  }
}
```

**Errors**

- `400` {"error":"Invalid"}: :id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.read"} when the key's scopes lack checkouts.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role.
- `404` {"error":"Not found"}: no such code in the caller's account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

##### `PATCH /v1/discounts/:id`

**Scope** `checkouts.write` - **Edit a discount code**

Any subset of the body of POST, laid over the stored code and validated whole. Changing the kind drops the other kind's value, changing the scope drops the other target (unless the body sets them). A code never moves to another account; an archived code is read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The row id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `code` | string | no | Letters, digits, - and _, starting with a letter or a digit, <= 64, no space. Stored as typed; unique per (account, scope, target) ignoring case, among the codes not archived. |
| `kind` | enum: percent \| fixed | no | percent = percentBp; fixed = amountCents (+ currency). |
| `percentBp` | integer 1..10000 | no | Percent codes: basis points (1500 = 15 %). Refused on a fixed code. |
| `amountCents` | integer >= 1 | no | Fixed codes: the amount off, in cents. Refused on a percent code. |
| `currency` | string (3 letters) | no | Fixed codes only; upper-cased. Omitted = unchanged. |
| `scope` | enum: account \| checkout \| shop | no | account = every checkout of the account; checkout = checkoutId; shop = shopId (a store the account routes - GET /v1/discounts/targets). Omitted = unchanged. |
| `checkoutId` | uuid \| null | no | The checkout of a checkout code (one of the account's; a super_admin may name another account's - the code is then THAT account's). |
| `shopId` | uuid \| null | no | The store of a shop code: a local shops.id the account routes. |
| `minSubtotalCents` | integer >= 0 \| null | no | The cart subtotal below which the code does not apply (checked by the storefront's validation, before the reservation). |
| `startsAt` | ISO instant \| null | no | Not valid before. |
| `endsAt` | ISO instant \| null | no | Not valid from this instant; must come after startsAt. |
| `maxRedemptions` | integer >= 1 \| null | no | Total uses: applied + reservations younger than 30 minutes. |
| `maxPerCustomer` | integer >= 1 \| null | no | Uses per customer (sha256 of the lower-cased e-mail). |
| `active` | boolean | no | Off = refused at checkout (inactive). Omitted = unchanged. |
| `note` | string <= 500 \| null | no | For the team; never shown to a customer. |

**Request body**

```json
{
  "active": false
}
```

**Response**

```json
{
  "discount": {
    "id": "7c2f0a51-3d1e-4b8a-9f00-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "scope": "checkout",
    "checkout_id": "11111111-1111-4111-8111-111111111111",
    "shop_id": null,
    "code": "SAVE10",
    "kind": "percent",
    "percent_bp": 1000,
    "amount_cents": null,
    "currency": null,
    "min_subtotal_cents": 2000,
    "starts_at": "2026-10-05T00:00:00.000Z",
    "ends_at": null,
    "max_redemptions": 500,
    "max_per_customer": 1,
    "active": false,
    "archived_at": null,
    "note": "October launch",
    "created_at": "2026-10-05T09:00:00.000Z",
    "created_by": "ops@example.com",
    "updated_at": "2026-10-05T09:00:00.000Z",
    "checkout_name": "Main checkout",
    "shop_name": null,
    "shop_domain": null,
    "applied_count": 42,
    "reserved_count": 1,
    "released_count": 3
  }
}
```

**Errors**

- `400` {"error":"Invalid","details":{...}}: :id is not a uuid or the body fails the schema (strict: an unknown key is refused); {"error":"<field>: <message>","details":{"fieldErrors":{...}}} for a cross-field rule on the merged code.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.write"} when the key's scopes lack checkouts.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin ({"error":"Admin role required"} is the handler's own refusal for the same case).
- `404` {"error":"Not found"}: no such code in the caller's account.
- `409` {"error":"This code is archived (it has redemptions): it can no longer be edited"}, or {"error":"A code with these letters already exists for this scope (codes ignore upper / lower case)"}.
- `422` {"error":"Unknown checkout"} / {"error":"Unknown store (a code can target a store of the account that routes it)"} for a new target, or {"error":"That target belongs to another account"}.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers {"discount": <row>}.

##### `DELETE /v1/discounts/:id`

**Scope** `checkouts.write` - **Delete (or archive) a discount code**

Deletes a code nothing ever redeemed. A code with redemptions is ARCHIVED instead - switched off for good (active false, archived_at), kept with its history - and the answer says so. One transaction under the code's row lock (the reservation's own lock).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The row id. |

**Response**

```json
{
  "ok": true,
  "deleted": false,
  "archived": true,
  "redemptions": 3,
  "message": "The code has 3 redemptions: it was archived (switched off for good), not deleted"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |
| `deleted` | boolean | true = the code had no redemption and is gone. |
| `archived` | boolean | true = the code had redemptions: it is switched off for good and kept (read-only) with its history. |
| `redemptions` | integer | Only when archived: how many redemptions (any status) the code has. |
| `message` | string | Only when archived: the sentence to show. |

**Errors**

- `400` {"error":"Invalid"}: :id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.write"} when the key's scopes lack checkouts.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for a member whose role is not admin ({"error":"Admin role required"} is the handler's own refusal for the same case).
- `404` {"error":"Not found"}: no such code in the caller's account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Deleting a code with any redemption (reserved, applied or released) archives it instead: check deleted / archived in the answer.
- An archived code cannot be edited (PATCH answers 409) and is hidden from the default list (archived=false).

##### `GET /v1/discounts/targets`

**Scope** `checkouts.read` - **What a discount code can target**

The account's checkouts and the stores it routes (local store ids - the ones the storefront renders and matches a shop code against): the Discounts modal's pickers.

*No parameters.*

**Response**

```json
{
  "checkouts": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "name": "Main checkout",
      "active": true,
      "owner_email": "ops@example.com"
    }
  ],
  "shops": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "name": "Example store",
      "domain": "shop.example.com",
      "owner_email": "ops@example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `checkouts[]` | object[] | The account's checkouts: {id, name, active, owner_email}. The id is a checkoutId for a checkout code. |
| `shops[]` | object[] | The stores the account routes: {id, name, domain, owner_email}. The id (local store id) is a shopId for a store code. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"checkouts.read"} when the key's scopes lack checkouts.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"stores"} when the account's plan lacks the stores module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- No parameters; the lists are not paged.

#### Cart recovery

Abandoned-cart recovery: sending settings, templates, store bindings, the carts and the sends, and the hand-off of a cart from your own checkout.

- Recovery reach is resolved in the browser from `GET /v1/recovery/bindings` and `GET /v1/recovery/profiles`: the profile the store's binding names for the channel, else the channel's default profile when the store has a binding for that channel; its `test_mode_pct` is the reach. Without either, the store's own settings apply. No endpoint returns a store's effective configuration.

##### `GET /v1/recovery/bindings`

**Scope** `recovery.read` - **List what each store picked**

One row per store and channel that has been bound: its switch override, its sending settings and its pinned template. A store absent from this list is unbound and uses its own settings.

*No parameters.*

**Response**

```json
{"rows": []}
```

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Everything here is an OVERLAY and every part of it is optional. A store with no binding, or a binding whose fields are null, reads exactly the settings it read before - which is what makes this safe against live stores: nothing changes until a store is bound on purpose.

##### `PUT /v1/recovery/bindings`

**Scope** `recovery.write` - **Set what one store picks**

Writes one store's choice for one channel: the switch, the sending settings and the template. The WHOLE row is taken, not a patch - a field sent as null is cleared, which is how an operator undoes a pin.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `shop_id` | string | **yes** | The store, as the checkout knows it. |
| `channel` | enum: sms\|email | **yes** | Which channel this choice applies to. |
| `enabled` | boolean\|null | no | null = the store's own switch decides. true / false OVERRIDE it, which is how a channel is turned off for one store without opening the checkout admin. |
| `profile_id` | uuid\|null | no | The sending settings to obey. null with a binding present = the channel's default profile; no binding at all = the store's own columns. |
| `template_id` | uuid\|null | no | Pin the template this store sends. null = let the ladder choose. |

**Request body**

```json
{
  "shop_id": "5b2e8d1c-7f4a-4c3e-9a6b-1d0f3e8c2a57",
  "channel": "email",
  "enabled": true,
  "profile_id": "1e4c7a9b-3d2f-4b6e-8a5c-0f9d2b4e6a18",
  "template_id": null
}
```

**Response**

```json
{"ok": true}
```

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused). {"error":"Sending settings do not belong to this account and channel"}; {"error":"Template does not belong to this account, store and channel"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Store not found"} when shop_id is not a store routed to the account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Everything here is an OVERLAY and every part of it is optional. A store with no binding, or a binding whose fields are null, reads exactly the settings it read before - which is what makes this safe against live stores: nothing changes until a store is bound on purpose.
- A pin that names a template which is deleted or switched off is IGNORED and the ladder runs as if nothing was pinned - a store must not stop relancing because a template was removed.
- The store must belong to the caller account. The profile and template must match the account and channel; a store-specific template must match this store.
- A binding with profile_id:null uses the channel default profile, when present, otherwise the store own settings. No binding retains original store settings.

##### `GET /v1/recovery/carts`

**Scope** `recovery.read` - **List recovery carts**

Paginated list of the account's abandoned carts pushed by the checkout, newest activity first, with status, channel states, contact (email / phone), subtotal and attribution. The heavy JSON columns (policy, links, cart items) are omitted here - fetch one cart for them.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `status` | string | no | Exact match on cart status: pending \| done \| recovered \| frozen. Not validated - an unknown value simply matches nothing. |
| `shop_id` | string | no | Exact match on the checkout shop id. |
| `search` | string | no | Contains-match (first 120 chars kept) on cart_token, email or phone_e164. |
| `limit` | integer; default `50` | no | Max 10000. Non-numeric or 0 -> 50. |
| `offset` | integer; default `0` | no | Max 1000000; negative/non-numeric -> 0. |

**Response**

```json
{
  "rows": [
    {
      "owner_email": "merchant@example.com",
      "cart_token": "c9f1e2d3a4b5f6a7",
      "api_key_id": "2b7d1a3e-9f40-4c6b-8e12-0a5d3c9b7f21",
      "shop_id": "shop_3f2a91c4",
      "shop": {
        "id": "shop_3f2a91c4",
        "name": "Acme Store",
        "domain": "example.com",
        "logo_url": "https://example.com/logo.png",
        "primary_color": "#111111"
      },
      "customer": {
        "email": "jane.doe@example.com",
        "phone_e164": "+12345550100",
        "first_name": "Jane",
        "language": "en"
      },
      "email": "jane.doe@example.com",
      "phone_e164": "+12345550100",
      "language": "en",
      "subtotal_cents": 4999,
      "currency": "USD",
      "attribution": {
        "fbp": "fb.1.1700000000.123",
        "fbc": null,
        "ttp": null,
        "ttclid": null
      },
      "mode": "external",
      "frozen": false,
      "last_event_at": "2026-09-19T10:30:00.000Z",
      "sms_state": "sent",
      "sms_sent_at": "2026-09-19T11:00:02.000Z",
      "email_state": "pending",
      "email_touches": 0,
      "last_email_sent_at": null,
      "status": "pending",
      "recovered_at": null,
      "recovered_order_id": null,
      "created_at": "2026-09-19T10:30:01.000Z",
      "updated_at": "2026-09-19T11:00:02.000Z"
    }
  ],
  "total": 412
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | recovery_carts rows minus policy, links and cart, ordered by last_event_at desc. |
| `rows[].cart_token` | string | The checkout's cart token - the id for GET /v1/recovery/carts/:cart_token/details. |
| `rows[].status` | enum: pending\|done\|recovered\|frozen | pending = ladder running; done = finished without a recovery (or converted organically); recovered = order placed after a relance; frozen = the checkout already sent/recovered it, never touched. |
| `rows[].sms_state / email_state` | enum: pending\|sent\|done | Per-channel ladder state. |
| `rows[].email_touches` | integer | Emails sent so far. |
| `rows[].subtotal_cents` | integer | Cart subtotal in cents. |
| `rows[].mode` | enum: shadow\|external | shadow = the tool only computes; external = it sends. |
| `rows[].recovered_at / recovered_order_id` | string\|null | Set when recovered. |
| `total` | integer | Matching carts. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Contact data (email, phone_e164, customer) is returned in clear here - unlike /v1/messaging/logs.
- converted_at is not in the list projection; a done cart with an order shows only through recovered_order_id when recovered.
- limit=0 is treated as "default 50", not "no rows".

##### `POST /v1/recovery/carts`

**Scope** `recovery.write` - **Hand an abandoned cart to the recovery tool**

The checkout pushes (and re-pushes on every change) a cart it wants relanced by SMS / email. Idempotent upsert on `cart_token` within the key's account: email / phone merge (a received value replaces, an absent one keeps), `last_event_at` keeps the latest, `mode` and `policy` (when sent) are replaced. A `frozen` cart (the checkout already sent or recovered it) is stored but never touched. The 60 s job then applies the checkout's exact rules (delay + tolerance window slid out of quiet hours, ramp bucket, minimum cart, price-point target, email ladder, 24 h dedup, suppressions) and sends through the account's providers (Integrations -> Messaging). `shadow` = compute and journal only; `external` = real send + signed `recovery.sent` / `recovery.failed` callback to the checkout.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `v` | integer (literal 1) | **yes** | Payload version; must be 1. |
| `cart_token` | string | **yes** | 1..255 characters; the idempotency key inside the account. |
| `mode` | enum: shadow\|external | **yes** | shadow computes and journals without sending; external sends for real. |
| `shop` | object | **yes** | Store label inside the account (never a partition key). |
| `shop.id` | string | **yes** | Store id, 1..64 characters (also used to build a missing policy). |
| `shop.name` | string\|null; default `null` | no | Up to 200 characters. |
| `shop.domain` | string\|null; default `null` | no | Up to 255 characters. |
| `shop.logo_url` | string\|null; default `null` | no | Up to 2048 characters. |
| `shop.primary_color` | string\|null | no | Up to 64 characters. |
| `customer` | object | **yes** | At least one of email or phone_e164 is required. |
| `customer.email` | string\|null; default `null` | no | Valid e-mail, up to 255 characters. |
| `customer.phone_e164` | string\|null; default `null` | no | E.164 phone: + then 7..19 digits, no leading 0. |
| `customer.first_name` | string\|null; default `null` | no | Up to 120 characters. |
| `customer.language` | string\|null; default `null` | no | Up to 8 characters (en, fr, it, es, pt, pl pick the default template). |
| `cart` | object | **yes** | Cart snapshot. |
| `cart.currency` | string | **yes** | ISO 4217 code, exactly 3 characters. |
| `cart.subtotal_cents` | integer | **yes** | Subtotal in cents, >= 0. |
| `cart.item_count` | integer; default `0` | no | >= 0. |
| `cart.items` | object[]; default `[]` | no | Up to 200 items. |
| `cart.items[].product_id` | string\|number | **yes** | Product id. |
| `cart.items[].title` | string | **yes** | Up to 500 characters. |
| `cart.items[].variant_title` | string\|null | no | Up to 500 characters. |
| `cart.items[].quantity` | integer | **yes** | >= 0. |
| `cart.items[].unit_price_cents` | integer | **yes** | >= 0. |
| `cart.items[].image_url` | string\|null | no | Up to 2048 characters. |
| `links` | object | **yes** | Checkout-generated links (the tool never mints links); a channel without its url is skipped (skipped_no_link). Send {} when none. |
| `links.sms_token` | string\|null; default `null` | no | Up to 64 characters. |
| `links.sms_url` | string\|null; default `null` | no | Up to 2048 characters. |
| `links.email_token` | string\|null; default `null` | no | Up to 64 characters. |
| `links.email_url` | string\|null; default `null` | no | Up to 2048 characters. |
| `links.unsubscribe_url` | string\|null; default `null` | no | Up to 4096 characters. |
| `links.open_pixel_url` | string\|null; default `null` | no | Up to 4096 characters. |
| `attribution` | object; default `{}` | no | Ad click ids; the TikTok Lead event fires only with ttclid (event id = the link token). |
| `attribution.fbp` | string\|null | no | Up to 200 characters. |
| `attribution.fbc` | string\|null | no | Up to 400 characters. |
| `attribution.ttp` | string\|null | no | Up to 200 characters. |
| `attribution.ttclid` | string\|null | no | Up to 400 characters. |
| `policy` | object | no | Recovery settings snapshot. Omitted: built from the store's saved settings (400 when the store is unknown). |
| `policy.price_points_cents` | integer[]; default `[]` | no | Price points in cents (>= 0), up to 200. |
| `policy.sms` | object | **yes** | SMS channel settings (required when policy is sent). |
| `policy.sms.enabled` | boolean; default `false` | no | Channel on. |
| `policy.sms.delay_minutes` | integer; default `30` | no | Minutes after last_event_at before the (first) touch, 1..10080. |
| `policy.sms.tolerance_minutes` | integer; default `120` | no | How late a touch may still go out, 1..1440 (a missed window is terminal). |
| `policy.sms.link_valid_minutes` | integer; default `30` | no | Discount link validity, 5..10080. |
| `policy.sms.discount_kind` | enum: percent\|amount; default `percent` | no | Discount type. |
| `policy.sms.discount_value` | integer; default `15` | no | Discount value (percent or cents), >= 0. |
| `policy.sms.min_cart_cents` | integer; default `1000` | no | Minimum cart subtotal in cents, >= 0. |
| `policy.sms.test_mode_pct` | integer; default `100` | no | Share of carts actually handled, 0..100. |
| `policy.sms.quiet_hours_enabled` | boolean; default `true` | no | Slide sends out of quiet hours. |
| `policy.sms.tz` | string; default `America/New_York` | no | IANA timezone for quiet hours, 1..64 characters. |
| `policy.email` | object | **yes** | E-mail channel settings (required when policy is sent). |
| `policy.email.enabled` | boolean; default `false` | no | Channel on. |
| `policy.email.delay_minutes` | integer; default `30` | no | Minutes after last_event_at before the (first) touch, 1..10080. |
| `policy.email.tolerance_minutes` | integer; default `240` | no | How late a touch may still go out, 1..1440 (a missed window is terminal). |
| `policy.email.link_valid_minutes` | integer; default `30` | no | Discount link validity, 5..10080. |
| `policy.email.discount_kind` | enum: percent\|amount; default `percent` | no | Discount type. |
| `policy.email.discount_value` | integer; default `15` | no | Discount value (percent or cents), >= 0. |
| `policy.email.min_cart_cents` | integer; default `1000` | no | Minimum cart subtotal in cents, >= 0. |
| `policy.email.test_mode_pct` | integer; default `100` | no | Share of carts actually handled, 0..100. |
| `policy.email.quiet_hours_enabled` | boolean; default `false` | no | Slide sends out of quiet hours. |
| `policy.email.tz` | string; default `America/New_York` | no | IANA timezone for quiet hours, 1..64 characters. |
| `policy.email.touch_delays_minutes` | integer[]; default `[]` | no | Delays of the later e-mail touches, each >= 1, up to 10. |
| `last_event_at` | string (ISO 8601 with offset) | **yes** | Last cart activity: the anchor of the SMS window and of e-mail touch 1. |
| `frozen` | boolean; default `false` | no | true = the checkout already handled this cart; stored, never relaunched. |

**Request body**

```json
{
  "v": 1,
  "cart_token": "ct_example_0001",
  "mode": "shadow",
  "shop": {
    "id": "00000000-0000-4000-8000-000000000001",
    "name": "Example Store",
    "domain": "shop.example.com",
    "logo_url": null,
    "primary_color": "#1c64f2"
  },
  "customer": {
    "email": "jane@example.com",
    "phone_e164": "+14155552671",
    "first_name": "Jane",
    "language": "en"
  },
  "cart": {
    "currency": "USD",
    "subtotal_cents": 8990,
    "item_count": 1,
    "items": [
      {
        "product_id": 123,
        "title": "Lamp",
        "variant_title": "Black",
        "quantity": 1,
        "unit_price_cents": 8990,
        "image_url": null
      }
    ]
  },
  "links": {
    "sms_token": "aB3kZ9qL",
    "sms_url": "https://shop.example.com/r/aB3kZ9qL",
    "email_token": "Qw7pL2mN",
    "email_url": "https://shop.example.com/r/Qw7pL2mN",
    "unsubscribe_url": "https://shop.example.com/unsubscribe?token=example",
    "open_pixel_url": null
  },
  "attribution": {
    "fbp": null,
    "fbc": null,
    "ttp": null,
    "ttclid": "example-ttclid"
  },
  "policy": {
    "price_points_cents": [
      1990,
      2990,
      3990,
      4990,
      5990,
      6990,
      7990
    ],
    "sms": {
      "enabled": true,
      "delay_minutes": 30,
      "tolerance_minutes": 120,
      "link_valid_minutes": 30,
      "discount_kind": "percent",
      "discount_value": 15,
      "min_cart_cents": 1000,
      "test_mode_pct": 100,
      "quiet_hours_enabled": true,
      "tz": "America/New_York"
    },
    "email": {
      "enabled": true,
      "delay_minutes": 60,
      "touch_delays_minutes": [
        60,
        1440
      ],
      "tolerance_minutes": 240,
      "link_valid_minutes": 60,
      "discount_kind": "percent",
      "discount_value": 15,
      "min_cart_cents": 1000,
      "test_mode_pct": 100,
      "quiet_hours_enabled": false,
      "tz": "America/New_York"
    }
  },
  "last_event_at": "2026-09-14T12:00:00Z",
  "frozen": false
}
```

**Response**

```json
{
  "ok": true,
  "cart_token": "ct_example_0001",
  "status": "pending",
  "stale": false
}
```

| response field | type | description |
|---|---|---|
| `status` | 'pending' \| 'done' \| 'recovered' \| 'frozen' | pending = at least one channel still has a touch to consider; done = both channels finished (sent, expired or skipped for good); recovered = an order was paid; frozen = never touched. |
| `stale` | boolean | true when this push arrived after a newer one: its contact data and frozen flag were recorded, its content was not adopted. |

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>} (also when neither email nor phone_e164 is present) or {"error":"policy missing and the shop is unknown on the checkout side"}.
- `401` {"error":"Missing API key"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key"}.
- `403` {"error":"API key has no account"}: the key has no owner account.
- `403` {"error":"Banned","message":"..."} when the key owner is banned; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks the recovery scope.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `429` 1200 requests per minute per API key (per IP without a key).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Service temporarily unavailable","detail":"authentication backend error"} when the key lookup fails; {"error":"Server busy, retry"} when the server is at capacity.

**Gotchas**

- Everything is PER ACCOUNT (owner_email of the key). The same cart_token pushed by two accounts is two carts; a key of another account gets 404 on every read of this cart.
- Re-pushing is the way to update: the cart's email / phone, policy and mode are taken from the latest push; the send state (sms_sent_at, email_touches) is never reset by a push.
- A paid order ends the ladder: either call `.../recovered`, or let the `order.approved` event of the unified ingest (step 1) close the cart by its cart_token.
- Nothing is sent in shadow mode - the journal shows `computed` rows with the provider and price target that WOULD have been used. Flip the shop to external on the checkout side to send for real.
- Skip reasons in the journal (`GET /v1/recovery/carts/:cart_token` or Logs -> Abandoned cart SMS / Email): skipped_not_yet, skipped_window_expired, skipped_min_cart, skipped_invalid_phone, skipped_no_email, skipped_dedupe / skipped_duplicate_address (24 h), skipped_suppressed, skipped_test_sample, skipped_no_price_fit, skipped_no_provider, skipped_no_link, skipped_ladder_exhausted, skipped_preview.

##### `GET /v1/recovery/carts/:cart_token`

**Scope** `recovery.read` - **Read a cart's recovery state and sends (integration view)**

The integration view of one cart's recovery state: its status and every send decision, without the policy snapshot, the links or the raw payloads that GET /v1/recovery/carts/:cart_token/details returns. Status of one cart of the key's account and every decision the job took for it (sent / failed / computed / skipped with reason), newest first. Policy and links are not echoed back; payloads and provider responses are only in the dashboard.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `cart_token` | string | **yes** | The cart token as pushed. |

**Response**

```json
{
  "cart": {
    "cart_token": "ct_example_0001",
    "shop_id": "00000000-0000-4000-8000-000000000001",
    "email": "jane@example.com",
    "phone_e164": "+14155550100",
    "language": "en",
    "subtotal_cents": 8990,
    "currency": "USD",
    "mode": "external",
    "frozen": false,
    "last_event_at": "2026-09-14T12:00:00Z",
    "sms_state": "sent",
    "sms_sent_at": "2026-09-14T12:31:05Z",
    "email_state": "pending",
    "email_touches": 1,
    "last_email_sent_at": "2026-09-14T13:01:07Z",
    "status": "pending",
    "recovered_at": null,
    "recovered_order_id": null
  },
  "sends": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "channel": "email",
      "touch_number": 1,
      "mode": "external",
      "status": "sent",
      "skip_reason": null,
      "provider_name": "SMTP main",
      "template_name": null,
      "target_cents": 7990,
      "currency": "USD",
      "recovery_token": "Qw7pL2mN",
      "message_id": "<message-0001@example.com>",
      "delivery_status": null,
      "status_code": null,
      "ms": 812,
      "error": null,
      "hard_bounce": false,
      "notify_status": "sent",
      "created_at": "2026-09-14T13:01:07Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `cart.sms_state / cart.email_state` | 'pending' \| 'sent' \| 'done' | pending = a touch is still to be considered; sent = the last touch went out (email: more touches may follow); done = finished for good. |
| `sends[].status` | 'computed' \| 'sent' \| 'failed' \| 'skipped' | computed = shadow mode (nothing left the tool); skipped rows carry `skip_reason`. |
| `sends[].notify_status` | 'none' \| 'pending' \| 'sent' \| 'failed' | State of the signed `recovery.sent` / `recovery.failed` callback to the checkout (retried 1 min, 5 min, 15 min, 1 h, 6 h). |

**Errors**

- `401` {"error":"Missing API key"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key"}.
- `403` {"error":"Banned","message":"..."} when the key owner is banned; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks the recovery scope.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `404` {"error":"unknown cart for this account"}.
- `429` 1200 requests per minute per API key (per IP without a key).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Service temporarily unavailable","detail":"authentication backend error"} when the key lookup fails; {"error":"Server busy, retry"} when the server is at capacity.

**Gotchas**

- Not a polling endpoint for delivery: the checkout is told of every send by the signed callback; use this for debugging one cart.
- GET /v1/recovery/carts/:cart_token/details is the full record of a cart (policy, links, raw send payloads); this one answers for the key's own pushed carts.

##### `GET /v1/recovery/carts/:cart_token/details`

**Scope** `recovery.read` - **Read a recovery cart's full record (policy, links, raw send payloads)**

The full recovery record of one cart (policy snapshot, recovery links, items) and every send with its payload and provider response excerpt; GET /v1/recovery/carts/:cart_token is the integration view without policy, links or raw payloads. Returns the full cart row (including the policy snapshot, the recovery links and the cart items) and every relance send made for it, newest first, with the payload sent and the provider response excerpt.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `cart_token` | string | **yes** | The checkout cart token (as listed). Owner-scoped: another account's cart is 404. |

**Response**

```json
{
  "cart": {
    "owner_email": "merchant@example.com",
    "cart_token": "c9f1e2d3a4b5f6a7",
    "api_key_id": "2b7d1a3e-9f40-4c6b-8e12-0a5d3c9b7f21",
    "shop_id": "shop_3f2a91c4",
    "shop": {
      "id": "shop_3f2a91c4",
      "name": "Acme Store",
      "domain": "example.com",
      "logo_url": "https://example.com/logo.png",
      "primary_color": "#111111"
    },
    "customer": {
      "email": "jane.doe@example.com",
      "phone_e164": "+12345550100",
      "first_name": "Jane",
      "language": "en"
    },
    "email": "jane.doe@example.com",
    "phone_e164": "+12345550100",
    "language": "en",
    "subtotal_cents": 4999,
    "currency": "USD",
    "attribution": {
      "fbp": "fb.1.1700000000.123",
      "fbc": null,
      "ttp": null,
      "ttclid": null
    },
    "mode": "external",
    "frozen": false,
    "last_event_at": "2026-09-19T10:30:00.000Z",
    "sms_state": "sent",
    "sms_sent_at": "2026-09-19T11:00:02.000Z",
    "email_state": "pending",
    "email_touches": 0,
    "last_email_sent_at": null,
    "status": "pending",
    "recovered_at": null,
    "recovered_order_id": null,
    "created_at": "2026-09-19T10:30:01.000Z",
    "updated_at": "2026-09-19T11:00:02.000Z",
    "cart": {
      "currency": "USD",
      "subtotal_cents": 4999,
      "item_count": 1,
      "items": [
        {
          "product_id": "prod_881",
          "title": "Acme Hoodie",
          "variant_title": "L / Black",
          "quantity": 1,
          "unit_price_cents": 4999,
          "image_url": "https://example.com/img/hoodie.jpg"
        }
      ]
    },
    "links": {
      "sms_token": "rt_8f1a2b3c",
      "sms_url": "https://example.com/r/rt_8f1a2b3c",
      "email_token": "rt_9a2b3c4d",
      "email_url": "https://example.com/r/rt_9a2b3c4d",
      "unsubscribe_url": "https://example.com/u/xyz",
      "open_pixel_url": "https://example.com/o/xyz.gif"
    },
    "policy": {
      "price_points_cents": [
        4999
      ],
      "sms": {
        "enabled": true,
        "delay_minutes": 30,
        "tolerance_minutes": 120,
        "link_valid_minutes": 1440,
        "discount_kind": "percent",
        "discount_value": 10,
        "min_cart_cents": 1000,
        "test_mode_pct": 0,
        "quiet_hours_enabled": true,
        "tz": "America/New_York"
      },
      "email": {
        "enabled": true,
        "delay_minutes": 60,
        "tolerance_minutes": 240,
        "link_valid_minutes": 4320,
        "discount_kind": "percent",
        "discount_value": 10,
        "min_cart_cents": 0,
        "test_mode_pct": 0,
        "quiet_hours_enabled": false,
        "tz": "America/New_York",
        "touch_delays_minutes": [
          60,
          1440,
          2880
        ]
      }
    }
  },
  "sends": [
    {
      "id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
      "owner_email": "merchant@example.com",
      "cart_token": "c9f1e2d3a4b5f6a7",
      "shop_id": "shop_3f2a91c4",
      "channel": "sms",
      "touch_number": 1,
      "mode": "external",
      "status": "sent",
      "skip_reason": null,
      "provider_id": "9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d",
      "provider_name": "MessageWhiz US",
      "template_id": "d1e2f3a4-b5c6-4d7e-8f90-a1b2c3d4e5f6",
      "template_name": "SMS 10% (en)",
      "target_cents": 4499,
      "currency": "USD",
      "discount_kind": "percent",
      "discount_value": 10,
      "recovery_token": "rt_8f1a2b3c",
      "message_id": "mw_7f31a9c2",
      "delivery_status": "DELIVRD",
      "status_code": 200,
      "ms": 388,
      "error": null,
      "hard_bounce": false,
      "notify_status": "sent",
      "notify_attempts": 1,
      "notify_next_at": null,
      "notify_error": null,
      "created_at": "2026-09-19T11:00:02.000Z",
      "payload_sent": {
        "to": "+12345550100",
        "text": "Hi Jane, your cart is waiting - 10% off here: https://example.com/r/rt_8f1a2b3c"
      },
      "response_excerpt": "{\"message_id\":\"mw_7f31a9c2\"}"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `cart` | object | Full recovery_carts row: everything in the list projection plus cart {currency, subtotal_cents, item_count, items[]}, links {sms_url, email_url, unsubscribe_url, open_pixel_url...} and policy (the per-channel relance policy snapshot pushed with the cart). |
| `sends` | array | Full recovery_sends rows for this cart (see GET /v1/recovery/sends/:id), newest first, INCLUDING payload_sent and response_excerpt. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown token or another account's cart.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- links.sms_url / email_url are LIVE discount links - do not paste them in public places.
- payload_sent carries the raw recipient and message text (PII in clear).
- The policy is the snapshot the checkout pushed with the cart; the live relance settings come from the shop row (Checkouts page), so an edit there is not reflected here.

##### `POST /v1/recovery/carts/:cart_token/recovered`

**Scope** `recovery.write` - **Close a cart: the order was paid**

Stops the SMS / email ladder of one cart of the key's account and stamps `recovered_at` / `recovered_order_id`. Idempotent (a cart already recovered stays as it was).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `cart_token` | string | **yes** | The cart token as pushed. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `recovered_at` | string (ISO 8601 with offset); default `now` | no | When the order was paid. |
| `order_id` | string\|null | no | The paid order id (up to 128 characters), for the dashboard. |

**Request body**

```json
{
  "recovered_at": "2026-09-14T12:41:00Z",
  "order_id": "order-0001"
}
```

**Response**

```json
{ "ok": true }
```

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>}: recovered_at not an ISO datetime with offset, or order_id too long.
- `401` {"error":"Missing API key"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key"}.
- `403` {"error":"Banned","message":"..."} when the key owner is banned; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks the recovery scope.
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `404` {"error":"unknown cart for this account"}: not one of this account's carts (another account's cart looks unknown).
- `429` 1200 requests per minute per API key (per IP without a key).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Service temporarily unavailable","detail":"authentication backend error"} when the key lookup fails; {"error":"Server busy, retry"} when the server is at capacity.

**Gotchas**

- Also triggered automatically by the unified ingest's `order.approved` when the event carries the cart_token - calling this too is harmless.

##### `GET /v1/recovery/health`

**Scope** `recovery.read` - **Get cart-recovery health**

Snapshot of the account's abandoned-cart recovery engine: carts waiting for a relance, carts recovered in the last 7 days, the last 24 h of send outcomes per channel, checkout callbacks still pending, and how many providers per channel are enabled with a positive weight.

*No parameters.*

**Response**

```json
{
  "pending_carts": 37,
  "recovered_7d": 12,
  "sends_24h": [
    {
      "channel": "email",
      "status": "sent",
      "n": 61
    },
    {
      "channel": "email",
      "status": "skipped",
      "n": 14
    },
    {
      "channel": "sms",
      "status": "failed",
      "n": 2
    },
    {
      "channel": "sms",
      "status": "sent",
      "n": 88
    }
  ],
  "notify_pending": 1,
  "providers": [
    {
      "channel": "sms",
      "enabled": 1
    },
    {
      "channel": "email",
      "enabled": 2
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `pending_carts` | integer | recovery_carts with status 'pending' (ladder not finished). |
| `recovered_7d` | integer | Carts whose recovered_at is within the last 7 days. |
| `sends_24h` | array | {channel, status, n} over recovery_sends created in the last 24 h (statuses computed\|sent\|failed\|skipped). |
| `notify_pending` | integer | Sends whose checkout callback (recovery.sent/failed webhook) is still notify_status 'pending'. |
| `providers` | array | Always two rows: {channel:'sms', enabled} then {channel:'email', enabled} = providers enabled with weight > 0 (caps not considered). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- `providers.enabled` ignores caps and missing credentials - a provider without a password still counts as enabled.
- sends_24h mixes shadow and external modes.
- recovered_7d counts by recovered_at, not by cart creation.

##### `GET /v1/recovery/profiles`

**Scope** `recovery.read` - **List recovery sending settings**

The account's named sending settings - the timings a relance obeys. They used to live as eighteen columns on each store's row and nowhere else: 36 stores, 648 fields, no two comparable on a screen.

*No parameters.*

**Response**

```json
{"rows": []}
```

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Everything here is an OVERLAY and every part of it is optional. A store with no binding, or a binding whose fields are null, reads exactly the settings it read before - which is what makes this safe against live stores: nothing changes until a store is bound on purpose.
- One default per channel: what "the account's settings" means on a store's binding.

##### `POST /v1/recovery/profiles`

**Scope** `recovery.write` - **Create recovery sending settings**

Creates a named set of sending settings for one channel. Nothing sends differently until a store picks it on PUT /v1/recovery/bindings.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Unique per account and channel, case-insensitive. |
| `channel` | enum: sms\|email | **yes** | Which channel these settings apply to. |
| `delay_minutes` | integer | no | How long after the cart goes quiet the first message is due. 1..10080. |
| `touch_delays_minutes` | string\|null | no | E-MAIL ONLY - the ladder as minutes after the cart, comma separated ("60,1440,4320"). The database and this route both refuse it on an SMS profile: SMS sends one touch. |
| `link_valid_minutes` | integer | no | How long the recovery link works; the reserved price expires with it. 5..44640. |
| `discount_kind` | enum: percent\|amount | no | How discount_value is read. |
| `discount_value` | integer | no | Percent, or cents when discount_kind is 'amount'. |
| `min_cart_cents` | integer | no | Carts below this are never relanced. |
| `test_mode_pct` | integer | no | The share of carts actually messaged, 0..100, bucketed deterministically on the cart token so a cart stays in or out across touches. |
| `quiet_hours_enabled` | boolean | no | Hold a message until the legal window. The window itself is read on the RECIPIENT's clock (TCPA, 47 CFR 64.1200(c)(1)). |
| `tz` | string | no | IANA zone used ONLY as the fallback for a recipient whose number cannot be placed by area code. |
| `provider_id` | uuid \| null | no | Optional enabled SMS or email messaging provider UUID owned by this account, matching the profile channel. Null uses normal weighted provider selection. A pinned provider is exclusive: disabled, unavailable or quota-exhausted providers pause sending rather than fall back. |

**Request body**

```json
{
  "provider_id": "e1111111-1111-4111-8111-111111111111",
  "test_mode_pct": 25
}
```

**Response**

```json
{"id": "<uuid>"}
```

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused). {"error":"An SMS profile has no touch ladder"} when touch_delays_minutes is sent on an SMS profile. {"error":"Select an enabled messaging integration belonging to this account and channel"} when provider_id is not an enabled provider (weight above 0) of the account for that channel.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `409` A database uniqueness or reference conflict (for example a name already used), mapped to a 409 sentence.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Everything here is an OVERLAY and every part of it is optional. A store with no binding, or a binding whose fields are null, reads exactly the settings it read before - which is what makes this safe against live stores: nothing changes until a store is bound on purpose.
- A profile is SETTINGS, not a switch: it can never turn a channel on. Only a binding's `enabled` does that, so assigning settings to thirty stores cannot start messaging from thirty stores.
- test_mode_pct is the stable percentage (0-100) of eligible abandoned carts to attempt recovering, not already paid sales.
- PUT cannot change the channel of an existing profile.
- Provider selection requires migration 257_recovery_provider_selection.sql. Existing profiles keep weighted routing.

##### `PUT /v1/recovery/profiles/:id`

**Scope** `recovery.write` - **Update recovery sending settings**

Patches a named set of sending settings. Only the fields sent are written. Takes effect on the next tick for every store bound to it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The profile to update. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Unique per account and channel, case-insensitive. |
| `channel` | enum: sms\|email | no | Optional; when sent it must equal the profile's channel (a profile cannot change channel: 400). |
| `delay_minutes` | integer | no | How long after the cart goes quiet the first message is due. 1..10080. |
| `touch_delays_minutes` | string\|null | no | E-MAIL ONLY - the ladder as minutes after the cart, comma separated ("60,1440,4320"). The database and this route both refuse it on an SMS profile: SMS sends one touch. |
| `link_valid_minutes` | integer | no | How long the recovery link works; the reserved price expires with it. 5..44640. |
| `discount_kind` | enum: percent\|amount | no | How discount_value is read. |
| `discount_value` | integer | no | Percent, or cents when discount_kind is 'amount'. |
| `min_cart_cents` | integer | no | Carts below this are never relanced. |
| `test_mode_pct` | integer | no | The share of carts actually messaged, 0..100, bucketed deterministically on the cart token so a cart stays in or out across touches. |
| `quiet_hours_enabled` | boolean | no | Hold a message until the legal window. The window itself is read on the RECIPIENT's clock (TCPA, 47 CFR 64.1200(c)(1)). |
| `tz` | string | no | IANA zone used ONLY as the fallback for a recipient whose number cannot be placed by area code. |
| `provider_id` | uuid \| null | no | Optional enabled SMS or email messaging provider UUID owned by this account, matching the profile channel. Null uses normal weighted provider selection. A pinned provider is exclusive: disabled, unavailable or quota-exhausted providers pause sending rather than fall back. |

**Request body**

```json
{
  "provider_id": "e1111111-1111-4111-8111-111111111111",
  "test_mode_pct": 25
}
```

**Response**

```json
{"ok": true}
```

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid. {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused). {"error":"A sending profile cannot change channel"}. {"error":"Select an enabled messaging integration belonging to this account and channel"} when provider_id is not an enabled provider (weight above 0) of the account for that channel.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Changing a profile re-times every store bound to it at once - that is the point, and it is the one action here with estate-wide reach.
- test_mode_pct is the stable percentage (0-100) of eligible abandoned carts to attempt recovering, not already paid sales.
- PUT cannot change the channel of an existing profile.
- Provider selection requires migration 257_recovery_provider_selection.sql. Existing profiles keep weighted routing.

##### `DELETE /v1/recovery/profiles/:id`

**Scope** `recovery.write` - **Delete recovery sending settings**

Deletes a named set of sending settings.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The profile to delete. |

**Response**

```json
{"ok": true}
```

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Stores bound to it are NOT left without settings: the binding's foreign key is ON DELETE SET NULL, so they fall back to their own columns and keep relancing. A deletion must never stop sending.

##### `POST /v1/recovery/profiles/:id/default`

**Scope** `recovery.write` - **Make sending settings the channel default**

Marks this profile as the channel's default: what a store bound WITHOUT naming a profile uses. Clears whichever profile held it, in the same transaction.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The profile to promote. |

**Response**

```json
{"ok": true}
```

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- One default per channel, not one per account.

##### `GET /v1/recovery/sends`

**Scope** `recovery.read` - **List recovery sends**

Paginated relance journal of the account (both channels, all statuses), newest first, with a per-(channel,status) histogram of the filtered set. Rows omit payload_sent and response_excerpt.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | string | no | sms \| email (exact, unvalidated). |
| `status` | string | no | computed \| sent \| failed \| skipped (exact, unvalidated). |
| `mode` | string | no | shadow \| external. |
| `shop_id` | string | no | Exact shop id. |
| `cart_token` | string | no | Exact cart token. |
| `from` | string | no | created_at >= from. Passed to Postgres as a timestamp - an unparsable value is a 400 "A date/time value is invalid." from the DB mapper. |
| `to` | string | no | created_at < to (exclusive). |
| `limit` | integer; default `50` | no | Max 10000; 0/non-numeric -> 50. |
| `offset` | integer; default `0` | no | Max 1000000. |

**Response**

```json
{
  "rows": [
    {
      "id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
      "owner_email": "merchant@example.com",
      "cart_token": "c9f1e2d3a4b5f6a7",
      "shop_id": "shop_3f2a91c4",
      "channel": "sms",
      "touch_number": 1,
      "mode": "external",
      "status": "sent",
      "skip_reason": null,
      "provider_id": "9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d",
      "provider_name": "MessageWhiz US",
      "template_id": "d1e2f3a4-b5c6-4d7e-8f90-a1b2c3d4e5f6",
      "template_name": "SMS 10% (en)",
      "target_cents": 4499,
      "currency": "USD",
      "discount_kind": "percent",
      "discount_value": 10,
      "recovery_token": "rt_8f1a2b3c",
      "message_id": "mw_7f31a9c2",
      "delivery_status": "DELIVRD",
      "status_code": 200,
      "ms": 388,
      "error": null,
      "hard_bounce": false,
      "notify_status": "sent",
      "notify_attempts": 1,
      "notify_next_at": null,
      "notify_error": null,
      "created_at": "2026-09-19T11:00:02.000Z"
    }
  ],
  "total": 1054,
  "byChannelStatus": [
    {
      "channel": "email",
      "status": "sent",
      "n": 320
    },
    {
      "channel": "email",
      "status": "skipped",
      "n": 140
    },
    {
      "channel": "sms",
      "status": "failed",
      "n": 4
    },
    {
      "channel": "sms",
      "status": "sent",
      "n": 590
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | recovery_sends rows without payload_sent / response_excerpt. |
| `rows[].status` | enum: computed\|sent\|failed\|skipped | computed = shadow mode (nothing sent). |
| `rows[].touch_number` | integer | Position in the ladder. |
| `rows[].target_cents / discount_kind / discount_value` | mixed | The price point offered (cents) and the discount applied. |
| `rows[].recovery_token` | string\|null | Token of the link sent (the /r/<token> page). |
| `rows[].delivery_status` | string\|null | SMS receipt (DELIVRD...); null for email. |
| `rows[].notify_status` | enum: none\|pending\|sent\|failed | Checkout callback state; 'none' when the send never required one. |
| `rows[].notify_attempts / notify_next_at / notify_error` | mixed | Callback retry bookkeeping. |
| `total` | integer | Rows matching the filters (sum of byChannelStatus). |
| `byChannelStatus` | array | {channel, status, n} histogram over the filtered set, ignoring paging. |
| `status` | string | Existing statuses plus unknown. Unknown is distinct from failed and sent; its existing error field contains generic investigation guidance. |

**Errors**

- `400` "A date/time value is invalid." - from/to unparsable (DB mapper).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Filters are exact-match and unvalidated: a typo returns an empty list, not a 400.
- to is exclusive, from inclusive.
- Contact data is not in this projection (see the cart or the send detail).
- Status unknown means delivery is unconfirmed and quota/touch reservations remain held. Do not issue a new send without independent provider evidence. Existing unknown messages are never automatically replayed.

##### `GET /v1/recovery/sends/:id`

**Scope** `recovery.read` - **Get one recovery send**

Returns the full relance send row of the account, including payload_sent (what was posted to the provider) and response_excerpt. The row is returned BARE (no wrapper object).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | recovery_sends id. Non-UUID -> 400 'bad id'. |

**Response**

```json
{
  "id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
  "owner_email": "merchant@example.com",
  "cart_token": "c9f1e2d3a4b5f6a7",
  "shop_id": "shop_3f2a91c4",
  "channel": "sms",
  "touch_number": 1,
  "mode": "external",
  "status": "sent",
  "skip_reason": null,
  "provider_id": "9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d",
  "provider_name": "MessageWhiz US",
  "template_id": "d1e2f3a4-b5c6-4d7e-8f90-a1b2c3d4e5f6",
  "template_name": "SMS 10% (en)",
  "target_cents": 4499,
  "currency": "USD",
  "discount_kind": "percent",
  "discount_value": 10,
  "recovery_token": "rt_8f1a2b3c",
  "message_id": "mw_7f31a9c2",
  "delivery_status": "DELIVRD",
  "status_code": 200,
  "ms": 388,
  "error": null,
  "hard_bounce": false,
  "notify_status": "sent",
  "notify_attempts": 1,
  "notify_next_at": null,
  "notify_error": null,
  "created_at": "2026-09-19T11:00:02.000Z",
  "payload_sent": {
    "to": "+12345550100",
    "text": "Hi Jane, your cart is waiting - 10% off here: https://example.com/r/rt_8f1a2b3c"
  },
  "response_excerpt": "{\"message_id\":\"mw_7f31a9c2\"}"
}
```

| response field | type | description |
|---|---|---|
| `(root)` | object | A RecoverySendRow: id, owner_email, cart_token, shop_id, channel, touch_number, mode, status, skip_reason, provider_id, provider_name, template_id, template_name, target_cents, currency, discount_kind, discount_value, recovery_token, message_id, delivery_status, status_code, ms, payload_sent, response_excerpt, error, hard_bounce, notify_status, notify_attempts, notify_next_at, notify_error, created_at. |
| `payload_sent` | object\|null | Provider request as sent (SMS: {to, text[, callback]}; email: {to, subject...}). Raw recipient in clear. |
| `response_excerpt` | string\|null | Provider's response, truncated. |
| `status` | string | Existing statuses plus unknown. Unknown is distinct from failed and sent; its existing error field contains generic investigation guidance. |

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The response is the row itself - there is no {send:...} wrapper (unlike GET /v1/unified/sends/:id).
- Status unknown means delivery is unconfirmed and quota/touch reservations remain held. Do not issue a new send without independent provider evidence. Existing unknown messages are never automatically replayed.

##### `POST /v1/recovery/sends/:id/notify`

**Scope** `recovery.write` - **Re-send the checkout callback for a send**

Re-posts the recovery.sent / recovery.failed webhook event of one send to the checkout (RECOVERY_CHECKOUT_WEBHOOK_URL, HMAC-signed with the unified ingest secret) and records the outcome on the send (notify_status, notify_attempts, notify_error). Used when the checkout missed the callback that stamps the recovery link's expiry.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | recovery_sends id of the caller's account. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the checkout answered 2xx (or 409 duplicate). false when the webhook is not configured, was rejected (4xx) or unreachable - see notify_error on the send. |

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `409` {"error":"Provider acceptance is unknown; investigate before notifying a final outcome"} when the send's provider status is unknown. Nothing is resent.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- A failure is a 200 {ok:false}; the reason lands in the send row (notify_error: "not configured" / the HTTP body / "timeout").
- No retry is scheduled by this route (notify_next_at is cleared) - the background queue only retries sends it marked pending itself.
- The event type follows the send's status: 'recovery.sent' for status sent, 'recovery.failed' otherwise (skipped/computed rows produce a recovery.failed event with error 'unknown').
- The checkout treats the event id (= send id) as idempotent: re-sending an already received one answers 409, counted as ok:true.
- 10 s timeout on the checkout call.
- Status unknown means delivery is unconfirmed and quota/touch reservations remain held. Do not issue a new send without independent provider evidence. Existing unknown messages are never automatically replayed.

##### `GET /v1/recovery/templates`

**Scope** `recovery.read` - **List recovery templates**

Lists the account's abandoned-cart message templates (SMS and email), optionally one channel, ordered by channel, language, name. When the account has no template for a channel/language the engine falls back to built-in defaults, which are NOT listed here.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | enum: sms\|email | no | Filter; any other value = both channels. |

**Response**

```json
{
  "rows": [
    {
      "id": "d1e2f3a4-b5c6-4d7e-8f90-a1b2c3d4e5f6",
      "owner_email": "merchant@example.com",
      "shop_id": null,
      "channel": "sms",
      "language": "en",
      "name": "SMS 10% (en)",
      "subject": null,
      "body": "Hi {first_name}, your cart is waiting - 10% off here: {link}",
      "body_text": null,
      "weight": 1,
      "enabled": true,
      "created_at": "2026-09-01T10:00:00.000Z",
      "updated_at": "2026-09-01T10:00:00.000Z"
    },
    {
      "id": "e2f3a4b5-c6d7-4e8f-9a0b-1c2d3e4f5a6b",
      "owner_email": "merchant@example.com",
      "shop_id": null,
      "channel": "email",
      "language": "en",
      "name": "Email touch 1 (en)",
      "subject": "You left something behind, {first_name}",
      "body": "<p>Your cart is waiting. <a href=\"{link}\">Finish your order</a> with 10% off.</p>",
      "body_text": "Your cart is waiting: {link}",
      "weight": 1,
      "enabled": true,
      "created_at": "2026-09-01T10:00:00.000Z",
      "updated_at": "2026-09-01T10:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | recovery_templates rows: id, owner_email, shop_id, channel, language, name, subject, body, body_text, weight, enabled, created_at, updated_at. |
| `rows[].shop_id` | string\|null | null = applies to every shop of the account. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Built-in default templates are implicit and never returned; an empty list does not mean "no message will be sent".
- Full bodies are returned (HTML can be large).

##### `POST /v1/recovery/templates`

**Scope** `recovery.write` - **Create a recovery template**

Creates an SMS or email template for the account's relances. The body must contain the {link} placeholder (replaced by the personal recovery link at send time). Returns the new id with 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `shop_id` | string\|null; default `null` | no | Restrict the template to one checkout shop id (<=64 chars); null = every shop of the account. |
| `channel` | enum: sms\|email | **yes** | Channel the template renders for. |
| `language` | string\|null; default `en` | no | BCP-47 tag, or NULL / absent (migration 252) meaning the template serves EVERY language and carries its words in `translations`. A named language still scopes the template to that language alone. |
| `name` | string | **yes** | Label, trimmed, 1..120 chars. Not unique. |
| `subject` | string\|null; default `null` | no | Email subject (<=255). Ignored for SMS. |
| `body` | string | **yes** | 1..50000 chars, MUST contain the literal placeholder {link} (the recovery link) or zod rejects it ('body must contain {link}'). HTML for email, plain text for SMS. |
| `body_text` | string\|null; default `null` | no | Plain-text alternative for email (<=50000). |
| `translations` | object | no | The template's words per language: {"fr": {"headline": "...", "cta_label": "..."}, ...}. The LAYOUT lives once in `body`; only these change between languages. Accepted keys: subject, body, body_text, preheader, greeting, headline, body_copy, cta_label, urgency_label, reassurance_line_1, reassurance_line_2, unsubscribe_label - the object is strict, an unknown key is a 400 rather than a translation that silently does nothing. A key absent for a language falls back to the engine's own wording FOR THAT LANGUAGE, never to another language's. On PUT the map REPLACES the stored one (it is not merged), so removing a translation is possible. For SMS there is no layout to share: a translation overrides `body`. |
| `weight` | integer; default `1` | no | 0..1000 weighted-random pick among matching enabled templates; 0 = never. |
| `enabled` | boolean; default `true` | no | Whether the picker may use it. |
| `is_default` | boolean (false only) | no | Only false is accepted (true is a 400): false demotes the template from the account default. Promote with POST /v1/recovery/templates/:id/default. |
| `translations.<language>` | object | no | The words for one language (key: a language tag of 2 to 8 characters). Strict: only the keys below are accepted. |
| `translations.<language>.subject` | string | no | Max 255 characters. |
| `translations.<language>.body` | string | no | Max 50000 characters. |
| `translations.<language>.body_text` | string | no | Max 50000 characters. |
| `translations.<language>.preheader` | string | no | Max 255 characters. |
| `translations.<language>.greeting` | string | no | Max 255 characters. |
| `translations.<language>.headline` | string | no | Max 255 characters. |
| `translations.<language>.body_copy` | string | no | Max 2000 characters. |
| `translations.<language>.cta_label` | string | no | Max 120 characters. |
| `translations.<language>.urgency_label` | string | no | Max 255 characters. |
| `translations.<language>.reassurance_line_1` | string | no | Max 255 characters. |
| `translations.<language>.reassurance_line_2` | string | no | Max 255 characters. |
| `translations.<language>.unsubscribe_label` | string | no | Max 120 characters. |

**Request body**

```json
{
  "channel": "email",
  "language": "en",
  "name": "Email touch 1 (en)",
  "subject": "You left something behind, {first_name}",
  "body": "<p>Your cart is waiting. <a href=\"{link}\">Finish your order</a> with 10% off.</p>",
  "body_text": "Your cart is waiting: {link}",
  "weight": 1,
  "enabled": true
}
```

**Response**

```json
{
  "id": "e2f3a4b5-c6d7-4e8f-9a0b-1c2d3e4f5a6b"
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | New template id. |

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- One template, its translations inside it (migration 252). Six languages used to be six rows with the sentences written into the HTML, so the same 86-line layout existed six times - measured 2026-10-26, 77 of those lines were identical across all six and the 9 that differed were each a sentence the renderer already had a placeholder for.
- 201, not 200.
- The error key is 'invalid payload' here, not 'Invalid' like most routes.
- The only enforced placeholder is {link}; other placeholders ({first_name}, {shop_name}, {discount}...) are rendered when known and otherwise left as-is - verify with a test cart.
- No uniqueness: several templates with the same channel/language are legal and picked weighted-random.
- Once the account has ONE enabled template for a channel+language, the built-in default for that pair is no longer used.
- subject is stored for SMS templates but never used.

##### `PUT /v1/recovery/templates/:id`

**Scope** `recovery.write` - **Update a recovery template**

Partial update of one template of the account (any subset of the creation fields; `body` is re-checked for {link}). Returns {ok:true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Template id. Non-UUID -> 400 'bad id'. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `shop_id` | string\|null; default `keep` | no | Restrict the template to one checkout shop id (<=64 chars); null = every shop of the account. |
| `channel` | enum: sms\|email | no | Channel the template renders for. |
| `language` | string\|null; default `keep` | no | BCP-47 tag, or NULL / absent (migration 252) meaning the template serves EVERY language and carries its words in `translations`. A named language still scopes the template to that language alone. |
| `name` | string | no | Label, trimmed, 1..120 chars. Not unique. |
| `subject` | string\|null; default `keep` | no | Email subject (<=255). Ignored for SMS. |
| `body` | string | no | 1..50000 chars, MUST contain the literal placeholder {link} (the recovery link) or zod rejects it ('body must contain {link}'). HTML for email, plain text for SMS. |
| `body_text` | string\|null; default `keep` | no | Plain-text alternative for email (<=50000). |
| `translations` | object | no | The template's words per language: {"fr": {"headline": "...", "cta_label": "..."}, ...}. The LAYOUT lives once in `body`; only these change between languages. Accepted keys: subject, body, body_text, preheader, greeting, headline, body_copy, cta_label, urgency_label, reassurance_line_1, reassurance_line_2, unsubscribe_label - the object is strict, an unknown key is a 400 rather than a translation that silently does nothing. A key absent for a language falls back to the engine's own wording FOR THAT LANGUAGE, never to another language's. On PUT the map REPLACES the stored one (it is not merged), so removing a translation is possible. For SMS there is no layout to share: a translation overrides `body`. |
| `weight` | integer; default `keep` | no | 0..1000 weighted-random pick among matching enabled templates; 0 = never. |
| `enabled` | boolean; default `keep` | no | Whether the picker may use it. |
| `is_default` | boolean (false only) | no | Only false is accepted (true is a 400): false demotes the template from the account default. Promote with POST /v1/recovery/templates/:id/default. |
| `translations.<language>` | object | no | The words for one language (key: a language tag of 2 to 8 characters). Strict: only the keys below are accepted. |
| `translations.<language>.subject` | string | no | Max 255 characters. |
| `translations.<language>.body` | string | no | Max 50000 characters. |
| `translations.<language>.body_text` | string | no | Max 50000 characters. |
| `translations.<language>.preheader` | string | no | Max 255 characters. |
| `translations.<language>.greeting` | string | no | Max 255 characters. |
| `translations.<language>.headline` | string | no | Max 255 characters. |
| `translations.<language>.body_copy` | string | no | Max 2000 characters. |
| `translations.<language>.cta_label` | string | no | Max 120 characters. |
| `translations.<language>.urgency_label` | string | no | Max 255 characters. |
| `translations.<language>.reassurance_line_1` | string | no | Max 255 characters. |
| `translations.<language>.reassurance_line_2` | string | no | Max 255 characters. |
| `translations.<language>.unsubscribe_label` | string | no | Max 120 characters. |

**Request body**

```json
{
  "enabled": false,
  "weight": 0
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid. {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- One template, its translations inside it (migration 252). Six languages used to be six rows with the sentences written into the HTML, so the same 86-line layout existed six times - measured 2026-10-26, 77 of those lines were identical across all six and the 9 that differed were each a sentence the renderer already had a placeholder for.
- An empty body ({}) returns {ok:true} without checking the id exists.
- channel can be changed on an existing template; language/shop_id too - the picker re-evaluates on the next tick.
- A missing JSON body (no content) fails zod (400), unlike {}.

##### `DELETE /v1/recovery/templates/:id`

**Scope** `recovery.write` - **Delete a recovery template**

Deletes one template of the account. Sends already made keep template_id / template_name as stored. Returns {ok:true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Template id. Non-UUID -> 400 'bad id'. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Hard delete; if it was the only enabled template for a channel+language, the engine silently returns to the built-in default.

##### `POST /v1/recovery/templates/:id/default`

**Scope** `recovery.write` - **Make a recovery template the default**

Marks this template as the account's DEFAULT for its channel and language: what a relance sends when no template matches the shop or the buyer's language. Before this existed the fallback was wording compiled into the engine, which appeared in no list, no editor and no preview - an account whose templates were deleted or switched off kept relancing buyers with words nobody on the platform could read. Promoting CLEARS whichever template held the default, in the same transaction, because the unique index would otherwise refuse the write instead of moving it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The template to promote. Must belong to the calling account and be account-wide (shop_id null). |

**Response**

```json
{"ok": true}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true - the template is now the default of its channel and language. |

**Errors**

- `400` {"error":"bad id"} when :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"} for an unknown id or another account's.
- `409` {"error":"<reason>"} when the template cannot be the default, for example {"error":"A template scoped to one shop cannot be the account default"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- One default per channel AND language, not one per channel: a six-language family is six rows, each the default of its own language.
- Being the default is independent of `enabled`. A disabled default is still shown as the default, and switching it off is what lets the engine's compiled-in wording apply again - a visible act rather than a silent second default appearing.
- There is no 'unset the default' route: demote by sending is_default:false on PUT, or promote another template, which clears this one.

##### `POST /v1/recovery/templates/preview`

**Scope** `recovery.read` - **Preview a recovery template**

Renders a template DRAFT against a fixed sample cart and returns exactly what a buyer would receive - the SMS text with its length, or the e-mail subject, HTML and plain-text alternative. Writes nothing, sends nothing, mints no recovery token. The draft is sent in the body rather than referenced by id, so the editor can preview unsaved work; an empty body renders the engine's own built-in wording for that language, which is what a shop with no template of its own receives.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | enum: sms\|email | **yes** | Which renderer to use. Decides the shape of the answer. |
| `language` | string (2..8); default `en` | no | Locale of the built-in wording and of the e-mail seeds (en, fr, it, es, pt, pl are translated; anything else falls back to en). |
| `subject` | string\|null | no | E-mail subject draft. Ignored for sms. |
| `body` | string\|null | no | The SMS text or the HTML body. Omit or leave empty to render the engine default. Unlike the create / update routes, {link} is NOT required here - a preview is for work in progress. For sms, strings.body (when given) is used instead. |
| `body_text` | string\|null | no | Plain-text alternative of an e-mail. Ignored for sms. |
| `shop_name` | string; default `Your store` | no | Name substituted for {shop_name} in the sample. |
| `first_name` | string; default `Alex` | no | Name substituted for {first_name} in the sample. |
| `strings` | object | no | The words of the draft for the language previewed (the template's translation for that language): subject, body, body_text (at most 50000), preheader, greeting, headline, urgency_label, reassurance_line_1, reassurance_line_2 (at most 255 each), body_copy (at most 2000), cta_label, unsubscribe_label (at most 120). Strict: an unknown key is a 400. For sms, strings.body wins over body; for email, the strings are rendered into the same layout as body. |
| `strings.subject` | string | no | Max 255 characters. |
| `strings.body` | string | no | Max 50000 characters. |
| `strings.body_text` | string | no | Max 50000 characters. |
| `strings.preheader` | string | no | Max 255 characters. |
| `strings.greeting` | string | no | Max 255 characters. |
| `strings.headline` | string | no | Max 255 characters. |
| `strings.body_copy` | string | no | Max 2000 characters. |
| `strings.cta_label` | string | no | Max 120 characters. |
| `strings.urgency_label` | string | no | Max 255 characters. |
| `strings.reassurance_line_1` | string | no | Max 255 characters. |
| `strings.reassurance_line_2` | string | no | Max 255 characters. |
| `strings.unsubscribe_label` | string | no | Max 120 characters. |

**Request body**

```json
{
  "channel": "email",
  "language": "fr",
  "subject": "Toujours {discount} ?",
  "body": "<p>Bonjour {first_name}, votre panier passait de {price_current} à {price}. <a href=\"{link}\">Finaliser</a></p>"
}
```

**Response**

```json
{
  "channel": "email",
  "language": "fr",
  "subject": "Toujours 15% économisés ?",
  "html": "<!doctype html>…",
  "text": "Bonjour Alex, …",
  "unknown_placeholders": [],
  "sample": {
    "shopName": "Your store",
    "firstName": "Alex",
    "currency": "USD",
    "originalTotalCents": 8990,
    "targetCents": 6990,
    "discountKind": "percent",
    "discountValue": 15,
    "validity": "1 h",
    "link": "https://example.invalid/r/PREVIEW"
  }
}
```

| response field | type | description |
|---|---|---|
| `channel` | enum: sms\|email | Echo of the channel rendered. |
| `language` | string | Locale actually used. |
| `text` | string | The SMS text, or the e-mail's plain-text alternative. |
| `length` | int | SMS only - characters in the rendered text. Over 160 the carrier bills more than one segment. |
| `subject` | string | E-mail only - the rendered subject, leading punctuation stripped and the first letter capitalised, exactly as the sender does it. |
| `html` | string | E-mail only - the full rendered document. Operator-authored HTML: render it sandboxed. |
| `unknown_placeholders` | string[] | E-mail only - {placeholders} the renderer did not know and therefore left literal, which is what a buyer would have received. Empty is the healthy answer. |
| `sample` | object | The fixed sample the draft was rendered against, so two previews of the same text are comparable. |

**Errors**

- `400` {"error":"invalid payload","details":<zod flatten()>} for an invalid body (strict: an unknown field is refused).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the account's plan lacks the recovery module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Renders only: no template is created or modified, nothing is sent, and the link in the output is a deliberately fake https://example.invalid/r/PREVIEW - never a usable recovery token.
- {price} is the DISCOUNTED price and {price_current} the one the cart held before. The naming is counter-intuitive and identical in both channels on purpose (recovery/run.ts fills them that way); swapping them would silently rewrite every template already written.
- {discount} is worded per channel: formatDiscountLabel for SMS ('15% off'), the locale seed's own label for e-mail ('15% saved'), because the e-mail copy is translated per locale.
- An unknown placeholder is NOT an error - the renderer leaves it literal, exactly as a buyer would see it, and names it in unknown_placeholders so a typo is visible before a send rather than after.

#### Senders

The e-mail (SMTP) and SMS providers, their tests, logs, analytics, rates and costs.

- Messaging analytics, from `GET /v1/messaging/analytics` (one row per day and provider): success rate = sent / (sent + failed); average latency = ms_sum / ms_n. The Total row sums the counts and recomputes both from the sums.

##### `GET /v1/messaging/alerts`

**Scope** `integrations.read` - **Get messaging provider alerts**

Evaluates every e-mail and SMS provider of the account against the last 24 hours of the cart-recovery send journal and returns the ones that can no longer send: supplier credit exhausted, a daily or monthly cap of the provider reached, or only failures. Also lists the channels that are fully down (every enabled provider of the channel alerting). This is the banner the dashboard shows on every page.

*No parameters.*

**Response**

```json
{
  "alerts": [
    {
      "kind": "sms",
      "provider_id": "00000000-0000-4000-8000-000000000011",
      "provider_name": "SMS pool US",
      "enabled": true,
      "reason": "credit",
      "last_error": "insufficient balance",
      "last_error_at": "2026-11-20 11:58:02.112+00",
      "failed_24h": 41,
      "sent_24h": 120,
      "sent_today": 88,
      "daily_cap": 0,
      "sent_month": 1904,
      "monthly_cap": 20000
    },
    {
      "kind": "email",
      "provider_id": "00000000-0000-4000-8000-000000000012",
      "provider_name": "Primary SMTP",
      "enabled": true,
      "reason": "daily_cap",
      "last_error": null,
      "last_error_at": null,
      "failed_24h": 0,
      "sent_24h": 5000,
      "sent_today": 5000,
      "daily_cap": 5000,
      "sent_month": 6120,
      "monthly_cap": 0
    }
  ],
  "channel_down": ["sms"]
}
```

| response field | type | description |
|---|---|---|
| `alerts` | array | One entry per alerting provider (e-mail and SMS mixed). Empty when everything is healthy. |
| `alerts[].kind` | enum: email\|sms | Channel of the provider. |
| `alerts[].provider_id / provider_name / enabled` | string / string / boolean | The provider. |
| `alerts[].reason` | enum: credit\|daily_cap\|monthly_cap\|failing | credit = the last outcome is a supplier no-balance / quota failure newer than the last success; daily_cap / monthly_cap = the provider cap is reached (enabled providers only); failing = 3 or more failures and no success in 24 hours. |
| `alerts[].last_error / last_error_at` | string\|null | Most recent failure text and time (24-hour window, external sends only). |
| `alerts[].failed_24h / sent_24h` | integer | Counts over the last 24 hours of external sends. |
| `alerts[].sent_today / daily_cap / sent_month / monthly_cap` | integer | Cap counters (UTC day / month); a cap of 0 = unlimited. |
| `channel_down` | array of enum: sms\|email | Channels whose every enabled provider is alerting (a channel with no enabled provider is not listed). |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A provider appears at most once, with the first matching reason in the order credit, daily_cap, monthly_cap, failing.
- Only external-mode sends (real sends, not shadow computations) count for credit and failing.
- A later successful send clears a credit alert automatically (the rule compares the last failure with the last success).
- A disabled provider can still show a credit alert (that rule ignores `enabled`), never a cap or failing alert.
- last_error_at is a Postgres timestamp text (for example "2026-11-20 11:58:02.112+00"), not strict ISO 8601.

##### `GET /v1/messaging/analytics`

**Scope** `integrations.read` - **Get per-day messaging analytics for a channel**

Per-day and per-provider send statistics of one channel (email or sms) over a time range, read from the cart-recovery send journal: sent, delivered, undelivered and failed counts and latency components, plus channel totals that also count skipped and shadow-computed decisions. Days are bucketed in the requested IANA time zone.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | enum: email\|sms | **yes** | Channel to report on. |
| `from` | string; default `to minus 30 days` | no | ISO 8601 datetime ending in Z (an offset is a 400). Inclusive start. |
| `to` | string; default `now` | no | ISO 8601 datetime ending in Z. Exclusive end: the range is [from, to). |
| `tz` | string; default `UTC` | no | IANA zone used to bucket the per-day rows, max 64 chars. An unknown zone silently falls back to UTC. |

**Response**

```json
{
  "range": {
    "from": "2026-08-20T12:00:00.000Z",
    "to": "2026-09-19T12:00:00.000Z"
  },
  "channel": "sms",
  "tz": "America/New_York",
  "totals": {
    "sent": 1904,
    "delivered": 1710,
    "undelivered": 61,
    "failed": 44,
    "hard_bounces": 0,
    "skipped": 322,
    "computed": 0,
    "ms_sum": 812300,
    "ms_n": 1948,
    "providers": 2
  },
  "days": [
    {
      "day": "2026-09-19",
      "provider_id": "00000000-0000-4000-8000-000000000011",
      "provider_name": "SMS pool US",
      "sent": 88,
      "delivered": 80,
      "undelivered": 3,
      "failed": 2,
      "ms_sum": 37200,
      "ms_n": 90
    },
    {
      "day": "2026-09-18",
      "provider_id": "00000000-0000-4000-8000-000000000011",
      "provider_name": "SMS pool US",
      "sent": 102,
      "delivered": 95,
      "undelivered": 2,
      "failed": 1,
      "ms_sum": 41000,
      "ms_n": 103
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `range` | object | Effective {from, to} used. |
| `channel` | enum: email\|sms | Echo. |
| `tz` | string | Effective zone: the requested one, or UTC when it was absent or invalid. |
| `totals.sent` | integer | Rows with status sent (accepted by the supplier / the SMTP server). |
| `totals.delivered / undelivered` | integer | Sent rows with a delivery receipt: DELIVRD or "delivered" = delivered; any other receipt = undelivered. No receipt = neither. |
| `totals.failed` | integer | Rows with status failed. |
| `totals.hard_bounces` | integer | Failed rows flagged hard_bounce (address permanently invalid). |
| `totals.skipped / computed` | integer | Recovery decisions that produced no send, and shadow-mode computed sends. |
| `totals.ms_sum / ms_n` | integer | Latency sum (ms) and count over sent and failed rows that stored one: average = ms_sum / ms_n. |
| `totals.providers` | integer | Distinct providers that sent or failed in the range. |
| `days` | array | One row per day per provider, newest day first: {day (YYYY-MM-DD in tz), provider_id, provider_name, sent, delivered, undelivered, failed, ms_sum, ms_n}. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: channel missing or unknown, from / to not ISO datetimes ending in Z, tz over 64 chars.
- `400` {"error":"from must be before to"}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the plan excludes the reports tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The range is half-open [from, to): a `to` at midnight excludes that day.
- `days` holds one row per day PER PROVIDER; aggregate client-side for a per-day chart.
- delivered / undelivered come from delivery receipts: the SMS supplier callback (DELIVRD) and, for e-mail, only when the sender has a status key or webhook configured (receipt "delivered"). Without receipts, treat `sent` as the terminal success.
- Totals include skipped and computed decisions while `days` only covers sent / failed rows with a provider: they do not reconcile on purpose.
- Shadow and external modes are both counted; there is no mode filter here (use /v1/messaging/logs for row detail).
- Rows keep the provider name at send time: a renamed provider shows its historical name, a null name shows "(deleted provider)".

##### `GET /v1/messaging/email-providers`

**Scope** `integrations.read` - **List email (SMTP) providers**

Lists the account's SMTP senders in creation order with their settings, whether each secret is saved (sending password, delivery-status key, webhook signing secret) and the send counters of the current UTC day and month. Secret values are never in the list; GET /v1/messaging/email-providers/:id/credentials reads them.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000012",
      "name": "Primary SMTP",
      "host": "smtp.example.com",
      "port": 587,
      "username": "outbound-1",
      "from_email": "hello@example.com",
      "from_name": "{shop_name} Support",
      "reply_to": "support@example.com",
      "link_base_url": "https://links.example.com",
      "weight": 3,
      "daily_cap": 5000,
      "monthly_cap": 0,
      "monthly_fee_cents": 2000,
      "enabled": true,
      "status_api_kind": "resend",
      "created_by": "ops@example.com",
      "created_at": "2026-11-01T10:00:00.000Z",
      "updated_at": "2026-11-15T08:30:12.000Z",
      "password_set": true,
      "status_api_key_set": true,
      "webhook_secret_set": false,
      "sent_today": 412,
      "sent_month": 6120
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | E-mail providers of the account, oldest first. |
| `rows[].port` | integer | 465 = implicit TLS; any other port = STARTTLS. |
| `rows[].from_name` | string | May contain {shop_name}, replaced per send. |
| `rows[].weight` | integer | 0..1000 weighted-random pick weight (0 = never picked). |
| `rows[].daily_cap / monthly_cap` | integer | 0 = unlimited. |
| `rows[].monthly_fee_cents` | integer | Fixed monthly cost of the sender, in cents (cost reports). |
| `rows[].status_api_kind` | string\|null | Delivery-status provider ("resend") or null. |
| `rows[].password_set / status_api_key_set / webhook_secret_set` | boolean | A decryptable value is stored for that secret. |
| `rows[].sent_today / sent_month` | integer | Counters of the current UTC day / month. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- password_set is false when no password is stored or the stored value can no longer be decrypted: re-save the password.
- Eligibility for sending = enabled, weight > 0, a password, and under both caps; the list does not compute it.
- owner_email is stripped from the rows.

##### `POST /v1/messaging/email-providers`

**Scope** `integrations.write` - **Create an email (SMTP) provider**

Adds an SMTP sender to the account's e-mail pool with its credentials (password encrypted at rest), sender identity, pick weight, caps, monthly fee and switch. Returns the new id with 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Label, trimmed, 1..120 chars. |
| `host` | string | **yes** | SMTP host, trimmed, 1..255 chars. |
| `port` | integer | **yes** | 1..65535. 465 = implicit TLS; any other port (587) = STARTTLS. |
| `username` | string | **yes** | SMTP login, trimmed, 1..255 chars. |
| `from_email` | string | **yes** | Sender address (valid e-mail, max 255). |
| `password` | string | no | SMTP password, max 1024 chars, encrypted at rest. Optional: without it the provider cannot send and the test answers 422. |
| `from_name` | string; default `""` | no | Sender display name, trimmed, max 120. The literal {shop_name} is replaced by the store name at send time. |
| `reply_to` | string\|null; default `null` | no | Reply-To address (valid e-mail, max 255) or null. |
| `link_base_url` | string\|null; default `null` | no | Base URL (valid URL, max 255) for click / unsubscribe / open-pixel links, or null for the platform default. |
| `weight` | integer; default `1` | no | 0..1000. Weighted-random pick among eligible providers; 0 = never picked. |
| `daily_cap` | integer; default `0` | no | >= 0 sends per UTC day; 0 = unlimited. |
| `monthly_cap` | integer; default `0` | no | >= 0 sends per UTC month; 0 = unlimited. |
| `monthly_fee_cents` | integer; default `0` | no | 0..100000000. Fixed monthly cost of the sender, in cents. |
| `enabled` | boolean; default `true` | no | Whether the picker may choose it. |
| `status_api_kind` | enum: resend\|null | no | Delivery-status provider for e-mail receipts. ACCEPTED BUT NOT STORED on create: set it with PUT afterwards. |
| `status_api_key` | string | no | Read-capable key of the status provider (not the sending password), max 1024, encrypted at rest. ACCEPTED BUT NOT STORED on create: set it with PUT afterwards. |
| `webhook_secret` | string | no | Signing secret of the delivery webhook (whsec_...), max 1024, encrypted at rest. ACCEPTED BUT NOT STORED on create: set it with PUT afterwards. |

**Request body**

```json
{
  "name": "Primary SMTP",
  "host": "smtp.example.com",
  "port": 587,
  "username": "outbound-1",
  "password": "example-smtp-password",
  "from_email": "hello@example.com",
  "from_name": "{shop_name} Support",
  "reply_to": "support@example.com",
  "link_base_url": "https://links.example.com",
  "weight": 3,
  "daily_cap": 5000,
  "monthly_cap": 0,
  "monthly_fee_cents": 2000,
  "enabled": true
}
```

**Response** `201`

```json
{
  "id": "00000000-0000-4000-8000-000000000012"
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | The new provider id (for PUT, DELETE, test, credentials). |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: missing name / host / port / username / from_email, port out of 1..65535, invalid e-mail or URL, weight over 1000, negative cap or fee, status_api_kind other than resend.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Answers 201, not 200.
- password is optional: a provider created without it is listed with password_set false and can neither send nor be tested (test answers 422).
- status_api_kind, status_api_key and webhook_secret pass validation on create but are NOT saved: send them in a PUT after the create.
- No uniqueness on name or host: duplicates are accepted.
- Nothing is verified at creation: call POST /v1/messaging/email-providers/:id/test afterwards.
- Unknown body keys are ignored (the schema is not strict).

##### `PUT /v1/messaging/email-providers/:id`

**Scope** `integrations.write` - **Update an email provider**

Partial update of one SMTP sender of the account: any subset of the creation fields. A secret (password, status_api_key, webhook_secret) set to null or "" is cleared, a string replaces it, an omitted one is kept. Returns {"ok":true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id (not a UUID: 400 "Invalid id"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Label, trimmed, 1..120 chars. |
| `host` | string | no | SMTP host, trimmed, 1..255 chars. |
| `port` | integer | no | 1..65535. 465 = implicit TLS; any other port (587) = STARTTLS. |
| `username` | string | no | SMTP login, trimmed, 1..255 chars. |
| `from_email` | string | no | Sender address (valid e-mail, max 255). |
| `password` | string\|null; default `keep` | no | SMTP password, max 1024 chars, encrypted at rest. null or "" clears it; omitted keeps it. |
| `from_name` | string; default `keep` | no | Sender display name, trimmed, max 120. The literal {shop_name} is replaced by the store name at send time. |
| `reply_to` | string\|null; default `keep` | no | Reply-To address (valid e-mail, max 255) or null. |
| `link_base_url` | string\|null; default `keep` | no | Base URL (valid URL, max 255) for click / unsubscribe / open-pixel links, or null for the platform default. |
| `weight` | integer; default `keep` | no | 0..1000. Weighted-random pick among eligible providers; 0 = never picked. |
| `daily_cap` | integer; default `keep` | no | >= 0 sends per UTC day; 0 = unlimited. |
| `monthly_cap` | integer; default `keep` | no | >= 0 sends per UTC month; 0 = unlimited. |
| `monthly_fee_cents` | integer; default `keep` | no | 0..100000000. Fixed monthly cost of the sender, in cents. |
| `enabled` | boolean; default `keep` | no | Whether the picker may choose it. |
| `status_api_kind` | enum: resend\|null; default `keep` | no | Delivery-status provider for e-mail receipts. null clears it. |
| `status_api_key` | string; default `keep` | no | Read-capable key of the status provider (not the sending password), max 1024, encrypted at rest. "" clears it; omitted keeps it. |
| `webhook_secret` | string; default `keep` | no | Signing secret of the delivery webhook (whsec_...), max 1024, encrypted at rest. "" clears it; omitted keeps it. |

**Request body**

```json
{
  "weight": 5,
  "daily_cap": 8000,
  "status_api_kind": "resend",
  "status_api_key": "re_example_status_key",
  "webhook_secret": "whsec_example"
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"Invalid id"}: :id is not a UUID.
- `400` {"error":"Invalid","details":<zod flatten()>}: a field fails its rule.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: no provider with this id in the account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- An EMPTY body ({}) answers {"ok":true} without touching the database and WITHOUT checking that the id exists.
- password: "" or null CLEARS the password (password_set becomes false and sends stop); omit the key to keep it. Same rule for status_api_key and webhook_secret.
- No default is applied on a partial body: a missing key means keep.
- Lowering daily_cap below sent_today makes the provider ineligible until the next UTC day.

##### `DELETE /v1/messaging/email-providers/:id`

**Scope** `integrations.write` - **Delete an email provider**

Deletes one SMTP sender of the account with its send counters, its memberships in sender ATRIs and its sender rates. Historical send rows keep the provider name they stored. Returns {"ok":true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id. Not pre-validated: a malformed UUID is a 400 from the database cast. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a UUID (database cast error, mapped to 400 before any lookup).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Hard delete, no confirmation, no undo; the stored secrets are gone with it.
- A sender ATRI whose only member was this provider is left with no member and sends nothing until a member is added.
- Analytics and logs keep the historical rows with the name stored at send time.

##### `GET /v1/messaging/email-providers/:id/credentials`

**Scope** `integrations.write` - **Read an email provider's stored secrets (in clear)**

Returns the stored secrets of one SMTP sender, decrypted: the sending password ("" when unset) plus the delivery-status key and the webhook signing secret when they are stored. The list only says whether each is set.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | E-mail provider id of the account. |

**Response**

```json
{
  "password": "example-smtp-password",
  "status_api_key": "re_example_status_key"
}
```

| response field | type | description |
|---|---|---|
| `password` | string | Decrypted sending password, "" when unset. |
| `status_api_key` | string | Present only when stored: the read-capable delivery-status key. |
| `webhook_secret` | string | Present only when stored: the delivery webhook signing secret. |

**Errors**

- `400` {"error":"Invalid id"}: :id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"}: the key lacks integrations.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The answer carries live secrets in clear: it is sent with Cache-Control: no-store and Pragma: no-cache. Never log or cache it.
- status_api_key and webhook_secret are OMITTED (not "") when they are not stored; password is always present ("" when unset).
- Each call that returns at least one value writes one action-log row, action view_secret, naming the fields revealed, never a value.
- This route is the only way to read these values: the lists and general reads carry *_set booleans only.
- Revealing the secrets needs the right to EDIT the sender, not only to read it: an API key needs the write scope of its update route as well as the read scope of this route.

##### `POST /v1/messaging/email-providers/:id/test`

**Scope** `integrations.write` - **Test an email provider (SMTP verify or send)**

Without `to`: opens an SMTP connection with the saved credentials and runs a login check (nothing is sent). With `to`: sends a REAL test e-mail through the provider to that address. Returns the outcome and latency.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id of the account. A malformed UUID is a 400 from the database cast. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `to` | string | no | Recipient e-mail (trimmed, valid e-mail). Present: a real message "[cocoapi] Test email from <name>" is sent; absent: only the SMTP login is verified. |

**Request body**

```json
{
  "to": "ops@example.com"
}
```

**Response**

```json
{
  "mode": "send",
  "ok": true,
  "messageId": "<00000000-0000-4000-8000-000000000051@example.com>",
  "response": "250 2.0.0 OK queued as 4Xk2",
  "ms": 1240
}
```

| response field | type | description |
|---|---|---|
| `mode` | enum: verify\|send | verify = login check only; send = a message was attempted. |
| `ok` | boolean | Login succeeded / message accepted by the SMTP server. |
| `error` | string | Only when ok is false: the SMTP or socket error text. |
| `ms` | integer | Elapsed milliseconds. |
| `messageId` | string | send mode, success: the Message-ID used (<uuid@sender-domain>). |
| `response` | string | send mode, success: first 300 chars of the SMTP server response. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a UUID (database cast error, mapped to 400 before any lookup).
- `400` {"error":"Invalid","details":<zod flatten()>}: `to` is not a valid e-mail.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `422` {"error":"No password saved for this provider"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A failed login or send is a 200 with ok:false: read `ok`.
- The test e-mail is a real delivery to `to`, sent with bulk-mail headers (Precedence: bulk, Auto-Submitted) and From = from_name / from_email with {shop_name} rendered as "Test store".
- Not journaled in the send log and does not bump sent_today / sent_month.
- Timeouts: 15 s connection and greeting, 20 s socket; an unreachable host can take about 15 s to fail.

##### `GET /v1/messaging/logs`

**Scope** `integrations.read` - **List messaging send logs for a channel**

Server-paginated journal of one channel's cart-recovery sends, newest first: provider, template, touch number, cart token, supplier message id, delivery receipt, latency, error, billed units and cost, a MASKED recipient and the customer's 3DS summary. Filterable by status (including the derived delivered / undelivered statuses), by one provider and by a free-text search.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | enum: email\|sms | **yes** | Channel. |
| `status` | enum: sent\|failed\|skipped\|computed\|delivered\|undelivered | no | Filter. delivered / undelivered are derived: status sent plus a delivered (DELIVRD or "delivered") / any other receipt. |
| `q` | string | no | Trimmed, max 200 chars. Contains-match on provider name, template name, error, skip reason, cart token, message id and the RAW recipient (e-mail or E.164 phone). |
| `providerId` | uuid | no | Only the sends of this provider (one sender's own history). |
| `limit` | integer; default `50` | no | 1..10000. |
| `offset` | integer; default `0` | no | 0..1000000. |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000021",
      "created_at": "2026-11-20T11:58:02.112Z",
      "channel": "sms",
      "mode": "external",
      "status": "sent",
      "skip_reason": null,
      "provider_id": "00000000-0000-4000-8000-000000000011",
      "provider_name": "SMS pool US",
      "template_id": "00000000-0000-4000-8000-000000000031",
      "template_name": "SMS 10% (en)",
      "touch_number": 1,
      "cart_token": "c9f1e2d3a4b5",
      "shop_id": "00000000-0000-4000-8000-000000000041",
      "message_id": "mw_7f31a9",
      "delivery_status": "DELIVRD",
      "status_code": 200,
      "ms": 388,
      "error": null,
      "hard_bounce": false,
      "dest_country": "US",
      "billable_units": 1,
      "cost_cents": 0.75,
      "recipient": "+141***100",
      "threeDsSummary": null
    }
  ],
  "total": 2226,
  "limit": 50,
  "offset": 0
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Send rows of the account and channel, newest first. |
| `rows[].mode` | enum: shadow\|external | shadow = computed only, nothing sent. |
| `rows[].status` | enum: computed\|sent\|failed\|skipped | Stored status (delivered / undelivered are derived from delivery_status). |
| `rows[].skip_reason` | string\|null | Why the recovery ladder produced no send (quiet hours, dedupe, minimum cart, unsubscribed...). |
| `rows[].touch_number` | integer | Position in the channel ladder. |
| `rows[].message_id` | string\|null | Supplier / SMTP message id. |
| `rows[].delivery_status` | string\|null | Delivery receipt: SMS supplier code (DELIVRD, UNDELIV, EXPIRED...) or the e-mail provider status ("delivered"...); null without a receipt. |
| `rows[].hard_bounce` | boolean | Failed e-mail whose address is permanently invalid. |
| `rows[].dest_country / billable_units / cost_cents` | string\|null / integer\|null / number\|null | Destination country and units billed for the send, and their cost at the current rate of the sender. |
| `rows[].recipient` | string\|null | MASKED: j***@example.com / +141***100. The raw address never leaves the API. |
| `rows[].threeDsSummary` | object\|null | The customer's 3DS proof inventory {total, ready, used, expired, pending, failed, readyForRebill, authenticationMode none\|single\|double}, null when the send cannot be linked to a customer e-mail. |
| `total` | integer | Rows matching the filters (for paging). |
| `limit / offset` | integer | Echo of the effective paging. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: missing channel, unknown status, q over 200 chars, providerId not a UUID, limit / offset out of range.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- `q` searches the RAW recipient, but the response only ever shows the masked one: you can find jane@example.com yet never read it back.
- The recipient comes from the payload actually sent, else the cart contact (e-mail or E.164 phone): skipped rows still show a masked recipient.
- delivered / undelivered return nothing on a channel without receipts.
- cost_cents is computed at TODAY's sender rate; null means no rate covers the send (never read it as free). dest_country, billable_units and cost_cents are null on a database without the sender cost tables.
- IDs are UUIDs.

##### `GET /v1/messaging/sms-providers`

**Scope** `integrations.read` - **List SMS providers**

Lists the account's SMS suppliers (MessageWhiz) with sender name, weight, caps, monthly fee, switch, whether an API key is saved and the send counters of the current UTC day and month. API keys are not in the list; GET /v1/messaging/sms-providers/:id/credentials reads one.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000011",
      "name": "SMS pool US",
      "supplier": "messagewhiz",
      "sender_name": "DEMO",
      "weight": 1,
      "daily_cap": 0,
      "monthly_cap": 20000,
      "monthly_fee_cents": 0,
      "enabled": true,
      "created_by": "ops@example.com",
      "created_at": "2026-11-01T10:05:00.000Z",
      "updated_at": "2026-11-01T10:05:00.000Z",
      "api_key_set": true,
      "sent_today": 88,
      "sent_month": 1904
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | SMS providers of the account, oldest first. |
| `rows[].supplier` | enum: messagewhiz | Supplier adapter. |
| `rows[].sender_name` | string | Sender id (max 20 chars) sent as `from`. |
| `rows[].monthly_fee_cents` | integer | Fixed monthly cost of the sender, in cents. |
| `rows[].api_key_set` | boolean | A decryptable API key is stored. |
| `rows[].sent_today / sent_month` | integer | Counters of the current UTC day / month. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- api_key_set false with a key saved earlier means the stored value can no longer be decrypted: re-save the key.
- owner_email is stripped from the rows.

##### `POST /v1/messaging/sms-providers`

**Scope** `integrations.write` - **Create an SMS provider**

Adds an SMS supplier account to the account's SMS pool (API key encrypted at rest) with its sender name, pick weight, caps, monthly fee and switch. Returns the new id with 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Label, trimmed, 1..120 chars. |
| `supplier` | enum: messagewhiz; default `messagewhiz` | no | Only messagewhiz exists. |
| `api_key` | string | no | Supplier API key, max 1024, encrypted at rest. Optional: without it every send and the test answer ok:false error "supplier_missing_key". |
| `sender_name` | string | **yes** | Sender id shown to the recipient, trimmed, 1..20 chars. |
| `weight` | integer; default `1` | no | 0..1000; 0 = never picked. |
| `daily_cap` | integer; default `0` | no | >= 0 per UTC day; 0 = unlimited. |
| `monthly_cap` | integer; default `0` | no | >= 0 per UTC month; 0 = unlimited. |
| `monthly_fee_cents` | integer; default `0` | no | 0..100000000. Fixed monthly cost of the sender, in cents. |
| `enabled` | boolean; default `true` | no | Whether the picker may choose it. |

**Request body**

```json
{
  "name": "SMS pool US",
  "supplier": "messagewhiz",
  "api_key": "example-sms-api-key",
  "sender_name": "DEMO",
  "weight": 1,
  "daily_cap": 0,
  "monthly_cap": 20000,
  "monthly_fee_cents": 0,
  "enabled": true
}
```

**Response** `201`

```json
{
  "id": "00000000-0000-4000-8000-000000000011"
}
```

| response field | type | description |
|---|---|---|
| `id` | uuid | The new provider id. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: missing name / sender_name, sender_name over 20 chars, supplier other than messagewhiz, weight over 1000, negative cap or fee.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Answers 201, not 200.
- api_key is optional: without it the provider is created but every send and the test answer ok:false error "supplier_missing_key".
- sender_name is limited to 20 chars here; carriers usually cap alphanumeric sender ids at 11 chars, which the API does not check.
- No uniqueness on name.

##### `PUT /v1/messaging/sms-providers/:id`

**Scope** `integrations.write` - **Update an SMS provider**

Partial update of one SMS provider of the account. `api_key` null or "" clears the stored key, a string replaces it, omitting it keeps it. Returns {"ok":true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id (not a UUID: 400 "Invalid id"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string; default `keep` | no | Label, trimmed, 1..120 chars. |
| `supplier` | enum: messagewhiz; default `keep` | no | Only messagewhiz exists. |
| `api_key` | string\|null; default `keep` | no | Supplier API key, max 1024, encrypted at rest. null or "" clears it; omitted keeps it. |
| `sender_name` | string; default `keep` | no | Sender id shown to the recipient, trimmed, 1..20 chars. |
| `weight` | integer; default `keep` | no | 0..1000; 0 = never picked. |
| `daily_cap` | integer; default `keep` | no | >= 0 per UTC day; 0 = unlimited. |
| `monthly_cap` | integer; default `keep` | no | >= 0 per UTC month; 0 = unlimited. |
| `monthly_fee_cents` | integer; default `keep` | no | 0..100000000. Fixed monthly cost of the sender, in cents. |
| `enabled` | boolean; default `keep` | no | Whether the picker may choose it. |

**Request body**

```json
{
  "enabled": false
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |

**Errors**

- `400` {"error":"Invalid id"}: :id is not a UUID.
- `400` {"error":"Invalid","details":<zod flatten()>}: a field fails its rule.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: no provider with this id in the account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- An empty body ({}) answers {"ok":true} with no database write and no existence check.
- api_key: "" or null CLEARS the key; omit it to keep it.
- No default is applied on a partial body (supplier included): a missing key means keep.

##### `DELETE /v1/messaging/sms-providers/:id`

**Scope** `integrations.write` - **Delete an SMS provider**

Deletes one SMS provider of the account with its send counters, its memberships in sender ATRIs and its sender rates. Returns {"ok":true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id. Not pre-validated: a malformed UUID is a 400 from the database cast. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when a row was deleted. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a UUID (database cast error, mapped to 400 before any lookup).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Hard delete, no undo.
- A sender ATRI whose only member was this provider is left with no member and sends nothing until a member is added.
- Delivery receipts of messages already sent still update their send rows (matched by message id); the provider row is not needed for that.

##### `GET /v1/messaging/sms-providers/:id/credentials`

**Scope** `integrations.write` - **Read an SMS provider's stored API key (in clear)**

Returns the stored supplier API key of one SMS provider, decrypted ("" when unset). The list only carries api_key_set.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | SMS provider id of the account. |

**Response**

```json
{
  "api_key": "example-sms-api-key"
}
```

| response field | type | description |
|---|---|---|
| `api_key` | string | Decrypted supplier API key, "" when unset. |

**Errors**

- `400` {"error":"Invalid id"}: :id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"}: the key lacks integrations.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The answer carries a live secret in clear: it is sent with Cache-Control: no-store and Pragma: no-cache. Never log or cache it.
- A call that returns a non-empty key writes one action-log row, action view_secret, naming the field, never the value.
- This route is the only way to read the key: the list carries api_key_set only.
- Revealing the secrets needs the right to EDIT the SMS provider, not only to read it: an API key needs the write scope of its update route as well as the read scope of this route.

##### `POST /v1/messaging/sms-providers/:id/test`

**Scope** `integrations.write` - **Send a test SMS through a provider**

Sends a REAL SMS ("cocoapi test SMS via <name> (messagewhiz).") to an E.164 number with the provider's saved API key and sender name, and returns the supplier's answer.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Provider id of the account. A malformed UUID is a 400 from the database cast. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `to` | string | **yes** | E.164 phone matching ^\+\d{8,15}$ (for example +12345550100). Trimmed. |

**Request body**

```json
{
  "to": "+12345550100"
}
```

**Response**

```json
{
  "ok": true,
  "messageId": "mw_7f31a9c2",
  "status": 200,
  "responseExcerpt": "{\"message_id\":\"mw_7f31a9c2\",\"status\":\"queued\"}",
  "ms": 412
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Supplier accepted the message (HTTP 2xx). |
| `messageId` | string\|null | Supplier message id. |
| `status` | integer\|null | Supplier HTTP status; null on a network error or a missing key. |
| `error` | string | Only when ok is false: supplier error text, http_<status>, supplier_missing_key or the network error. |
| `responseExcerpt` | string | First 500 chars of the supplier response body. |
| `ms` | integer | Elapsed milliseconds (0 when refused locally for a missing key). |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a UUID (database cast error, mapped to 400 before any lookup).
- `400` {"error":"Invalid","details":<zod flatten()>}: `to` missing or not E.164 ("E.164 phone, e.g. +12345550100").
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"recovery"} when the plan excludes the recovery tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: unknown id or a provider of another account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- This sends a real, billable SMS.
- A provider without a saved API key is NOT a 422: the answer is 200 {"ok":false,"error":"supplier_missing_key","status":null}.
- Not journaled in the send log, no counter bump, and no delivery callback URL is passed: no receipt ever arrives for it.
- 15 s supplier timeout.

##### `GET /v1/sender-costs`

**Scope** `integrations.read` - **Read messaging costs for a range**

The two messaging costs of a time range, kept apart on purpose: unitCostCents is attached to sends and belongs inside net; monthlyFeeCents is the monthly subscription of the enabled senders, attached to nothing, and takes its own line below net.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 date-time, UTC Z form) | **yes** | Range start, inclusive (for example 2026-11-01T00:00:00Z). An offset such as +02:00 is refused. |
| `to` | string (ISO 8601 date-time, UTC Z form) | **yes** | Range end, exclusive. Must be after from and at most 400 days later. |

**Response**

```json
{
  "unitCostCents": 4210,
  "pricedSends": 1480,
  "unpricedSends": 12,
  "billableUnits": 1611,
  "monthlyFeeCents": 2500
}
```

| response field | type | description |
|---|---|---|
| `unitCostCents` | integer \| null | Sum of per-send costs in US cents (rounded), at today's rates; null when no sent message in the range had a matching rate. |
| `pricedSends` | integer | Sent external messages that a rate covered. |
| `unpricedSends` | integer | Sent external messages that no rate covered (excluded from unitCostCents, not counted as free). |
| `billableUnits` | integer | Total billable units (SMS segments; 1 per e-mail) of the sent external messages. |
| `monthlyFeeCents` | integer | Sum of monthly_fee_cents of the enabled e-mail and SMS senders, today; not prorated to the range. |

**Errors**

- `400` Invalid range (from or to missing or not an ISO date-time); Range start must be before its end; or Range cannot exceed 400 days.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Only status=sent, mode=external sends cost money: a refused send gave its quota slot back and a skipped one never reached a provider.
- Before the rate storage exists every figure is 0 and unitCostCents is null.

##### `GET /v1/sender-rates`

**Scope** `integrations.read` - **List sender rates**

The account's per-country unit costs of its senders. A row with country null is the catch-all.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | string (email\|sms) | no | Only rates of this provider kind. Omitted returns both. |

**Response**

```json
{
  "rates": [
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "provider_kind": "sms",
      "provider_id": "44444444-4444-4444-8444-444444444444",
      "country": null,
      "unit_cost_cents": 2.5,
      "currency": "USD"
    },
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "provider_kind": "sms",
      "provider_id": "44444444-4444-4444-8444-444444444444",
      "country": "US",
      "unit_cost_cents": 0.65,
      "currency": "USD"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rates[]` | object[] | Ordered by provider_kind, provider_id, catch-all first: id, provider_kind (email\|sms), provider_id, country (ISO alpha-2 upper case, or null), unit_cost_cents (decimal number of US cents, up to 4 decimals), currency (USD). [] before the rate storage exists. |

**Errors**

- `400` Invalid channel.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- unit_cost_cents is per SEGMENT for SMS and per send for e-mail, and it is a decimal: a fraction of a cent per segment is normal.

##### `PUT /v1/sender-rates`

**Scope** `integrations.write` - **Replace sender rates**

Replace every rate of ONE sender (delete and insert in one transaction). Costs are recomputed at read time, so correcting a rate corrects the reported history. Returns the whole grid of that channel.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string (email\|sms) | **yes** | Provider kind of the sender. |
| `providerId` | uuid | **yes** | The sender (e-mail or SMS provider) of this account whose grid is replaced. |
| `rates` | array (max 300) | **yes** | Whole grid; one row per country (case-insensitive), at most one catch-all. [] removes every rate of the sender. |
| `rates[].country` | string (2 letters) \| null | no | ISO 3166-1 alpha-2 destination country, stored upper case; null or omitted = catch-all. E-mail accepts only the catch-all. |
| `rates[].unitCostCents` | number (0..100000, multiple of 0.0001) | **yes** | Cost in US cents per SMS segment or per e-mail, up to 4 decimals. |
| `rates[].currency` | string (USD); default `USD` | no | Only 'USD' is accepted. |

**Request body**

```json
{
  "kind": "sms",
  "providerId": "44444444-4444-4444-8444-444444444444",
  "rates": [
    {
      "country": "US",
      "unitCostCents": 0.65
    },
    {
      "country": null,
      "unitCostCents": 2.5
    }
  ]
}
```

**Response**

```json
{
  "rates": [
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "provider_kind": "sms",
      "provider_id": "44444444-4444-4444-8444-444444444444",
      "country": null,
      "unit_cost_cents": 2.5,
      "currency": "USD"
    },
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "provider_kind": "sms",
      "provider_id": "44444444-4444-4444-8444-444444444444",
      "country": "US",
      "unit_cost_cents": 0.65,
      "currency": "USD"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rates[]` | object[] | Every rate of the channel (kind) for the account, same fields as GET /v1/sender-rates. |

**Errors**

- `400` Invalid rates (details: zod flatten; strict body; "One rate per country"); or An e-mail has no destination country: use the single catch-all rate.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `404` Sender not found. (providerId is not a sender of this account for that kind)
- `503` Authentication scope is temporarily unavailable. Sender rates are not available on this database yet (migration pending).

**Gotchas**

- A send that no rate covers reports a NULL cost, never zero.
- USD only: the report sums these as US cents and there is no exchange rate, so any other currency is refused.
- A country rate wins over the catch-all for the same sender.

#### Sender ATRIs

The routing pools of the messaging senders.

##### `GET /v1/sender-atris`

**Scope** `integrations.read` - **List sender ATRIs**

The account's sender ATRIs (pools of e-mail or SMS senders used by cart recovery), each with its ordered members, plus the account's senders to choose from and the rate grid. One call because the editor needs all three.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | string (email\|sms) | no | Limits atris, senders and rates to one channel. Omitted returns both. |

**Response**

```json
{
  "atris": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "owner_email": "owner@example.com",
      "channel": "email",
      "name": "Email senders",
      "description": null,
      "active": true,
      "is_default": true,
      "created_at": "2026-11-04T10:00:00.000Z",
      "updated_at": "2026-11-20T09:12:00.000Z",
      "members": [
        {
          "atri_id": "11111111-1111-4111-8111-111111111111",
          "sender_id": "22222222-2222-4222-8222-222222222222",
          "position": 0,
          "active": true,
          "weight": 100,
          "sender_name": "Primary SMTP",
          "sender_enabled": true,
          "monthly_fee_cents": 2500,
          "daily_cap": 0,
          "monthly_cap": 50000,
          "credential_set": true,
          "sent_today": 41,
          "sent_month": 812
        }
      ]
    }
  ],
  "senders": {
    "email": [
      {
        "id": "22222222-2222-4222-8222-222222222222",
        "name": "Primary SMTP",
        "host": "smtp.example.com",
        "port": 587,
        "username": "mailer",
        "from_email": "shop@example.com",
        "from_name": "Example Shop",
        "weight": 100,
        "enabled": true,
        "daily_cap": 0,
        "monthly_cap": 50000,
        "monthly_fee_cents": 2500,
        "password_set": true,
        "status_api_key_set": false,
        "webhook_secret_set": false,
        "sent_today": 41,
        "sent_month": 812
      }
    ],
    "sms": []
  },
  "rates": [
    {
      "id": "33333333-3333-4333-8333-333333333333",
      "provider_kind": "email",
      "provider_id": "22222222-2222-4222-8222-222222222222",
      "country": null,
      "unit_cost_cents": 0.05,
      "currency": "USD"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `atris[]` | object[] | Sender ATRIs ordered by name: id, owner_email, channel, name, description, active, is_default, created_at, updated_at, members[] (same member fields as POST /v1/sender-atris). [] before the sender ATRI storage exists. |
| `senders.email[]` | object[] | The account's e-mail providers, same shape as GET /v1/messaging/email-providers: provider columns with password_set, status_api_key_set, webhook_secret_set booleans instead of secrets, plus sent_today and sent_month. [] when channel=sms. |
| `senders.sms[]` | object[] | The account's SMS providers, same shape as GET /v1/messaging/sms-providers (api_key_set instead of the key, sent_today, sent_month). [] when channel=email. |
| `rates[]` | object[] | Rate grid rows: id, provider_kind, provider_id, country (null = catch-all), unit_cost_cents (decimal, US cents), currency (USD). |

**Errors**

- `400` Invalid channel.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Member weight is the share of FIRST picks; the failover order is position. Two different orders on purpose.
- Daily and monthly caps belong to the sender, not to the member; they are echoed on each member read-only. A sender at its cap is skipped.
- credential_set false means the sender cannot send at all.
- An account with NO ATRI for a channel still dispatches through its flat sender list. An EMPTY ATRI sends nothing.

##### `POST /v1/sender-atris`

**Scope** `integrations.write` - **Create a sender ATRI**

Create a sender ATRI for one channel. members may be sent with it and are written in the same transaction, so an ATRI is never half saved. It is not the channel default until POST /v1/sender-atris/:id/default.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `channel` | string (email\|sms) | **yes** | Channel of the ATRI; fixed after creation. |
| `name` | string (1..128, trimmed) | **yes** | Name, unique per account and channel (case-insensitive). |
| `description` | string (max 1024) \| null | no | Free text. |
| `active` | boolean; default `true` | no | An inactive ATRI is never used for dispatch and cannot become the default. |
| `members` | array (max 200) | no | Whole ordered membership; sender ids must be unique. Every sender must belong to this account and to the ATRI channel (email providers for email, SMS providers for sms). |
| `members[].senderId` | uuid | **yes** | Sender id: an email provider or SMS provider of this account, from the senders lists of GET /v1/sender-atris or /v1/messaging/email-providers and /v1/messaging/sms-providers. |
| `members[].position` | integer (0..1000) | **yes** | Failover order: after the first pick, the remaining senders are tried by ascending position. |
| `members[].active` | boolean; default `true` | no | Inactive members are never tried. |
| `members[].weight` | number (0..100); default `100` | no | Share of first picks among active members under their caps. 0 makes the member a backup: never drawn first, still tried in the failover order. |

**Request body**

```json
{
  "channel": "sms",
  "name": "US senders",
  "active": true,
  "members": [
    {
      "senderId": "22222222-2222-4222-8222-222222222222",
      "position": 0,
      "active": true,
      "weight": 100
    },
    {
      "senderId": "44444444-4444-4444-8444-444444444444",
      "position": 1,
      "weight": 0
    }
  ]
}
```

**Response** `201`

```json
{
  "atri": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "channel": "sms",
    "name": "US senders",
    "description": null,
    "active": true,
    "is_default": false,
    "created_at": "2026-11-04T10:00:00.000Z",
    "updated_at": "2026-11-20T09:12:00.000Z",
    "members": [
      {
        "atri_id": "11111111-1111-4111-8111-111111111111",
        "sender_id": "22222222-2222-4222-8222-222222222222",
        "position": 0,
        "active": true,
        "weight": 100,
        "sender_name": "Primary SMTP",
        "sender_enabled": true,
        "monthly_fee_cents": 2500,
        "daily_cap": 0,
        "monthly_cap": 50000,
        "credential_set": true,
        "sent_today": 41,
        "sent_month": 812
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The sender ATRI: id, owner_email, channel (email\|sms), name, description, active, is_default, created_at, updated_at, members[]. |
| `atri.members[]` | object[] | Ordered by position then sender_id: atri_id, sender_id, position, active, weight (0..100), sender_name, sender_enabled, monthly_fee_cents, daily_cap, monthly_cap (0 = no cap; read from the sender itself), credential_set (false when the sender has no usable credential), sent_today, sent_month. |

**Errors**

- `400` Invalid sender ATRI (details: zod flatten; unknown keys are refused, duplicate senderId gives "Duplicate sender"); or Choose senders from this account and channel (a member sender of another account or channel).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `409` A record with these details already exists. (another ATRI of this channel has the same name)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A member with no weight defaults to 100, never 0.
- Inside an ATRI, member weight 0 means BACKUP: never drawn first, still tried when the senders before it refuse.
- The body is strict: an unknown key answers 400.

##### `PATCH /v1/sender-atris/:id`

**Scope** `integrations.write` - **Update a sender ATRI**

Change name, description and active. Sending members replaces the whole membership in the same transaction. The channel cannot change.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sender ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string (1..128, trimmed) | no | New name, unique per account and channel. |
| `description` | string (max 1024) \| null | no | New description; null clears it; omitted keeps it. |
| `active` | boolean | no | Activate or deactivate. Deactivating the default leaves it flagged default but unused for dispatch. |
| `members` | array (max 200) | no | Whole ordered membership; sender ids must be unique. Every sender must belong to this account and to the ATRI channel (email providers for email, SMS providers for sms). |
| `members[].senderId` | uuid | **yes** | Sender id: an email provider or SMS provider of this account, from the senders lists of GET /v1/sender-atris or /v1/messaging/email-providers and /v1/messaging/sms-providers. |
| `members[].position` | integer (0..1000) | **yes** | Failover order: after the first pick, the remaining senders are tried by ascending position. |
| `members[].active` | boolean; default `true` | no | Inactive members are never tried. |
| `members[].weight` | number (0..100); default `100` | no | Share of first picks among active members under their caps. 0 makes the member a backup: never drawn first, still tried in the failover order. |

**Request body**

```json
{
  "name": "US senders",
  "active": false
}
```

**Response**

```json
{
  "atri": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "channel": "email",
    "name": "Email senders",
    "description": null,
    "active": false,
    "is_default": true,
    "created_at": "2026-11-04T10:00:00.000Z",
    "updated_at": "2026-11-20T09:12:00.000Z",
    "members": [
      {
        "atri_id": "11111111-1111-4111-8111-111111111111",
        "sender_id": "22222222-2222-4222-8222-222222222222",
        "position": 0,
        "active": true,
        "weight": 100,
        "sender_name": "Primary SMTP",
        "sender_enabled": true,
        "monthly_fee_cents": 2500,
        "daily_cap": 0,
        "monthly_cap": 50000,
        "credential_set": true,
        "sent_today": 41,
        "sent_month": 812
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The sender ATRI: id, owner_email, channel (email\|sms), name, description, active, is_default, created_at, updated_at, members[]. |
| `atri.members[]` | object[] | Ordered by position then sender_id: atri_id, sender_id, position, active, weight (0..100), sender_name, sender_enabled, monthly_fee_cents, daily_cap, monthly_cap (0 = no cap; read from the sender itself), credential_set (false when the sender has no usable credential), sent_today, sent_month. |

**Errors**

- `400` Invalid sender ATRI (details: zod flatten; strict body); or Choose senders from this account and channel (a member sender of another account or channel).
- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `404` Sender ATRI not found.
- `409` A record with these details already exists. (name already used in this channel)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- members is a REPLACE, not a merge: omit it to leave the membership alone; [] empties the ATRI, and an empty ATRI sends nothing.

##### `DELETE /v1/sender-atris/:id`

**Scope** `integrations.write` - **Delete a sender ATRI**

Delete an ATRI that is neither its channel default nor referenced by a recovery profile. Answers 204 with no body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sender ATRI id. |

**Response** `204`

No example body: see the purpose above for what the response carries.

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `404` Sender ATRI not found.
- `409` This ATRI is in use. Deactivate it or select another one first. (it is the channel default, or a recovery profile uses it)
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Refusing to delete the default is deliberate: a channel with no ATRI falls back to the flat sender list, and a delete must not silently change routing. Make another ATRI the default first.

##### `POST /v1/sender-atris/:id/default`

**Scope** `integrations.write` - **Set the default sender ATRI**

Make this ATRI its channel's default: what a store dispatches through when its recovery profile names no ATRI. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sender ATRI id; it must be active. |

**Response**

```json
{
  "ok": true,
  "is_default": true
}
```

**Errors**

- `400` Activate the ATRI first.
- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `404` Sender ATRI not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- The previous default of the same channel is cleared in the same transaction; there is at most one default per channel.

##### `PUT /v1/sender-atris/:id/members`

**Scope** `integrations.write` - **Replace sender ATRI members**

Replace the ordered membership of one ATRI (delete and insert in one transaction, so a failed save changes nothing). position is the failover order, weight the share of first picks.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sender ATRI id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `members` | array (max 200) | **yes** | Whole ordered membership, unique sender ids; [] empties the ATRI (it then sends nothing). |
| `members[].senderId` | uuid | **yes** | Sender id: an email provider or SMS provider of this account, from the senders lists of GET /v1/sender-atris or /v1/messaging/email-providers and /v1/messaging/sms-providers. |
| `members[].position` | integer (0..1000) | **yes** | Failover order: after the first pick, the remaining senders are tried by ascending position. |
| `members[].active` | boolean; default `true` | no | Inactive members are never tried. |
| `members[].weight` | number (0..100); default `100` | no | Share of first picks among active members under their caps. 0 makes the member a backup: never drawn first, still tried in the failover order. |

**Request body**

```json
{
  "members": [
    {
      "senderId": "22222222-2222-4222-8222-222222222222",
      "position": 0,
      "active": true,
      "weight": 60
    },
    {
      "senderId": "44444444-4444-4444-8444-444444444444",
      "position": 1,
      "active": true,
      "weight": 40
    }
  ]
}
```

**Response**

```json
{
  "atri": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "channel": "email",
    "name": "Email senders",
    "description": null,
    "active": true,
    "is_default": true,
    "created_at": "2026-11-04T10:00:00.000Z",
    "updated_at": "2026-11-20T09:12:00.000Z",
    "members": [
      {
        "atri_id": "11111111-1111-4111-8111-111111111111",
        "sender_id": "22222222-2222-4222-8222-222222222222",
        "position": 0,
        "active": true,
        "weight": 100,
        "sender_name": "Primary SMTP",
        "sender_enabled": true,
        "monthly_fee_cents": 2500,
        "daily_cap": 0,
        "monthly_cap": 50000,
        "credential_set": true,
        "sent_today": 41,
        "sent_month": 812
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `atri` | object | The sender ATRI: id, owner_email, channel (email\|sms), name, description, active, is_default, created_at, updated_at, members[]. |
| `atri.members[]` | object[] | Ordered by position then sender_id: atri_id, sender_id, position, active, weight (0..100), sender_name, sender_enabled, monthly_fee_cents, daily_cap, monthly_cap (0 = no cap; read from the sender itself), credential_set (false when the sender has no usable credential), sent_today, sent_month. |

**Errors**

- `400` Invalid members (details: zod flatten; strict body; "Duplicate sender"); or Choose senders from this account and channel (a member sender of another account or channel).
- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module recovery).
- `404` Sender ATRI not found.
- `503` Authentication scope is temporarily unavailable. Sender ATRIs are not available on this database yet (migration pending).

**Gotchas**

- An empty list is authoritative: the channel stops sending through this ATRI instead of falling back to the flat sender list.

### Headless checkout

The storefront runtime that a merchant's own front end, or the embedded iframe, calls with an API key of the checkout's account: sessions, entry, orders, the flow runtime and the wallet and wire legs.

#### Embedded (iframe) checkout

Open an embedded checkout session from your server, then load its URL in an iframe.

##### `POST /v5/standalone/iframe-session`

**Scope** `charges.write` - **Create an embedded (iframe) checkout session**

Creates the private URL of an embedded (iframe) card checkout for one buyer, from your server; creating the session never charges. The whole flow: (1) in the dashboard, Commerce > Checkouts > Add > Add iframe checkout, set its products, prices, currency, payment route and verified serving domain, add the exact HTTPS origin of every website that will embed it under Allowed origins (settings.presentation.allowedOrigins, up to 20; POST /v1/checkouts/standalone or PATCH /v1/checkouts/standalone/:id with settings.presentation.mode iframe does the same through the API), then publish it (POST /v1/checkouts/standalone/:id/publish through the API); (2) when a buyer reaches your payment step, your server calls this route with an API key of the checkout's account, the checkout id, its domain and slug, the embedding page's origin (parentOrigin) and the buyer's details (prefill); (3) your page sets the returned url as the src of an iframe (allow="payment"), and listens to postMessage events whose event.origin equals the returned origin and whose event.source is that iframe: kontrol:iframe:ready, kontrol:iframe:resize (height) and kontrol:iframe:payment (status approved or pending, orderId, amountMinor, currency, isTest); the buyer types the card and submits inside the frame, 3-D Secure runs there too; (4) the url expires 30 minutes after creation (expiresAt): create a new session for a new visit, never while a payment is pending; (5) before fulfilling, your server verifies the order with Kontrol: the orderId of the payment message is the order id the charge is recorded with, so POST /v1/refund/search with {orderId} (exact match) or GET /v1/transactions?q=<orderId> returns the transaction, whose status must be approved with the expected amount and currency; GET /v1/transactions/:id/details then gives the full record. A browser message alone never proves payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Active published standalone checkout of the key's account, configured with presentation.mode iframe (created in Commerce > Checkouts > Add iframe checkout). |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Lowercase verified serving hostname of the published checkout, no scheme, path or port. |
| `slug` | string, ^[a-z0-9][a-z0-9-]{0,59}$ | **yes** | Published checkout slug on that host; must resolve to checkoutId. |
| `parentOrigin` | string | **yes** | Exact bare HTTPS origin of the embedding website (https://host, no path, port syntax beyond the origin, credentials or trailing slash). Must be listed in the published presentation.allowedOrigins. |
| `rawQuery` | string <= 8192 | no | Checkout link query without the leading "?", same signed standalone-link contract as an entry (sig, kt and the documented parameters). Customer and card values are never query parameters. |
| `prefill` | object of strings; default `{}` | **yes** | Customer prefill. Allowed keys only: email (<= 255, valid e-mail), first_name, last_name, city, state (<= 120), address, address2 (<= 255), postal_code, phone (<= 32), shipping_country (two uppercase letters). 164, +[1-9] then 7 to 14 digits); state is also required for US, CA and FR. Empty strings count as absent. Over 8192 bytes answers 413. An unknown key answers 400. |
| `prefill.email` | string <= 255 | **yes** | Buyer e-mail (a valid address). |
| `prefill.first_name` | string | **yes** | Buyer first name. |
| `prefill.last_name` | string | **yes** | Buyer last name. |
| `prefill.address` | string <= 255 | **yes** | Street address. |
| `prefill.address2` | string <= 255 | no | Second address line. |
| `prefill.city` | string <= 120 | **yes** | City. |
| `prefill.state` | string <= 120 | no | State or province; required when shipping_country is US, CA or FR. |
| `prefill.postal_code` | string | **yes** | Postal code. |
| `prefill.phone` | string <= 32 | **yes** | Phone in E.164 (+ then 8 to 15 digits). |
| `prefill.shipping_country` | string (2 uppercase letters) | **yes** | Delivery country; must be offered by the checkout and the offer. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "pay.example.com",
  "slug": "embedded-payment",
  "parentOrigin": "https://www.example.com",
  "rawQuery": "",
  "prefill": {
    "email": "buyer@example.com",
    "first_name": "Alex",
    "last_name": "Taylor",
    "address": "100 Example Street",
    "city": "New York",
    "state": "NY",
    "postal_code": "10001",
    "shipping_country": "US",
    "phone": "+12125550100"
  }
}
```

**Response** `200`

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "url": "https://pay.example.com/embed/11111111-1111-4111-8111-111111111111?session=SHORT_LIVED_CAPABILITY",
  "origin": "https://pay.example.com",
  "expiresAt": "2026-11-17T12:30:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `checkoutId` | uuid | Checkout bound to the session. |
| `url` | string | Private HTTPS iframe source https://<domain>/embed/<checkoutId>?session=<capability>. The signed capability carries checkout, account, host, parent origin, buyer session token and expiry, never customer or card data. Do not log or share it. |
| `origin` | string | https://<domain>: the expected postMessage event.origin. Also verify event.source against your iframe.contentWindow. |
| `expiresAt` | string | ISO expiry of the capability (30 minutes after creation). |

**Errors**

- `400` {"error":"Unknown customer prefill field"}, {"error":"Invalid customer email"}, {"error":"Invalid customer country"}, or a rawQuery refusal ({"error":"Unknown parameter"}, "Duplicate parameter", "Malformed parameter encoding", "Customer prefill requires POST" and the other checkout-parameter refusals). Malformed JSON body.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`. An invalid parentOrigin, a non-string prefill value or an unknown top-level key falls in this case.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Website is not allowed to embed this checkout"}: presentation.mode is not iframe or parentOrigin is not allowlisted. {"error":"Invalid checkout signature"}: rawQuery commercial parameters without a valid signature. {"error":"Offer ownership conflicts with this flow"}.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Checkout unavailable"} also when the slug does not resolve to this checkout and account; {"error":"Checkout not found"}, {"error":"Offer unavailable"}, {"error":"A valid flow link is required"}, {"error":"Flow link unavailable"} from the entry resolution.
- `413` {"error":"Prefill exceeds the limit"}: prefill over 8192 bytes. {"error":"Request body is too large"}: body over 32768 bytes.
- `422` "Missing iframe prefill: <field>", "Iframe phone must use international E.164 format", "Invalid iframe delivery country", "Iframe delivery country is not supported by this checkout" (or "... by this offer"), "Iframe checkout configuration is incomplete" (published settings fail validation), "Iframe checkout cannot change checkout at entry", "Iframe entry must be a checkout node", "Iframe checkout requires a non-empty product selection", "Use a full checkout for subscription offers", and the live catalog refusals ("Product <n> is unavailable for this account", "Add at least one product"...).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.
- `503` {"error":"Iframe checkout is unavailable"}: the session signing secret is not configured. {"error":"Iframe session unavailable"}: no buyer session cookie was produced.

**Gotchas**

- The buyer must enter the card and explicitly submit inside the iframe. Loading the frame and postMessage never charge.
- No third-party cookie dependence: a narrowly scoped same-origin adapter carries the signed session capability to the existing native controller/server actions. Payment amounts, eligibility, idempotency and 3DS remain server-authoritative.
- This is a one-time card presentation. A required consent/subscription block cannot be silently hidden; use a full checkout for those documents. Browser-hosted Stripe choices and wallets are not shown; configure a native card route.
- Iframe response CSP allows only the signed parent origin. Opening a customer URL, receiving an onload or a browser completion event never proves approval.
- The frame emits kontrol:iframe:ready, kontrol:iframe:resize and kontrol:iframe:payment. Approved carries server-verified orderId, amountMinor, currency and isTest; pending means continue observation, not retry payment. Decline remains in the frame. Confirm the order server-side before fulfillment (step 5 above).
- The issued src is stripped from the displayed frame URL before loading native pixels. Retain it privately in the parent to recreate the same frame; do not create a new session while a payment is ambiguous.
- No price or product authority comes from unsigned query parameters. rawQuery uses the same signed standalone-link contract.
- The prefill is validated before the key is checked: a malformed prefill answers 400/413/422 even with a wrong key.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. A 429 is returned before anything runs; resend after the window.
- Full implementation guide: the Embedded card checkout guide of the dashboard (Help > Integration guides > iframe checkout) and the test parent page /examples/iframe-checkout.html on the dashboard origin.
- One-time card payments only: subscription offers, order bumps, consent checkboxes and pre-authorization offers need a full checkout, and the payment route must support native card submission (NMI, Convesio card or Stripe S2S).
- Do not accept the checkout id, parentOrigin, prices or products from the browser: decide them on your server for the authenticated buyer and cart.

#### Store sessions and entry

Open or resume the checkout session of a store cart and enter the checkout.

##### `POST /v5/store/entry`

**Scope** `charges.write` - **Create or refresh store checkout entry**

Internal server admission before checkout HTML/pixels. Independently authorizes the current routed shop, cart, checkout and host, captures attribution and pins its flow. An optional signed first-document bootstrap admits a preissued HttpOnly cookie during the same freshly priced render, avoiding a second browser entry/render round trip. This does not charge a payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string (uuid) | **yes** | Exact checkout selected by the authoritative cart assignment; must belong to the key's account. |
| `storeId` | string (uuid) | **yes** | Verified account-owned shop whose exact cart is admitted. |
| `domain` | string | **yes** | Lowercase verified serving hostname, max 253 characters, no spaces, slash, @, ?, #, backslash or colon (else 400 "Invalid checkout host"). |
| `cartToken` | string | **yes** | Current cart token, 1-512 characters. Never a payment credential. |
| `checkoutPath` | string | **yes** | Exact local pathname /checkout/<token> without query or fragment (must match ^/checkout/[^?#]+$), max 12000 characters. |
| `rawQuery` | string | **yes** | Original URL query without leading question mark, at most 8192 characters. Used for allowed acquisition/affiliate attribution. |
| `landingPageId` | string (uuid) | no | Optional unique published landing entry belonging to the pinned flow. |
| `landingFlowId` | string (uuid) | no | Optional exact flow for landingPageId; requires landingPageId (400 otherwise). Restricted to the same account, published flow, authorized checkout and domain; a store cart keeps its pinned flow. |
| `bootstrap` | object | no | Optional signed first-document bootstrap (strict object). When present the incoming session cookie is ignored and a new session is always inserted; an invalid, expired or replayed proof creates nothing. |
| `bootstrap.token` | string | **yes** | Exactly 43 base64url characters. Must match the storefront-signed __Host-kontrol_flow_scope cookie of the request. Reusing a token answers 409. |
| `bootstrap.issuedAt` | integer | **yes** | Safe integer, UTC epoch milliseconds; not more than 5 seconds in the future and within the proof's maximum age. |
| `bootstrap.signature` | string | **yes** | 64 lowercase hexadecimal characters: HMAC-SHA256 signed with the API key sent on this request. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | no | Optional __Host-kontrol_flow (existing session, reused only for the same checkout, store and cart with no landing page and an empty rawQuery), __Host-kontrol_attribution (an existing attribution token, used when exactly one is present) and, with bootstrap, the __Host-kontrol_flow_scope cookie the proof is checked against. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "checkout.example",
  "cartToken": "existing-cart-token",
  "checkoutPath": "/checkout/existing-token",
  "rawQuery": "utm_source=campaign",
  "storeId": "22222222-2222-4222-8222-222222222222"
}
```

**Response** `200`

```json
{
  "ok": true,
  "flow": false
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | True only after the admission transaction commits successfully. |
| `flow` | boolean | Whether this admitted session has an enabled pinned flow. Old carts retain their original immutable assignment. |
| `inline` | boolean | Present and true only after successful signed bootstrap admission. Absent for ordinary entry calls. |
| `pixels` | array | Inline bootstrap only: public pixel recipients resolved from the verified account and captured affiliate owner. No provider credentials. |
| `tracking` | object | Inline bootstrap only: allowlisted public acquisition parameters from the captured attribution snapshot. No private session configuration or customer information. |
| `Set-Cookie` | header | Host-only Secure HttpOnly SameSite=Lax session cookie and attribution cookie when produced, emitted only after commit. Navigation-scope hints are signed and delivered locally by the storefront; the API never signs or overwrites that hint. |

**Errors**

- `400` {"error":"Invalid entry."} for an invalid body (strict; landingFlowId without landingPageId; malformed bootstrap); {"error":"Invalid checkout host"} for a malformed domain.
- `401` {"error":"Charge authentication required"} when no key is sent; {"error":"Invalid API key"} for an unknown or deactivated key or a key without an owner.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"Invalid entry bootstrap."} when the bootstrap proof does not verify. {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Forbidden"} for a crawler User-Agent.
- `404` {"error":"Cart not found."} when the checkout, verified store, cart, owner, host or pinned route does not match.
- `409` {"error":"This cart has already been paid. Open the order confirmation."} when the same store and cart token have an approved order in the last 24 hours; {"error":"Store flow does not match its pinned checkout."}; {"error":"Entry bootstrap already used."}. An existing session is never rebound or reset.
- `429` Per-IP rate limit (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database or transaction failure; nothing is committed and no cookie is sent.
- `503` {"error":"Server busy, retry"} with Retry-After: 1, or the database is unreachable.

**Gotchas**

- This is private server transport, not a replacement for supported external checkout links or charge APIs. No payment is initiated.
- The account is the checkout's (the key must belong to it). Cart pricing is freshly resolved before admission; no shared authority, amount or cart cache is introduced.
- Omitting bootstrap preserves the existing response and compatible-session reuse. Supplying bootstrap ignores the incoming candidate session cookie and always performs a unique insert; replay/collision rolls back with 409 rather than upserting.
- The transaction verifies current shop, checkout, account and cart pin. Its opaque flow-read evidence is scoped to that live transaction and exact account/checkout/store/cart/domain only; it cannot be serialized or reused elsewhere.
- The checkout, flow and entry landing may have only one affiliate owner; resolved asset ownership precedes attribution capture. URL/cookie values cannot override it.
- Ordinary entry applies Set-Cookie and uses a clean same-origin 303. First-document bootstrap renders the same fresh cart after admission, then delivers any attribution cookie using the separate encrypted same-origin browser POST /api/v5/store-entry. kt still takes the clean redirect path before pixels.
- The signed __Host-kontrol_flow_scope cookie is created locally by the storefront and is bound to its host, flow token and checkout-path hash. A different valid path may cause a new token reservation, but a cookie or signature alone never authorizes a session or charge.
- Public landing links may use /funnel/<pageId>?flow=<flowId> to disambiguate a reused page. The storefront reads only current published versions and forwards both IDs through private transport, removing flow from tracking. An ambiguous unscoped link fails closed. Historical revisions, foreign or archived flows and mismatched cart pins are never selected.
- A cart with an approved order (same store and cart token) in the last 24 hours is refused with 409 before any session is created; send the buyer to the order confirmation instead.
- Not a client endpoint: buyer-facing storefront runtime called by the storefront server.

##### `POST /v5/store/session`

**Scope** `charges.write` - **Read safe store entry bootstrap**

Storefront server check: does the buyer's __Host-kontrol_flow cookie name an active, unexpired session of this checkout on this domain? Returns whether a flow is pinned, whether the card may be stored for post-sell offers, the public pixel recipients and the public tracking snapshot. Never returns cookie tokens, session ids, attribution secrets or gateway credentials.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string (uuid) | **yes** | A checkout of the key's account; must be the checkout of the cookie session. |
| `domain` | string | **yes** | Lowercase verified serving domain, max 253 characters, no spaces, slash, @, ?, #, backslash or colon (else 400 "Invalid checkout host"); must match the host-bound session. |
| `storeId` | string (uuid) | no | Optional verified store pin, sent together with cartToken (one without the other is a 400). The pair is authorized independently and must match the cookie session configuration. |
| `cartToken` | string | no | Optional exact cart token, 1 to 4096 characters, sent together with storeId. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | no | The buyer's opaque __Host-kontrol_flow session cookie, forwarded by the storefront server. Without it (or with an expired one, or one of another checkout or store pin) the answer is active:false. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "checkout.example"
}
```

**Response** `200`

```json
{
  "active": true,
  "flow": true,
  "storesCard": true,
  "pixels": [],
  "tracking": {}
}
```

| response field | type | description |
|---|---|---|
| `active` | boolean | True when the cookie names an unexpired session of this checkout (and of the supplied store/cart pin). When false the reply is exactly {active:false, flow:false, pixels:[]}. |
| `flow` | boolean | True when the session runs a pinned flow. |
| `storesCard` | boolean \| absent | True when the pinned flow version has post-sell steps, so the card may be saved for one-click offers. The checkout must then show the card-storage notice and send commerce.cardStorageConsent with the order. Presentation metadata only, never payment authority. False without a flow or without post-sell steps. Absent when active is false. |
| `pixels` | array | Public pixel recipients resolved from the account and the captured affiliate owner. No provider credentials. |
| `tracking` | object | Public allowlisted acquisition snapshot (UTM/click IDs) for this verified host-bound session. Restore tracking across clean node redirects; never contains provider tokens or arbitrary session configuration. |
| `storePinVerified` | boolean | Present and true only for an active session after the optional storeId/cartToken pair has been independently authorized and matched exactly to the cookie session kind, store and cart. Older clients omitting the pair retain the original response. This does not confer payment authority. |

**Errors**

- `400` {"error":"Invalid session request."} for an invalid body (strict: unknown fields refused; storeId and cartToken must come together); {"error":"Invalid checkout host"} for a malformed domain.
- `401` {"error":"Charge authentication required"} when no key is sent; {"error":"Invalid API key"} for an unknown or deactivated key or a key without an owner.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Forbidden"} for a crawler User-Agent.
- `404` {"error":"Store checkout not found."} when the storeId/cartToken pin is not an active store checkout of this account and domain; {"error":"Checkout unavailable"} when the checkout is not an active checkout of the key's account; {"error":"Checkout host unavailable"} when the domain is not a verified host of the checkout.
- `429` Per-IP rate limit (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected database or transaction failure; nothing is committed and no cookie is sent.
- `503` {"error":"Server busy, retry"} with Retry-After: 1, or the database is unreachable.

**Gotchas**

- Account ID is derived from authenticated context; it is never accepted from the caller.
- storeId and cartToken are an optional pair. Omit both for the legacy session-derived pin; supplying only one returns 400. A supplied pin is checked against current store/domain/checkout ownership and the unexpired session kind, store and cart before public data is returned. It does not select or recreate a session.
- An active:true response without storePinVerified:true is not proof of a caller-supplied store/cart pair. A storefront using this optimization must fall back to its full session verification when an older API rejects the fields or omits this acknowledgment.
- Not a client endpoint: buyer-facing storefront runtime called by the storefront server.

#### Checkout orders

Prepare, reserve, dispatch, verify and recover the order of a checkout session.

##### `POST /v5/checkout/order`

**Scope** `charges.write` - **Prepare a canonical checkout order**

Private storefront quote adapter. Creates canonical order context and real order/ownership sidecar/link atomically. Store orders require the cart-pinned real shop; standalone orders retain NULL shop_id. Browser-supplied account/context IDs are not accepted.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the HttpOnly buyer session; the browser cannot select another account or checkout. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `row` | object | **yes** | Storefront order snapshot from the trusted server (extra keys pass through; see gotchas for what persists). id, amount_cents and currency are required. The server derives shop, account and context ownership; row fields cannot select it. Keys builder_quote, builder_selections, checkout_document_version, subscription_consent and discount_amount_cents answer 400, and credential-like keys (card_number, pan, cvv, password, api_key, session_token, kt...) are refused. |
| `row.id` | uuid | **yes** | Initial order identity returned by /v5/checkout/order/reserve for this exact checkout session. An unreserved UUID is rejected. |
| `row.amount_cents` | integer | **yes** | 0..2147483647 minor units; must equal commerce.amountMinor exactly. |
| `row.currency` | string | **yes** | Three uppercase letters; must equal commerce.currency exactly and the pinned standalone currency where applicable. |
| `row.cart_token` | string | no | Required for a store-backed order and must match the pinned session cart. Standalone rows keep cart_token, shop_id and session_id null; a caller cannot attach them to a store. |
| `row.customer_email / row.customer_info` | string / object | no | Optional trusted customer snapshot used for the buyer receipt. Supported customer_info fields include first_name/firstName, last_name/lastName, lang, phoneDialCode, country, phone, address/address1, address2, city, state and postal_code/postalCode. Do not put payment credentials here. |
| `row.line_items` | object[] | no | Optional trusted server order lines used for display fallback. The corresponding captured product/variant identity, quantity and unit price must match before a receipt uses its variant/image/compare-at data. |
| `commerce` | object | **yes** | Strict server-quoted commerce snapshot. Required: amountMinor, taxMinor, currency and items. Unknown commerce fields are rejected; this endpoint records a verified storefront quote rather than accepting browser pricing. |
| `commerce.amountMinor / commerce.taxMinor` | integer | **yes** | 0..2147483647 minor units. amountMinor is the final total and must match row.amount_cents; taxMinor may not exceed amountMinor. |
| `commerce.currency` | string | **yes** | Three uppercase letters, identical to row.currency. |
| `commerce.initialCartRevision` | string | no | Optional 64 lowercase hexadecimal characters. Required in practice when the buyer session carries a landing-page product selection (flow checkout): it must equal the current cart revision the server issued (initialCart.revision of the flow view, initialCartRevision of POST /v5/standalone/session). Missing or stale returns 409 'The selected cart changed. Reload checkout before paying.' Ignored when the session has no landing selection. |
| `commerce.subtotalMinor / commerce.shippingMinor / commerce.discountMinor / commerce.protectionMinor` | integer | no | Optional nonnegative integer minor-unit components, maximum 2147483647 each, from the same server quote. |
| `commerce.items` | object[] | **yes** | At most 100 canonical server line objects. Only these item keys are kept in the immutable snapshot (others are dropped): id, productId, variantId, sku, name and variant (strings cut at 300 characters), image (cut at 2048 characters), shopifyProductId and shopifyVariantId (digits only), quantity, priceMinor, unitPriceMinor, paidUnitPriceMinor, paidTotalMinor, totalMinor and taxMinor (nonnegative safe integers), and isGift, isDiscount and isShippingProtection (booleans). paidUnitPriceMinor is the unit price actually paid after discounts; post-purchase offers of the same product and quantity offers are priced from it when present. compareAtMinor is not kept: receipts take compare-at from the matching row.line_items entry. Standalone quantities must be positive safe integers and obey configured cart limits. No PAN, CVV, reusable credential or secret belongs in this snapshot. |
| `commerce.cardStorageConsent` | object | no | Optional strict historical consent evidence {version, locale, textHash}. version is post-purchase-card-v1 or post-purchase-card-v2; locale must be canonical and textHash a 64-character lowercase hexadecimal SHA-256 matching the exact server notice for that version/locale. Never fabricate this evidence; current post-sell acceptance and fresh verification remain separate. Send it only when the session or entry response reported storesCard:true and the buyer was shown that exact notice. Without valid post-purchase-card-v2 evidence the card is not saved for post-sell offers. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "pay.example.com",
  "row": {
    "id": "22222222-2222-4222-8222-222222222222",
    "amount_cents": 3999,
    "currency": "USD"
  },
  "commerce": {
    "amountMinor": 3999,
    "taxMinor": 0,
    "currency": "USD",
    "subtotalMinor": 3999,
    "shippingMinor": 0,
    "discountMinor": 0,
    "items": [
      {
        "productId": "33333333-3333-4333-8333-333333333333",
        "variantId": "44444444-4444-4444-8444-444444444444",
        "name": "Example product",
        "quantity": 1,
        "unitPriceMinor": 3999,
        "totalMinor": 3999
      }
    ]
  }
}
```

**Response**

```json
{
  "orderId": "22222222-2222-4222-8222-222222222222"
}
```

| response field | type | description |
|---|---|---|
| `orderId` | uuid | The reserved order UUID whose pending order, canonical initial context and ownership link were prepared atomically. This is not payment approval or dispatch. |

**Errors**

- `400` {"error":"Unsupported order fields"}: row carries builder_quote, builder_selections, checkout_document_version, subscription_consent or discount_amount_cents. Malformed JSON body.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`. Also an invalid cardStorageConsent (the strict schema checks textHash against the exact notice).
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session for this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Checkout unavailable"} also when the pinned standalone configuration no longer resolves; {"error":"Standalone order context not found"}.
- `409` {"error":"Order quote differs"}: row.amount_cents/currency differ from commerce. {"error":"The selected cart changed. Reload checkout before paying."}: commerce.initialCartRevision missing or stale while the session carries a landing selection. {"error":"Initial payment identity unavailable"}: row.id was not reserved for this session. {"error":"Order currency differs"}, {"error":"Order quantity differs"} (an item quantity that is not a positive safe integer), {"error":"Checkout cart limit exceeded"} (standalone limits). {"error":"Store checkout session unavailable"}: store session without store or row.cart_token not the pinned cart. {"error":"Store order unavailable"}: an existing store order with another amount or currency. Database conflicts answer 409 with the mapped sentence.
- `413` {"error":"Request body is too large"}: body over 131072 bytes (route bodyLimit).
- `422` Live catalog or link refusal of the pinned offer: "Product <n> is unavailable for this account", "Product <n> currency differs from the checkout", "Product <n> requires a name, valid price and quantity", "Product <n> compare price is below price", "Add at least one product", or a saved-link integration refusal ("Select a configured 3DS integration owned by this account", "Select an enabled email sender owned by this account", "A country is not offered by this checkout"...).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure. Also credential-like keys inside row or commerce.taxMinor above amountMinor (plain errors raised after validation, not mapped to 400).

**Gotchas**

- The example uses a standalone order after reserve. For a store order also include the exact pinned row.cart_token. The prepared order belongs to the real server-resolved store; a standalone order keeps shop_id null.
- All amounts in this endpoint are integer minor units. The later /v1/charge amount is in major units and must agree with the prepared context. Preparing an order never submits a payment.
- New order preparation requires current checkout/store admission. The canonical initial context copies attribution from the authenticated entry session, not a caller-selected account/context. Card and wallet starts share the reserved initial identity.
- Store receipt thumbnails, including free gifts, are sourced by the trusted storefront from the server cart bound to the signed price envelope and exact line price. Upsell thumbnails come from the server quote. A missing or timed-out optional thumbnail lookup does not block a payment, and arbitrary browser image URLs are not authoritative.
- Never submit PAN, CVV, credentials, secrets or entry tokens inside row/commerce. The alternate fields builder_quote, builder_selections, checkout_document_version, subscription_consent and discount_amount_cents are unsupported and explicitly rejected during order insertion.
- Additional persisted row properties are allowlisted: visitor_id, session_id, card_brand, card_last4, click_ids, referrer_host, utm_source, utm_medium, utm_campaign, utm_adset, utm_ad, utm_id, utm_term, utm_content, attribution_network, event_source_url, payment_method, payment_path, wallet_kind, three_ds_attempted, three_ds_status, three_ds_eci, three_ds_phase, three_ds_ms, three_ds_ab_bucket, gateway_kind, apple_pay_ab_bucket, discount_code, consents, subscription_optin, upsell_lines, discount_cents and discount_redemption_id. ip_version is retained only when its legacy column exists. These properties are reporting data, never payment authorization or account ownership; unknown passthrough fields are not guaranteed to persist.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

##### `POST /v5/checkout/order/dispatch`

**Scope** `charges.write` - **Claim the single initial payment dispatch**

Atomically claims the card or wallet dispatch of the reserved, prepared initial order of this buyer session. claimed:true means this caller won and may submit the payment; claimed:false means the attempt was already dispatched (a replay): only observe the existing payment. Never charges by itself.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `orderId` | uuid | **yes** | Reserved and prepared initial order id of this session. |
| `channel` | card \| wallet | **yes** | Channel claiming the dispatch (wire is not accepted on this route). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com", "orderId": "22222222-2222-4222-8222-222222222222", "channel": "card"}
```

**Response**

```json
{"claimed":true}
```

| response field | type | description |
|---|---|---|
| `claimed` | boolean | true when this call set the dispatch claim; false when the attempt already had one (whatever its channel). |

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session for this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link).
- `409` {"error":"Initial payment attempt unavailable"}: session expired or completed, domain no longer accepts payments, orderId not reserved for this session, a successor attempt exists, the previous attempt's decline is not proved, or the order was not prepared (no canonical context and link).
- `413` {"error":"Request body is too large"}: body over 2048 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- A failed payment fact alone is not evidence of non-capture: a successor attempt needs persisted terminal processor decline evidence.
- Recovery (POST /v5/checkout/order/recover) only reads. Unknown outcomes never cause automatic resubmission.
- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

##### `POST /v5/checkout/order/recover`

**Scope** `charges.write` - **Recover the owned initial order without dispatch**

Reads the exact account, checkout, host and HttpOnly-cookie session order. Optional orderId must belong to that scope; otherwise selects the attempt-chain leaf. Supports standalone orders with null shop/cart and completed unexpired flow sessions. Never dispatches or resubmits payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the HttpOnly buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `orderId` | uuid | no | Optional exact order within this authenticated session. If omitted, the server selects the leaf of the initial-attempt chain. An arbitrary order ID never grants access. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow` entry cookie; its session must not be expired (or have an unexpired or paid wire session), may be completed. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com"}
```

**Response**

```json
{"row":null}
```

| response field | type | description |
|---|---|---|
| `row` | object \| null | Every column of the owned order row (orders.*) plus dispatch_channel and latest, or null when this session has no matching prepared order. Private server response with buyer and order fields: do not expose it wholesale or log it. |
| `row.dispatch_channel` | card \| wallet \| wire \| null | Persisted channel that claimed the initial attempt, not a payment verdict. |
| `row.latest` | boolean | Whether the returned order has no successor attempt. An explicitly requested older order may return false. |
| `declined` | boolean \| absent | Present only when row exists. True only after the server verifies final non-capture/refusal evidence for this exact order; a status label or timeout alone is insufficient. |

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout recovery unavailable"}: missing entry cookie or no eligible session for this cookie, checkout and host.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account. A missing order within a valid scope answers 200 {"row":null} instead.
- `413` {"error":"Request body is too large"}: body over 2048 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Read-only: no session reopening, new order, dispatch, retry or settlement. Unknown outcomes must reconcile; returning a row never authorizes another charge.
- Supports completed but unexpired flow sessions and standalone orders with null shop/cart through their ownership sidecar. The session must not have status expired. An associated unexpired or paid wire session can extend this lookup condition; expired paid-flow receipt rendering is a separate GET /v5/flow/:checkoutId behavior.
- Pausing/archiving a store or changing its current route does not by itself remove access to an already-owned order observation. New payment admission still runs through the ordinary current access checks.
- A missing scoped order returns {row:null} without declined. Missing/invalid session evidence returns an authentication error instead; never infer decline from either result.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

##### `POST /v5/checkout/order/reserve`

**Scope** `charges.write` - **Reserve the server-owned initial payment identity**

Returns the same UUID for concurrent or replayed session requests. previousOrderId requests the single successor of a proved final processor decline. Pending, unknown, captured, configuration failures and missing processor evidence cannot authorize another payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the HttpOnly buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `previousOrderId` | uuid | no | Only for a successor attempt after the server proves the previous scoped order has a final non-capture outcome. Repeated calls with the same previousOrderId reuse the same successor. Omit for the first attempt. |
| `initialCartRevision` | string | no | Optional 64 lowercase hexadecimal characters. Required in practice when the buyer session carries a landing-page product selection: it must equal the current cart revision the server issued. Missing or stale returns 409 'The selected cart changed. Reload checkout before paying.' |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com"}
```

**Response**

```json
{
  "orderId": "22222222-2222-4222-8222-222222222222",
  "dispatched": false,
  "channel": null,
  "dispatchManagedByApi": true
}
```

| response field | type | description |
|---|---|---|
| `orderId` | uuid | Stable reserved initial order ID for this session/checkout and optional previous-order link. |
| `dispatched` | boolean | Whether this attempt already holds a dispatch claim. True is not a processor approval. |
| `channel` | card \| wallet \| wire \| null | Persisted winning dispatch channel, or null before dispatch. |
| `dispatchManagedByApi` | boolean | Always true for this route. The API owns the atomic card/wallet dispatch claim; do not send an additional independent payment. |

**Errors**

- `400` {"error":"Product selection unavailable."}: the stored landing selection names an offer that is not on the published page. Malformed JSON body.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session for this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link).
- `409` {"error":"Initial payment attempt unavailable"}: session expired or completed, the store or standalone domain no longer accepts new payments, or previousOrderId has no proved final non-capture outcome. {"error":"The selected cart changed. Reload checkout before paying."}: initialCartRevision missing or stale while the session carries a landing selection. {"error":"Reload the product selection before paying."}: unreadable stored selection. {"error":"Published product choices unavailable."}.
- `422` {"error":"Choose <option> before continuing."} (or "Choose a variant before continuing."): the stored landing selection misses a required option confirmation. {"error":"Product option confirmation differs from the selected variant."}.
- `413` {"error":"Request body is too large"}: body over 2048 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- This route reserves a payment identity, not money. Current checkout/store admission and an active unexpired, uncompleted session are required.
- Concurrent calls and replays return the same identity. Never mint a new order ID after a timeout, pending authentication or unknown provider result; reconcile the existing attempt.
- A failed fact or an orders status alone does not prove non-capture. A successor requires persisted terminal processor decline evidence or the explicitly supported, account-bound pre-gateway refusal evidence. A test decline, missing transaction, configuration failure, pending/reconciling result or captured order does not authorize a successor.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

##### `POST /v5/checkout/order/verify`

**Scope** `charges.write` - **Verify a prepared checkout order**

Rechecks, before a 3DS re-submit, that orderId is the reserved initial order of this buyer session (not yet dispatched, or dispatched to card), that its prepared quote matches amount and currency, and that the pinned checkout configuration is still available. Does not charge and changes nothing.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `orderId` | uuid | **yes** | Reserved initial order id of this session (from POST /v5/checkout/order/reserve, prepared by POST /v5/checkout/order). |
| `amount` | number >= 0 | **yes** | Charge amount in MAJOR units; Math.round(amount * 100) must equal the prepared commerce.amountMinor. |
| `currency` | string, ^[A-Z]{3}$ | **yes** | Must equal the prepared commerce.currency. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com", "orderId": "11111111-1111-4111-8111-111111111111", "amount": 39.99, "currency": "USD"}
```

**Response**

```json
{"ok":true}
```

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session for this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Card payments are disabled for this store"}: store checkout whose card method is off.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link).
- `409` {"error":"Initial payment dispatch unavailable"}: orderId is not an initial attempt of this session, or it was dispatched to another channel. {"error":"Checkout order differs from its prepared quote"}: no prepared context, or amount/currency differ. {"error":"Checkout order owner differs"}, {"error":"Checkout configuration unavailable"}: the pinned standalone configuration can no longer be resolved.
- `413` {"error":"Request body is too large"}: body over 2048 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Request headers X-Kontrol-Checkout / X-Kontrol-Domain are ignored here: the body checkoutId and domain are used.
- The delivery-country check of a real charge is skipped by this verification.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

#### Flow runtime

Read and act on the post-purchase flow of a session: view, cart, quotes, actions, authentication and events.

##### `GET /v5/flow/:checkoutId`

**Scope** `charges.write` - **Read current pinned flow node**

Loads the authenticated pinned flow page and verified receipt. Expired paid journeys expose their configured read-only Thank-you page without moving the stored cursor. Current browsers record visits separately using the returned signed observationToken; a read alone is not a visit.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string | **yes** | Public checkout UUID. No session identifier is accepted in the path. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `viewId` | UUID | no | Legacy active-page observation UUID. Retained for compatibility; current browsers post page_view with the served observationToken to /events. Does not record completed or expired Thank-you visits. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact verified checkout hostname, supplied by the trusted storefront proxy. |

**Response** `200`

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "nodeId": "offer",
  "kind": "post_sell",
  "state": "active",
  "simulation": true,
  "completed": false,
  "paymentConfirmed": true,
  "purchases": [],
  "pixels": [],
  "confirmation": {
    "orders": [
      {
        "id": "22222222-2222-4222-8222-222222222222",
        "kind": "initial",
        "currency": "USD",
        "totalMinor": 1000,
        "taxMinor": 0,
        "shippingMinor": 0,
        "subtotalMinor": 1000,
        "discountMinor": 0,
        "items": [
          {
            "name": "Starter kit",
            "quantity": 1,
            "unitPriceMinor": 1000,
            "totalMinor": 1000,
            "image": "https://assets.example.com/starter-kit.jpg"
          },
          {
            "name": "Gift pouch",
            "quantity": 1,
            "unitPriceMinor": 0,
            "totalMinor": 0,
            "image": "https://assets.example.com/gift-pouch.jpg"
          }
        ]
      }
    ],
    "locale": "en"
  }
}
```

| response field | type | description |
|---|---|---|
| `nodeId / kind / state` | string | Current pinned graph node and durable session state; do not choose a client-side next node. |
| `checkoutId` | uuid | The selected verified checkout bound to this buyer session and domain. |
| `locale` | string | Post-purchase display locale: en, fr, it, es, pt or pl. The language captured with the initial order wins over the entry lang parameter, and the Thank-you receipt locale wins over both; anything else falls back to en. |
| `completed / paymentConfirmed` | boolean | Completed can also indicate expiry; paymentConfirmed identifies a recorded initial payment fact that has not been corrected as failed. Inspect receipt/capture facts rather than treating completion alone as a sale. |
| `paymentFailed` | boolean \| absent | Present and true when the initial capture was later corrected as failed by verified provider reconciliation (a correction, never a refund). paymentConfirmed is then false, offers, offer and destination are removed, purchases and confirmation exclude it, and the session ends as expired. Show a declined message; do not offer another payment from this session. |
| `document` | object | When applicable, the pinned native page document; default Thank-you is supplied after an eligible captured initial payment. |
| `offers / offer` | array / object | Published/quoted selectable post-sell configurations. offers contains the choices and stable IDs; legacy offer remains compatible. Prices and quantities are server-owned. |
| `data` | object | Allowlisted public display variables such as store_name, store_logo and cart totals from verified brand/commerce facts. Never the private session configuration or integration secrets. |
| `pixels / tracking` | array / object | Eligible public recipients and allowlisted acquisition values; no server pixel tokens. |
| `destination / challenge` | string / object | Conditional navigation or verified pending challenge data. An explicit published Thank-you suppresses fallback completion navigation. |
| `backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. Each entry also includes its original nodeId; entries can belong to a preceding node after the primary purchase completed. |
| `paymentRequirements` | object \| absent | Optional public verification hint: {securityCodeRequired:boolean}. When true, collect a fresh three- or four-digit security code from the buyer for this purchase. Currently required for Convesio card sales. The code itself, original card and credentials are never returned. Page admission depends on the confirmed initial payment, not provider support. |
| `paymentRequirements.method` | string | Optional verified original payment method: card, apple_pay, google_pay or wire. Available to the shared Wallet payment block on paid post-sell views. Derived from captured fact/source/owner evidence, never editor preview settings; absence does not authorize an alternate source. |
| `receiptOnly` | boolean \| absent | True when an expired paid session is projected to its pinned Thank-you receipt. Render the receipt with all offers inert. The stored cursor, completion reason and session expiry remain unchanged; no payment permission is granted. |
| `observationToken` | string \| absent | Opaque signed proof for the displayed page, valid for five minutes. Submit unchanged with event:page_view, the displayed nodeId and stable UUID viewId only after the page renders. Never put this token in a URL. Poll responses are not visits; simulations and unconfirmed/pending payment pages omit it. |
| `simulation` | boolean \| absent | True when the persisted session is classified as a test. It is a presentation flag, not a caller-controlled switch or proof of a real payment. Offer and receipt access additionally require the server to verify the initial test transaction, captured test fact, account and session binding. Test flows follow the configured post-sell and Thank-you nodes. |
| `confirmation` | object \| absent | Buyer-scoped receipt on eligible post-sell and Thank-you views. Live journeys contain the captured initial order, captured upsell orders and supported accepted free fulfillments. Verified simulations contain the approved test initial order plus accepted simulated offer snapshots; these are display records, not real upsell captures. Each order has kind:initial\|upsell and integer minor-unit amounts. No raw card, security code or reusable credential is returned. |
| `confirmation.orders[].items` | object[] | Receipt lines contain name, optional variant/image/compareAtMinor, quantity, unitPriceMinor and totalMinor. image is a validated HTTPS URL when available. Initial store items, including zero-value gifts, use the server cart bound to the signed price envelope; caller-supplied thumbnails do not override it. Upsell images follow the selected server-quoted variant. Missing optional images do not reject payment. Render initial and accepted upsell lines from confirmation, not the Purchase-event list. |
| `purchases` | array | Tracking-eligible captured non-test payment events, with eventId, kind, amountMinor, currency and canonical items. Stable event IDs permit deduplication across reloads. This is not the complete display receipt: it is empty for simulations and excludes free fulfillments. Use confirmation for the order summary. |
| `initialSelection` | object[] \| absent | Published selected offer IDs, allowed variants/quantities and explicit required-option confirmations; scoped to the pinned page/session. |
| `initialCart` | object \| absent | Checkout pre-payment cart: revision (64 hex chars), editable, currency, totalMinor and authoritative lines. Each line includes productId, variantId, name, variant, sku, image, quantity, unitPriceMinor, compareAtMinor and subscriptionProductId. Not permission to charge. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` The pinned published flow or the session state is no longer available; reload the session.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Account ID is derived from authenticated context; it is never accepted from the caller.
- See the *Pages and flows* section of llm.md for publication order, graph schema, token capabilities and UNKNOWN recovery.
- Requires a published account-owned flow and a verified session. All cookies and responses use private no-store.
- Purchase eventId is the actual immutable logical order UUID, stable across reloads. Purchase events expose no reusable credential or private customer fields; the separate confirmation object is restricted to the bound buyer and can include their receipt/contact details.
- paymentConfirmed reflects the captured initial order independently from purchases, which only contains tracking-eligible captures. Verified test payments follow the published post-sell and Thank-you sequence without emitting Purchase pixels.
- Render data is a server-built allowlist, not a serialization of private configuration. Thank-you receipt data requires the bound buyer session and confirmed eligible initial payment.
- Paid post_sell views expose the buyer-scoped confirmation receipt as well as thank_you views. For live journeys, confirmation.orders contains captured initial/upsell orders and supported free fulfillments, with kind distinguishing them; simulations use the separate test receipt behavior described here. purchases also includes kind for original-order fallback and keeps initial captures first. Original blocks must not infer confirmation from a heading or an unconfirmed payment.
- paymentRequirements is a display hint, not payment authorization. A required security code must be entered again by the buyer and kept in memory only; never replay the original checkout CVV. Confirm and authentication-resume requests remain bound to the existing buyer session, original source and accepted basket.
- The builder Wallet payment block uses the same signed basket, explicit acceptance and configured authentication as the existing confirmation. Initial checkouts retain native device/provider eligibility. On post-sells the verified original method determines presentation and continuation; the block does not change MID or bypass required verification.
- An expired paid session can return kind:thank_you and receiptOnly:true while state remains expired. The read-only projection uses the pinned graph, existing paid decisions and captured initial-order facts; it never persists invented declines or decisions, reopens offers or resends a payment.
- A served observationToken is not a visit or payment authorization. Browser page_view submission records the served node even if an action advances the flow first. Server completions and historical sessions are never backfilled as observed Thank-you visits.
- With simulation:true, server verification of the existing initial test payment permits the configured offer journey. Confirm still checks the current node, published products/variants, signed quote, complete selection and explicit acceptance. Accepted offers are recorded as simulated actions only: no real upsell order, intent, gateway call, 3DS authentication, usage reservation or fulfillment is created. The resulting receipt can contain these offers while purchases remains [].
- Test flow responses suppress advertising: pixels is [], tracking is omitted and no page-view observationToken is issued. paymentRequirements, primary authentication and background authentications are not requested for the simulated confirmation. Attribution can still be persisted on the initial test order/session/transaction; absence of browser tracking in a test response is intentional, but losing UTMs before session creation is not.
- The response example is a reduced receipt-focused verified simulation: the GET shows the approved test initial order plus its free gift; the confirm response adds the accepted travel-case/cable basket for 1100 minor units. Simulated upsell receipt IDs identify simulated action records, not real paid orders. The full published document and display variables are omitted here for readability. purchases remains empty; render confirmation.orders instead. Live replies use verified captured orders and eligible Purchase events as documented above.
- A session whose initial payment is captured keeps read access (this view, events, purchase observation) after the checkout is paused or its live route or published host changes; an unpaid session needs current checkout access. Confirm and authentication actions still recheck current access and answer 409 'This offer is no longer available. You can continue to your receipt.'
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/actions`

**Scope** `charges.write` - **Confirm an upsell cart or advance its flow**

Confirm is the only new-payment action: the authenticated buyer submits a signed quote for the complete selected upsell basket. Add and pre-add are local cart operations; stale accept requests are refused. Existing continue, decline and authentication-resume actions remain available. On a pre-purchase landing, continue can persist published initialSelection and enum-only quizAnswers atomically before advancing; neither is a payment action.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string | **yes** | Checkout UUID of the key's account, matching the buyer session. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nodeId` | string | **yes** | Current flow node, at most 80 characters. |
| `action` | string | **yes** | confirm, decline, continue or authenticate. Legacy accept returns409 without payment admission. |
| `scope` | string | no | Required page for confirm. Per-offer scope is refused. |
| `selections` | array | no | Required for confirm: 1-20 unique offerId values with optional published variantId UUID and quantity1-10. Server checks catalog, ownership, fixed/allowed choices, availability and quantity-tier exclusivity. |
| `quoteToken` | string | no | Required confirm token from the quote endpoint, maximum12000 characters. Binds session, initial payment fact, domain, flow version/node, selected-price digest, attempts and expiry. |
| `acceptance` | object | no | Required confirm disclosure version post-purchase-accept-v2, locale, amountMinor and currency. Amount must match the recomputed server basket; client values never set gateway amount. Historical v1 does not authorize a new confirmation. |
| `browser` | object | no | Optional bounded browser characteristics for confirm. IP/user-agent originate only from trusted proxy headers. |
| `authentication` | object | no | Only for authenticate: existing sessionId, stage poll\|method\|challenge\|cancel and optional methodCompleted; resumes one pending intent. |
| `payment` | object | no | Fresh verification only: strict object {securityCode:string}, exactly 3 or 4 digits (^[0-9]{3,4}$), no other properties. Allowed only on confirm or authenticate. Required when paymentRequirements.securityCodeRequired is true, on confirm and every non-cancel authentication continuation that can dispatch this same sale. Cancellation does not require it. Never send PAN, expiry, provider credentials or the initial checkout CVV. |
| `initialSelection` | array | no | 1-10 unique selections: {offerId,variantId?,quantity?,confirmedOptions?}. offerId is a published ID (1-80 alphanumeric/underscore/hyphen, starting alphanumeric); variantId is an allowed UUID, quantity 1-10 within published bounds. confirmedOptions maps at most 20 option names (1-80 chars) to published values (1-160 chars), or $variant to the selected variant UUID. Browser-supplied product IDs, prices, currency and plan IDs are rejected. Allowed only with continue, without upsell/payment/authentication fields. |
| `quizAnswers` | object | no | Only with continue: map published question IDs (1-80 chars, at most 30 keys) to arrays of declared option values (1-160 chars, at most 20 unique values). Maximum serialized size 32768 bytes. Single-choice steps accept at most one; required reachable answers must be present. Unknown keys/values are rejected; skipped branch answers are omitted from persistence. Information steps need no answer. Cannot combine with payment/authentication/upsell fields. |
| `selectedOfferIds` | string[] | no | Legacy per-offer selection (1..20 offer ids). Refused with selections, quoteToken or scope; use selections + quoteToken + scope=page with action confirm instead. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact verified checkout hostname, supplied by the trusted storefront proxy. |
| `x-v5-buyer-ip` | string | no | Shopper IP forwarded by the trusted storefront proxy. Recorded with the confirm acceptance evidence (only when it is a valid IP) and used as the browser IP for authentication. Never read from the body. |
| `x-v5-buyer-ua` | string | no | Shopper user agent forwarded by the trusted storefront proxy; the first 512 characters are recorded with the acceptance evidence and used for authentication. |

**Request body**

```json
{
  "nodeId": "offer",
  "action": "confirm",
  "scope": "page",
  "selections": [
    {
      "offerId": "travel-case",
      "quantity": 1
    },
    {
      "offerId": "cable",
      "quantity": 2
    }
  ],
  "quoteToken": "<signed basket quote>",
  "acceptance": {
    "version": "post-purchase-accept-v2",
    "locale": "en",
    "amountMinor": 1100,
    "currency": "USD"
  }
}
```

**Response** `200`

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "nodeId": "thank-you",
  "kind": "thank_you",
  "state": "completed",
  "simulation": true,
  "completed": true,
  "paymentConfirmed": true,
  "purchases": [],
  "pixels": [],
  "confirmation": {
    "orders": [
      {
        "id": "22222222-2222-4222-8222-222222222222",
        "kind": "initial",
        "currency": "USD",
        "totalMinor": 1000,
        "taxMinor": 0,
        "shippingMinor": 0,
        "subtotalMinor": 1000,
        "discountMinor": 0,
        "items": [
          {
            "name": "Starter kit",
            "quantity": 1,
            "unitPriceMinor": 1000,
            "totalMinor": 1000,
            "image": "https://assets.example.com/starter-kit.jpg"
          },
          {
            "name": "Gift pouch",
            "quantity": 1,
            "unitPriceMinor": 0,
            "totalMinor": 0,
            "image": "https://assets.example.com/gift-pouch.jpg"
          }
        ]
      },
      {
        "id": "33333333-3333-4333-8333-333333333333",
        "kind": "upsell",
        "currency": "USD",
        "totalMinor": 1100,
        "taxMinor": 0,
        "shippingMinor": 0,
        "subtotalMinor": 1100,
        "discountMinor": 0,
        "items": [
          {
            "name": "Travel case",
            "quantity": 1,
            "unitPriceMinor": 500,
            "totalMinor": 500,
            "image": "https://assets.example.com/travel-case.jpg"
          },
          {
            "name": "Cable",
            "quantity": 2,
            "unitPriceMinor": 300,
            "totalMinor": 600,
            "image": "https://assets.example.com/cable.jpg"
          }
        ]
      }
    ],
    "locale": "en"
  }
}
```

| response field | type | description |
|---|---|---|
| `cartKey` | string | Opaque identity of authenticated session + pinned flow version + node, used only to isolate local cart IDs. Never a payment capability. |
| `locale` | string | Post-purchase display locale: en, fr, it, es, pt or pl. The language captured with the initial order wins over the entry lang parameter, and the Thank-you receipt locale wins over both; anything else falls back to en. |
| `paymentFailed` | boolean \| absent | Present and true when the initial capture was later corrected as failed by verified provider reconciliation (a correction, never a refund). paymentConfirmed is then false, offers, offer and destination are removed, purchases and confirmation exclude it, and the session ends as expired. Show a declined message; do not offer another payment from this session. |
| `offerBehavior` | string | basket for all new actions, including historically independent configurations. |
| `authentication` | object | Existing fresh per-sale SCA challenge or method step, when policy requires it. |
| `authentication.provider` | string \| absent | Provider of the active primary authentication. PAAY supports concurrent Method execution and polling. |
| `authentication.backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. |
| `authentication.pendingDeadlineAt` | string (ISO 8601) \| absent | Server-owned deadline for optional silent PAAY authentication of the current purchase, default 45 seconds from its durable creation. Secondary background work has its own lifetime and neither extends nor cancels this deadline. Resume the SAME order and session through the normal charge path; the server rechecks required authentication and current provider state. Real issuer challenges, known negative results and mandatory authentication retain their controls. This deadline never approves a sale or authorizes retrying an unknown bank result. |
| `backgroundAuthentications` | object[] \| absent | Optional PAAY sibling work: array of {sessionId,provider:"paay_3ds",status,next,expiresAt}. next is only method or poll; no secondary challenge, SDK or cryptogram is included. Run returned Methods in real hidden browser iframes concurrently with the primary, then report stage:"method",methodCompleted:false to mark submission and start result polling. This is not a claim that fingerprinting succeeded. Secondary read failures, expiration or challenges must not delay or re-submit an already dispatched payment. Browser and worker poll the existing authentication only; neither creates another payment. Flow-level entries also include nodeId so already-started work can continue after navigation. Use the dedicated background-observation endpoint, never the authenticate payment action, for these optional reads. |
| `paymentRequirements` | object \| absent | Optional public verification hint: {securityCodeRequired:boolean}. When true, collect a fresh three- or four-digit security code from the buyer for this purchase. Currently required for Convesio card sales. The code itself, original card and credentials are never returned. Page admission depends on the confirmed initial payment, not provider support. |
| `receiptOnly` | boolean \| absent | True when an expired paid session is projected to its pinned Thank-you receipt. Render the receipt with all offers inert. The stored cursor, completion reason and session expiry remain unchanged; no payment permission is granted. |
| `observationToken` | string \| absent | Opaque signed proof for the displayed page, valid for five minutes. Submit unchanged with event:page_view, the displayed nodeId and stable UUID viewId only after the page renders. Never put this token in a URL. Poll responses are not visits; simulations and unconfirmed/pending payment pages omit it. |
| `simulation` | boolean \| absent | True when the persisted session is classified as a test. It is a presentation flag, not a caller-controlled switch or proof of a real payment. Offer and receipt access additionally require the server to verify the initial test transaction, captured test fact, account and session binding. Test flows follow the configured post-sell and Thank-you nodes. |
| `confirmation` | object \| absent | Buyer-scoped receipt on eligible post-sell and Thank-you views. Live journeys contain the captured initial order, captured upsell orders and supported accepted free fulfillments. Verified simulations contain the approved test initial order plus accepted simulated offer snapshots; these are display records, not real upsell captures. Each order has kind:initial\|upsell and integer minor-unit amounts. No raw card, security code or reusable credential is returned. |
| `confirmation.orders[].items` | object[] | Receipt lines contain name, optional variant/image/compareAtMinor, quantity, unitPriceMinor and totalMinor. image is a validated HTTPS URL when available. Initial store items, including zero-value gifts, use the server cart bound to the signed price envelope; caller-supplied thumbnails do not override it. Upsell images follow the selected server-quoted variant. Missing optional images do not reject payment. Render initial and accepted upsell lines from confirmation, not the Purchase-event list. |
| `purchases` | array | Tracking-eligible captured non-test payment events, with eventId, kind, amountMinor, currency and canonical items. Stable event IDs permit deduplication across reloads. This is not the complete display receipt: it is empty for simulations and excludes free fulfillments. Use confirmation for the order summary. |
| `initialSelection` | object[] \| absent | Published selected offer IDs, allowed variants/quantities and explicit required-option confirmations; scoped to the pinned page/session. |
| `initialCart` | object \| absent | Checkout pre-payment cart: revision (64 hex chars), editable, currency, totalMinor and authoritative lines. Each line includes productId, variantId, name, variant, sku, image, quantity, unitPriceMinor, compareAtMinor and subscriptionProductId. Not permission to charge. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Malformed request, missing confirm fields, empty/duplicate/foreign selections, invalid per-offer scope or legacy selectedOfferIds. Also malformed security code, extra payment properties, or payment sent with continue/decline.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Buyer session, checkout ownership or serving domain not found. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` Legacy accept; stale quote/attempt/price; payment pending; wrong node; offer no longer available. Never blindly retry unknown payments. Missing required fresh security-code verification rejects sale dispatch; read the current flow state before allowing another manual confirmation.
- `410` Offer or confirmation window expired.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Add and preAddToCart never call this endpoint; they do not create orders, intents, payments or reservations.
- A live paid confirmation reprices and verifies the entire basket under the session lock; one page-scoped idempotent intent/order uses all selected lines. The verified test and explicit zero-value paths have the separate effects documented below. Double-clicks and concurrent tabs cannot create duplicate captured sales.
- The internal engine keeps its historical accept outcome name, but only the public confirm action can reach it for a new payment. Historical pending intents retain their reconciliation scope.
- In a live journey, an explicitly zero-value free basket creates one gift fulfillment with no gateway transaction/captured payment fact. Verified simulations only record their simulated accepted action.
- Confirmed failure may retry only with a fresh quote/attempt. Unknown outcomes must reconcile the existing intent and must not redispatch.
- Closing/declining a page discards outstanding offers; single-card removal is local and makes no payment request.
- The storefront action proxy bounds body length24576 and token12000. Responses are private,no-store and no-referrer.
- Post-sell authentication starts only after explicit acceptance. Its primary usable proof can proceed without waiting for an optional secondary. Both requests concern the accepted post-sell amount; neither enrolls a subscription or places a secondary proof in the rebill stock. Authentication resumes retain the same durable payment intent.
- Convesio direct card sales require a freshly collected buyer security code. Retain it only in request/browser memory during this confirmation, including same-intent 3DS continuations; collect it again after reload. Never persist it in URLs, cookies, browser storage, intents, authentication records, queues, analytics, logs or responses. Background authentication observation and payment reconciliation do not accept it. The initial checkout CVV and cryptogram are never reused.
- A 409 does not prove that no payment exists. Read the authenticated current flow state; resume pending authentication or reconciliation, and only allow a new manual confirmation when the session is active and no payment/action/authentication is pending. Never automatically replay a failed or unknown sale.
- An expired paid session can return kind:thank_you and receiptOnly:true while state remains expired. The read-only projection uses the pinned graph, existing paid decisions and captured initial-order facts; it never persists invented declines or decisions, reopens offers or resends a payment.
- A served observationToken is not a visit or payment authorization. Browser page_view submission records the served node even if an action advances the flow first. Server completions and historical sessions are never backfilled as observed Thank-you visits.
- With simulation:true, server verification of the existing initial test payment permits the configured offer journey. Confirm still checks the current node, published products/variants, signed quote, complete selection and explicit acceptance. Accepted offers are recorded as simulated actions only: no real upsell order, intent, gateway call, 3DS authentication, usage reservation or fulfillment is created. The resulting receipt can contain these offers while purchases remains [].
- Test flow responses suppress advertising: pixels is [], tracking is omitted and no page-view observationToken is issued. paymentRequirements, primary authentication and background authentications are not requested for the simulated confirmation. Attribution can still be persisted on the initial test order/session/transaction; absence of browser tracking in a test response is intentional, but losing UTMs before session creation is not.
- The response example is a reduced receipt-focused verified simulation: the GET shows the approved test initial order plus its free gift; the confirm response adds the accepted travel-case/cable basket for 1100 minor units. Simulated upsell receipt IDs identify simulated action records, not real paid orders. The full published document and display variables are omitted here for readability. purchases remains empty; render confirmation.orders instead. Live replies use verified captured orders and eligible Purchase events as documented above.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/authentication/background`

**Scope** `charges.write` - **Observe an existing optional post-sell authentication**

Reads the result or marks real browser Method submission for an already-created PAAY post-sell secondary. This path cannot authorize, dispatch, capture, retry or advance a payment or flow. It remains separate from the authenticate action that resumes a pending purchase.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the authenticated buyer flow session. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nodeId` | string | **yes** | Original post-sell node owning the secondary, 1-80 characters. It can precede the current node after navigation. |
| `sessionId` | uuid | **yes** | Existing PAAY post_sell_secondary session ID from backgroundAuthentications. Primary and foreign IDs return 404. |
| `stage` | enum: poll\|method | **yes** | poll reads the existing authentication. method records that its returned Method has actually been POSTed into the live browser, then polls; it does not assert successful fingerprinting. Challenge, cancel, accept, card data and unknown fields are rejected. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact lower-case serving host of the buyer page (no scheme, port or path). |

**Request body**

```json
{
  "nodeId": "offer",
  "sessionId": "22222222-2222-4222-8222-222222222222",
  "stage": "poll"
}
```

**Response**

```json
{
  "session": {
    "sessionId": "22222222-2222-4222-8222-222222222222",
    "provider": "paay_3ds",
    "status": "authenticated",
    "next": null,
    "expiresAt": "2026-11-02T16:30:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `session` | object | Existing sessionId, provider, status, expiresAt and next. No auth object, card, cryptogram, secret or payment result is returned. |
| `session.next` | object \| null | Only method (provider URL and opaque fields), poll or null. A secondary challenge/SDK is never returned as a hidden action. A terminal authentication status is not payment approval. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Invalid UUID, node ID, stage, extra field or malformed body.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Buyer session, secondary, ownership/binding or unexpired authentication not found. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` Pinned published flow unavailable.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- This endpoint never enters offer authorization or payment dispatch, even when the primary is ready, dispatched, unknown or already captured. Calling it cannot complete a pending purchase.
- Fingerprinting must run in the real browser. A worker can poll an accepted provider reference but cannot emulate a missing browser Method or an issuer challenge. Navigation away can reduce secondary completion yield without delaying the primary sale.
- Browser and worker share a durable secondary poll lease. Preserve the same session identity and stop client reads on terminal status, expiry or navigation away. Never create a replacement authentication from this read-only continuation.
- The private response has Cache-Control: private, no-store and Referrer-Policy: no-referrer. The storefront same-origin proxy enforces its Origin and Fetch Metadata rules.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/cart`

**Scope** `charges.write` - **Update the initial flow cart**

Requote a pre-payment standalone cart on its current checkout node using the same pinned source offers. Atomically verifies revision and updates trusted totals; it never sends a charge or advances the flow.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout UUID bound to the authenticated account/domain/session. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nodeId` | string | **yes** | Current checkout node ID, 1-80 characters. |
| `initialSelection` | array | **yes** | 1-10 unique selections: {offerId,variantId?,quantity?,confirmedOptions?}. offerId is a published ID (1-80 alphanumeric/underscore/hyphen, starting alphanumeric); variantId is an allowed UUID, quantity 1-10 within published bounds. confirmedOptions maps at most 20 option names (1-80 chars) to published values (1-160 chars), or $variant to the selected variant UUID. Browser-supplied product IDs, prices, currency and plan IDs are rejected. |
| `cartRevision` | string | **yes** | Exact initialCart.revision from the latest flow view: 64 lowercase hexadecimal characters. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Verified serving hostname, supplied by the trusted storefront. |

**Request body**

```json
{
  "nodeId": "checkout",
  "initialSelection": [
    {
      "offerId": "kit",
      "variantId": "22222222-2222-4222-8222-222222222222",
      "quantity": 1,
      "confirmedOptions": {
        "Size": "M"
      }
    }
  ],
  "cartRevision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
```

**Response** `200`

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "nodeId": "checkout",
  "kind": "checkout",
  "state": "active",
  "completed": false,
  "paymentConfirmed": false,
  "purchases": [],
  "initialSelection": [
    {
      "offerId": "kit",
      "variantId": "22222222-2222-4222-8222-222222222222",
      "quantity": 1,
      "confirmedOptions": {
        "Size": "M"
      }
    }
  ],
  "initialCart": {
    "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "editable": true,
    "currency": "USD",
    "totalMinor": 2995,
    "lines": [
      {
        "productId": "11111111-1111-4111-8111-111111111111",
        "variantId": "22222222-2222-4222-8222-222222222222",
        "name": "Travel kit",
        "variant": "M",
        "sku": "KIT-M",
        "image": "https://assets.example.com/kit-m.webp",
        "quantity": 1,
        "unitPriceMinor": 2995,
        "compareAtMinor": null,
        "subscriptionProductId": null
      }
    ]
  }
}
```

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Malformed strict request, invalid identifier or encoding.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Flow link unavailable."} when the flow link of the session is no longer live.
- `403` {"error":"Charge access denied"}: the key owner is banned or the key lacks the charges.write scope.
- `404` Resource is absent or belongs to another account. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` Conflicting request key, stale revision or incompatible session state. Read the current resource before retrying.
- `413` Request or decoded media exceeds its endpoint budget.
- `422` A required option is not confirmed: commerce.variant blocks with requireChoice:true on the source landing page need confirmedOptions for that option ('Choose <option> before continuing.' or 'Choose a variant before continuing.'), or a confirmation contradicts the chosen variant; also invalid catalogue, offer, variant or subscription configuration. The previous selection stays in the session.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Any initial payment reservation/order context, captured payment, completed/expired session, source publication mismatch or stale revision blocks mutation. Reread; never force overwrite or resend payment.
- Choices are validated exactly as payment reservation will validate them: a selection missing a required option confirmation (commerce.variant requireChoice:true on the source landing page) is refused 422 and not stored, so the previous, payable selection stays in the session. A refusal is a definite answer: keep the checkout payable with the previous cart and let the buyer retry.
- Canonical host kontrolcheckout.com is supported for store-free checkout. Custom domains still require verified ownership.
- Use the returned revision in the existing signed checkout preparation flow. Never compute prices or a replacement revision in the browser.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/events`

**Scope** `charges.write` - **Record verified page and offer activity**

Records actual rendered flow pages using a signed served-page observationToken, including paid Thank-you receipts after completion or expiry. Also retains current-offer visibility and server-verified timer notifications. Browser events never declare a payment, reopen a session or prepare offers.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string | **yes** | Public checkout UUID. No session identifier is accepted in the path. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nodeId` | string | **yes** | Displayed published node ID, 1-80 ASCII letters, digits, underscores or hyphens for page_view; it must match the signed observationToken. Other event variants require the current published node. |
| `offerId` | string | no | Required only for offer_viewed or offer_timer_expired; stable offer ID present on the current published node. Forbidden for page_view, whose displayed offers are bound in the token. |
| `event` | string | **yes** | page_view \| offer_viewed \| offer_timer_expired. page_view requires observationToken; the other variants require offerId. Objects are strict and these payload variants cannot be mixed. |
| `viewId` | uuid | **yes** | Stable UUID for this page view, reused by retries to deduplicate the observation. |
| `observationToken` | string | no | Required only for page_view: unchanged opaque proof returned by the rendered FlowView, maximum 8000 characters and valid for five minutes. Bound to account, buyer session, serving domain, pinned flow version, displayed node and displayed offers. No caller-selected account or receipt is accepted. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact verified checkout hostname. |

**Request body**

```json
{
  "event": "page_view",
  "nodeId": "thank-you",
  "observationToken": "<observationToken returned by the served FlowView>",
  "viewId": "33333333-3333-4333-8333-333333333333"
}
```

**Response** `200`

```json
{
  "ok": true,
  "recorded": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | The allowed observation was processed idempotently. This is not a payment or advertising-delivery result. |
| `recorded` | boolean \| absent | For page_view only: true if a new page observation was inserted; false for a duplicate or an ineligible observation. This is not proof of a charge or a new server-side flow completion. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Malformed or mixed event payload, invalid node or view ID, or invalid, expired, foreign or tampered observationToken.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Unknown or foreign session/checkout/domain. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` Inactive node, unavailable or expired offer, exhausted quantity, or parent payment no longer eligible.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Only page_view, offer_viewed and offer_timer_expired are accepted from the browser; accepted, failed and declined outcomes come from authoritative server actions.
- The account and buyer session come from the existing bearer, verified hostname and HttpOnly flow cookie. A signed observation token alone does not grant access.
- page_view records the served node, not whichever node is current when its request arrives. A stable viewId makes retries idempotent; no extra offer lifecycle, payment intent, provider request or completion is created.
- Paid page observations recheck the captured initial payment and exclude simulations and reversed captures. A completed or expired paid Thank-you view may be recorded without reopening the session. Generic checkout activity expiry rules remain unchanged.
- Legacy offer events still verify the current offer and persisted countdown deadline. Browser notification cannot expire an offer early.
- Thank-you server completion and a browser visit are separate facts. No historical browser visits are inferred or backfilled.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/purchase-observed`

**Scope** `charges.write` - **Observe browser Purchase dispatch**

Record a completed browser Purchase dispatch for a captured non-test store or standalone order owned by the buyer session. Repeated observations are idempotent and never create a payment or a server-side conversion. Store orders also produce their existing pixel coverage beacon once.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string | **yes** | Public checkout UUID. No session identifier is accepted in the path. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `eventId` | uuid | **yes** | The actual paid order UUID supplied by the server receipt or flow purchases array. |
| `sdk` | object | **yes** | Exactly seven boolean SDK presence flags: fbq, ttq, snaptr, gtag, pintrk, axon and twq. No amounts, account IDs or customer data. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact verified checkout hostname. |

**Request body**

```json
{
  "eventId": "22222222-2222-4222-8222-222222222222",
  "sdk": {
    "fbq": false,
    "ttq": false,
    "snaptr": false,
    "gtag": false,
    "pintrk": false,
    "axon": false,
    "twq": false
  }
}
```

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | The buyer-owned purchase observation was stored or already existed. Does not prove that an advertising network received it. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Malformed UUID, non-boolean SDK flag or unknown field.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Unknown or foreign buyer session, unpaid/test order, a capture later corrected as failed, mismatched host or expired session. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Call only after the browser Purchase promise resolves, with exactly the same order event ID.
- No observation is inferred from a server-rendered flow page or payment alone.
- The HttpOnly session and verified checkout account are mandatory. A caller cannot choose another account, session, amount or order.
- The standalone default checkout uses this transport too; no flow graph is required.
- SDK presence indicates browser dispatch capability, never acceptance by an advertising network.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

##### `POST /v5/flow/:checkoutId/quote`

**Scope** `charges.write` - **Quote published offer choices**

Reprice allowed variant and quantity choices from the current published flow. Returns server-authoritative totals and an expiring signed token; this operation never charges or fulfills.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | string | **yes** | Public checkout UUID. No session identifier is accepted in the path. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nodeId` | string | **yes** | Current published node ID, 1-80 characters. |
| `selections` | array<object> | **yes** | 1-20 unique {offerId, variantId?, quantity?} choices. Variant IDs are published UUIDs; integer quantity is 1-10 and within the configured offer range. No product, amount, currency, discount, tax, shipping, account or gateway fields. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-v5-domain` | string | **yes** | Exact verified checkout hostname. |

**Request body**

```json
{
  "nodeId": "offer",
  "selections": [
    {
      "offerId": "travel-bottle",
      "variantId": "22222222-2222-4222-8222-222222222222",
      "quantity": 2
    }
  ]
}
```

**Response** `200`

```json
{
  "nodeId": "offer",
  "offers": [
    {
      "id": "travel-bottle",
      "quantity": 2,
      "unitPriceMinor": 1500,
      "totalMinor": 3000,
      "currency": "USD",
      "available": true
    }
  ],
  "quote": {
    "subtotalMinor": 3000,
    "compareAtMinor": 4000,
    "savingsMinor": 1000,
    "discountMinor": 0,
    "shippingMinor": 0,
    "taxMinor": 0,
    "totalMinor": 3000,
    "currency": "USD"
  },
  "quoteToken": "<opaque signed token>",
  "expiresAt": "2026-11-01T00:05:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `nodeId` | string | The current pinned published node. |
| `offers` | array<object> | Selected repriced offers, including allowed variants, quantity limits, availability and persisted timer deadline when configured. |
| `quote` | object | subtotalMinor, compareAtMinor, savingsMinor, discountMinor, shippingMinor, taxMinor, totalMinor and currency. Every amount is an integer minor-unit value from the server. |
| `quoteToken / expiresAt` | string | Opaque signed token bound to the buyer/session/domain, original payment, page version, selected identities, prices and expiration. Send unchanged on acceptance. |

**Errors**

- `400` {"error":"Send the X-V5-Domain header: the host the checkout is served on (host only, no scheme or path)."} when X-V5-Domain is missing or malformed; Malformed or unknown field, duplicate offer, non-published offer/variant, or invalid selection.
- `400` {"error":"Invalid checkout host"} when X-V5-Domain is missing or malformed; {"error":"Invalid request."} for a body, query or path that fails validation (strict objects).
- `401` {"error":"Charge authentication required"} (no key) or {"error":"Invalid API key"} (unknown, inactive or ownerless key).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Unknown or foreign session/checkout/domain. {"error":"Session not found."} (no or unknown flow session cookie) or {"error":"Checkout unavailable"} (checkout inactive, of another account, or served on another host).
- `409` Inactive node, unavailable or expired offer, exhausted quantity, or parent payment no longer eligible.
- `429` Rate limit exceeded on this route's own per-IP budget, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute), separate from the 300/min default. Body {"error":"Rate limit exceeded, retry in 1 minute"}. Refused before the handler runs.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity.

**Gotchas**

- Use only through the cookie-scoped storefront proxy. Never expose the server bearer.
- A displayed quote does not reserve a charge. Acceptance rechecks availability, lifecycle and totals under the session lock.
- Variant or quantity changes require a fresh quote; disable acceptance while the latest quote is pending.
- Client prices and payment-success claims are rejected. A free offer is permitted only when explicitly published as free with zero total.
- Verified simulations use the same published selections, variant/quantity constraints, server repricing and signed quote as live journeys. The quote alone does not create an order, reserve funds, send a payment or confirm an upsell. Only the subsequent confirmed action selects the live or verified simulated effect.
- Rate limit: this storefront runtime route counts its own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, held in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP), so every shopper behind one storefront shares the bucket. A 429 is returned before the handler runs: nothing was read, reserved, prepared or dispatched, and the same request can be resent after the window. It is never a payment decline.

#### Standalone runtime

The session, entry, lead, activity and completion of a standalone checkout.

##### `POST /v5/standalone/activity`

**Scope** `charges.write` - **Record bound checkout activity**

Records a pay_click or a cumulative engagement snapshot for the cookie-bound standalone session (checkout funnel reporting). viewId deduplicates; no browser session identifier is accepted.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `kind` | pay_click \| engagement | **yes** | Activity kind. |
| `viewId` | uuid | **yes** | Page view id chosen by the storefront; the same kind + viewId + activeMs is stored once. |
| `activeMs` | integer 0..1800000 | no | Cumulative active time of the view, engagement only; must be absent or 0 for pay_click. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com", "kind": "pay_click", "viewId": "11111111-1111-4111-8111-111111111111"}
```

**Response**

```json
{"ok":true}
```

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session of this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Standalone checkout required"}: a store checkout.
- `413` {"error":"Request body is too large"}: body over 2048 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per API instance), shared with every route that has no budget of its own.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure. Also activeMs above 0 with kind pay_click.

**Gotchas**

- Always {"ok":true} once authorized: a duplicate, a session no longer active/processing/unknown, or a session past 1000 activity rows records nothing.
- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Answers carry cache-control: no-store.

##### `POST /v5/standalone/completion`

**Scope** `charges.write` - **Read captured standalone completion**

Returns safe thank-you data for an actual canonical captured initial order owned by this session. Purchase deduplication uses the real order UUID. A capture later corrected as failed by verified provider reconciliation no longer counts: the route answers 409.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow` entry cookie. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com"}
```

**Response**

```json
{
  "isTest": false,
  "tracking": {},
  "receiptTotals": {
    "subtotalMinor": 3999,
    "shippingMinor": 0,
    "discountMinor": 0,
    "protectionMinor": 0,
    "taxMinor": 0,
    "taxIncluded": false
  },
  "order": {
    "id": "22222222-2222-4222-8222-222222222222",
    "currency": "USD",
    "amount_cents": 3999,
    "customer_email": "buyer@example.com",
    "card_brand": "Visa",
    "card_last4": "1234"
  },
  "published": {},
  "configuration": {},
  "pixels": []
}
```

| response field | type | description |
|---|---|---|
| `isTest` | boolean | True for a test order (test payment fact, test commerce, test customer or test session). Do not fire advertising events for it. |
| `receiptTotals` | object | Integer minor units: subtotalMinor, shippingMinor, discountMinor and protectionMinor from the immutable order quote and taxMinor from the payment fact (0 when absent or invalid), plus taxIncluded (true when the session tax mode is inclusive). |
| `order` | object | Buyer-scoped order: id, currency, amount_cents, customer_email, customer_info, provider_order_id, gateway_order_id, card_brand, card_last4 and line_items. Personal data: never log it. |
| `published / configuration / tracking` | object | Render data of the pinned checkout and allowlisted acquisition values. |
| `pixels` | array | Public pixel recipients; empty for a test payment. |

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Confirmation unavailable"}: not a standalone checkout, missing cookie, or no unexpired matching session. {"error":"Checkout unavailable"} also when the pinned configuration no longer resolves.
- `409` {"error":"Payment confirmation pending"}: no valid capture of the initial order yet, or its capture was corrected as failed.
- `413` {"error":"Request body is too large"}: body over the 1 MB global limit.
- `422` Live catalog or link refusal of the pinned offer: "Product <n> is unavailable for this account", "Product <n> currency differs from the checkout", "Product <n> requires a name, valid price and quantity", "Product <n> compare price is below price", "Add at least one product", or a saved-link integration refusal ("Select a configured 3DS integration owned by this account", "Select an enabled email sender owned by this account", "A country is not offered by this checkout"...).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per API instance), shared with every route that has no budget of its own.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Purchase deduplication uses the real order id (order.id).
- Answers carry cache-control: no-store.

##### `POST /v5/standalone/entry`

**Scope** `charges.write` - **Pin standalone entry and clean its URL**

Validates the raw, duplicate-free entry parameters and their HMAC, resolves the owned catalog, captures attribution, resolves published flow conditions and A/B before entry, and pins the immutable configuration in a server session. Returns the clean location and the Set-Cookie values for the server proxy to apply before its redirect. Customer prefill is accepted only in this POST body. A direct query is bounded to 8192 bytes; saved short links to 65536 bytes. A different checkout branch uses its own defaults unless it pins its own offer; source prices and products never cross branches.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout the published slug resolves to on this host; must match it and belong to the key's account. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `slug` | string | **yes** | Published checkout slug: lowercase letters, digits and hyphens, 1-60 characters, starting with a letter or digit. |
| `rawQuery` | string <= 8192 | no | Original URL query without the leading question mark, at most 8192 characters; default empty. |
| `prefill` | object | no | Optional customer prefill, accepted only here, never from the URL. Object of strings with the allowed keys email (<= 255, valid e-mail), first_name, last_name, city, state (<= 120), address, address2 (<= 255), postal_code, phone (<= 32), shipping_country (two uppercase letters). Empty strings are skipped; an unknown key answers 400; over 8192 bytes answers 413. Stored privately for the session; an e-mail also records a checkout lead. |
| `countryCode` | string \| null | no | Optional ISO 3166-1 alpha-2 country of the serving request (two uppercase letters), forwarded by the server proxy for flow routing. XX is treated as unknown. |
| `landingPageId` | uuid | no | Published landing page selected by the server entry route. |
| `landingFlowId` | uuid | no | Optional exact flow for landingPageId; requires that page. Restricted to the same account, published flow, authorized checkout and domain. Store carts retain their pinned flow; this field cannot reroute them. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | no | Optional. `__Host-kontrol_flow` (an existing entry session to reuse) and `__Host-kontrol_attribution` (prior attribution). |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com", "slug": "offer", "rawQuery": "sub1=campaign", "countryCode": "US"}
```

**Response**

```json
{
  "checkoutId": "22222222-2222-4222-8222-222222222222",
  "location": "/c/selected-offer",
  "cookies": [
    "__Host-kontrol_attribution=<opaque>; Path=/; HttpOnly; Secure; SameSite=Lax",
    "__Host-kontrol_flow=<opaque>; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400"
  ],
  "flow": true
}
```

| response field | type | description |
|---|---|---|
| `checkoutId` | uuid | Checkout of the created (or reused) session. It can differ from the requested checkoutId when a published flow routes to another checkout branch; the proxy must verify the same account and domain before redirecting. |
| `location` | string | Clean same-domain path /c/<slug>. The session itself travels in cookies. |
| `cookies` | string[] | Set-Cookie values (HttpOnly entry session and attribution cookies) for the server proxy to apply before its redirect. Never expose them to page scripts. |
| `flow` | boolean | True when the pinned session runs a published flow. |

**Errors**

- `400` rawQuery refusals: {"error":"Unknown parameter"}, "Duplicate parameter", "Parameter requires a value", "Malformed parameter encoding", "Invalid parameter key", "Customer prefill requires POST", "Link is too long. Use a short link", "Invalid signature", "Invalid attribution token" and the per-parameter validation messages. Prefill refusals: "Unknown customer prefill field", "Invalid customer email", "Invalid customer country". Malformed JSON body.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`. landingFlowId without landingPageId falls in this case (issue path landingPageId, message "A landing flow requires a landing page.").
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned. {"error":"Invalid checkout signature"}: signed parameters tampered with or unsigned. {"error":"Offer ownership conflicts with this flow"}.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Checkout unavailable"} also when the checkout is not standalone (or flow-link projected) or the slug resolves to another checkout. {"error":"Checkout not found"}, {"error":"A valid domain link is required"}, {"error":"Offer unavailable"}, {"error":"A valid flow link is required"}, {"error":"Checkout branch unavailable"}, {"error":"Flow link unavailable"}.
- `413` {"error":"Prefill exceeds the limit"}: prefill over 8192 bytes. {"error":"Request body is too large"}: body over 131072 bytes.
- `422` Live catalog or link refusal of the pinned offer: "Product <n> is unavailable for this account", "Product <n> currency differs from the checkout", "Product <n> requires a name, valid price and quantity", "Product <n> compare price is below price", "Add at least one product", or a saved-link integration refusal ("Select a configured 3DS integration owned by this account", "Select an enabled email sender owned by this account", "A country is not offered by this checkout"...).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Short links store commercial/content/pixel settings server-side. kt is a signed attribution/offer reference containing only link id/revision, never commercial payload, PII, card data or flow-session tokens.
- Only a freshly verified kt may restore stored short-link offer settings. An older attribution cookie retains reporting only and cannot replace direct-entry commercial defaults.
- countryCode is optional ISO-2 serving-request geography forwarded only by the authenticated server proxy; never take it from URL/customer prefill. Standalone store AOV is unknown/null.
- Public landing links may use /funnel/<pageId>?flow=<flowId> to disambiguate a reused page. The storefront reads only current published versions and forwards both IDs through private transport, removing flow from tracking. An ambiguous unscoped link fails closed. Historical revisions, foreign or archived flows and mismatched cart pins are never selected.
- Reuse: with no rawQuery, no prefill, no landingPageId and a live cookie session of the same checkout, the existing session is returned and its cookie refreshed; nothing new is pinned.
- Answers carry cache-control: no-store. The answer also sets referrer-policy: no-referrer.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

##### `POST /v5/standalone/lead`

**Scope** `charges.write` - **Record checkout contact submission**

Records an explicit contact submission for the cookie-bound standalone session: snapshots the validated contact, deduplicates by an HMAC of the e-mail per session, and appends a checkout.lead_captured event in the same transaction. The lead feeds standalone cart recovery. No personal data in URLs or logs.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |
| `customer` | object | **yes** | Strict contact object; unknown keys refused. |
| `customer.email` | string <= 255 | **yes** | Valid e-mail (trimmed, stored lowercase). |
| `customer.first_name / customer.last_name` | string <= 120 | no | Names. |
| `customer.phone` | string <= 32 | no | Phone number. |
| `customer.address / customer.address2` | string <= 255 | no | Street lines. |
| `customer.city / customer.state` | string <= 120 | no | City and state. |
| `customer.postal_code` | string <= 32 | no | Postal code. |
| `customer.shipping_country` | string, ^[A-Z]{2}$ | no | ISO country code. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com", "customer": {"email": "buyer@example.com"}}
```

**Response**

```json
{"ok":true}
```

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie or no live session of this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Standalone checkout required"}: a store checkout. {"error":"Checkout contact unavailable"}: the session is no longer active (for example payment processing).
- `413` {"error":"Request body is too large"}: body over 16384 bytes (route bodyLimit).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per API instance), shared with every route that has no budget of its own.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure. Also a contact value containing a control character.

**Gotchas**

- Replays are harmless: the same e-mail in the same session keeps one lead.
- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Answers carry cache-control: no-store.

##### `POST /v5/standalone/session`

**Scope** `charges.write` - **Read pinned standalone render input**

Private server renderer DTO from pinned immutable configuration. Live catalog availability, account/checkout/domain and cookie scope are rechecked. No signing or charge secrets are serialized. Also reports whether the pinned flow may save the card for post-sell offers (storesCard).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Standalone checkout of the key's account, matching the buyer session. Unknown extra body keys are ignored. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow=<43 base64url characters>` entry cookie (the buyer session issued at entry). Two cookies of that name, or a malformed value, count as missing. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com"}
```

**Response**

```json
{
  "published": {},
  "configuration": {},
  "document": {},
  "prefill": {},
  "ownedProductIds": [],
  "pixels": [],
  "tracking": {},
  "cookie": "__Host-kontrol_flow=<opaque>; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400",
  "flow": true,
  "storesCard": true
}
```

| response field | type | description |
|---|---|---|
| `published / configuration / document` | object | Pinned published checkout, its immutable entry configuration and the native page document to render. |
| `prefill` | object | Customer prefill captured at entry. Personal data: render server-side for this buyer only, never log it. |
| `ownedProductIds / pixels / tracking` | array / array / object | Account-owned products in the document, public pixel recipients and allowlisted acquisition values. No provider tokens. |
| `initialCartRevision` | string \| absent | Present when the session carries a landing-page selection: send it unchanged as commerce.initialCartRevision / initialCartRevision when preparing and reserving the order. |
| `initialSubscriptionEvidence` | object \| absent | Present when the pinned selection includes a subscription offer: the terms evidence the checkout must display. |
| `cookie` | string | Refreshed host-only entry cookie (`__Host-kontrol_flow`, HttpOnly, Secure, SameSite=Lax, Max-Age 86400) for the server proxy to set. |
| `flow` | boolean | True when the pinned session runs a published flow. |
| `storesCard` | boolean | True when the pinned flow version has post-sell steps, so the card may be saved for one-click offers. The checkout must then show the card-storage notice and send commerce.cardStorageConsent with the order. Presentation metadata only, never payment authority. False without a flow or without post-sell steps. |

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when checkoutId or domain is missing or malformed (zod parse, before the key is checked).
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account. {"error":"Checkout session expired"}: missing entry cookie, or no live session of this checkout and host.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the key's account has no active platform subscription (checked before the handler).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Standalone checkout required"}: the checkout is a store checkout. {"error":"Checkout unavailable"} also when the pinned configuration no longer resolves.
- `413` {"error":"Request body is too large"}: body over the 1 MB global limit.
- `422` Live catalog or link refusal of the pinned offer: "Product <n> is unavailable for this account", "Product <n> currency differs from the checkout", "Product <n> requires a name, valid price and quantity", "Product <n> compare price is below price", "Add at least one product", or a saved-link integration refusal ("Select a configured 3DS integration owned by this account", "Select an enabled email sender owned by this account", "A country is not offered by this checkout"...).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: this route's own per-IP bucket, RATE_LIMIT_CHECKOUT_RUNTIME (default 3000 requests per minute, in memory per API instance), separate from the 300/min default. Refused before the handler runs: nothing was read or changed.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Catalog availability is live: a product that became unavailable since entry makes the read answer 422; signed display and price overrides stay the immutable choices of the entry.
- Answers carry cache-control: no-store.
- Rate limit: own bucket of RATE_LIMIT_CHECKOUT_RUNTIME (default 3000) requests per minute per calling IP, in memory per API instance. The key is the calling server's address (the storefront proxy forwards the shopper IP only as X-V5-Buyer-IP, which this route does not read), so every shopper behind one storefront shares the bucket. A 429 is never a payment decline; resend the same request after the window.

#### Wallet and wire sessions

The payment methods of a session and its wallet and wire legs.

##### `POST /v5/payment-methods`

**Scope** `charges.write` - **Read checkout payment methods (storefront)**

Storefront runtime: which payment methods (card, wallet, wire, Apple Pay, Google Pay) the buyer session can use for a currency, optionally with the card presentation modes of its route. Reads only: selects, reserves and charges nothing.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string (max 253, lowercase host) | **yes** | Exact serving host of the session; no scheme or path. |
| `currency` | string (3 upper-case letters) | **yes** | ISO currency to evaluate. |
| `includeCardModes` | boolean; default `false` | no | Also return cardModes. A standalone session uses its published configuration ATRI. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "pay.example.com",
  "currency": "USD",
  "includeCardModes": true
}
```

**Response** `200`

```json
{
  "card": true,
  "wallet": false,
  "wire": false,
  "applePay": false,
  "googlePay": false,
  "cardModes": {
    "modes": [],
    "cardAvailable": true
  }
}
```

| response field | type | description |
|---|---|---|
| `card / wallet / wire / applePay / googlePay` | boolean | Method availability for the account, store and currency. |
| `cardModes` | object | Only with includeCardModes: {modes (s2s\|embedded\|hosted Stripe presentations), cardAvailable}. |

**Errors**

- `400` Invalid wire request (any body validation failure, strict body); or Invalid checkout host.
- `401` Charge authentication required; Invalid API key; or Checkout session expired (no or foreign buyer cookie).
- `402` A paid platform subscription is required (code subscription_required): the key owner account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Checkout payment route unavailable; Checkout unavailable; or Checkout host unavailable.
- `413` Body larger than 2 KB.

**Gotchas**

- Without includeCardModes the answer is the five booleans only.

##### `POST /v5/standalone/wallet-status`

**Scope** `charges.write` - **Read bound standalone wallet outcome**

Reads the actual owned order outcome for the HttpOnly session; never accepts a browser order or wallet session identifier. A capture later corrected as failed by verified provider reconciliation reads as declined with retryAllowed:false.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string <= 253, ^[a-z0-9][a-z0-9.-]*[a-z0-9]$ | **yes** | Exact lowercase serving hostname, no scheme, port, path or query. Must be the verified host of the published configuration (or an allowed link domain of the pinned saved link). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | Must carry exactly one `__Host-kontrol_flow` entry cookie. |

**Request body**

```json
{"checkoutId": "11111111-1111-4111-8111-111111111111", "domain": "pay.example.com"}
```

**Response**

```json
{
  "status": "approved",
  "retryAllowed": true,
  "orderId": "22222222-2222-4222-8222-222222222222",
  "flow": false
}
```

| response field | type | description |
|---|---|---|
| `status` | string | approved when the latest owned order has a valid capture; declined when that capture was later corrected as failed; otherwise the order status (for example pending or declined), or pending when the session has no order yet. |
| `retryAllowed` | boolean | False only when the capture was corrected as failed after the fact. Show a declined message and do not offer another payment from this session. True otherwise. |
| `orderId` | uuid \| null | Latest order owned by this session, or null. |
| `flow` | boolean | True when the session runs a published flow. |

**Errors**

- `400` Malformed or empty JSON body, answered by the body parser before the handler, for example {"error":"Body cannot be empty when content-type is set to 'application/json'"}.
- `400` `{"error":"Invalid request","details":{"issues":[{"path":"...","code":"...","message":"..."}]}}` when the body fails the route's zod schema (missing or malformed field, or an unknown key where the schema is strict): one issue per problem with its dotted `path` (empty for an unknown key), the zod `code` and its `message`.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header. {"error":"Invalid API key"}: unknown or inactive key, or a key without an owner account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` {"error":"Checkout unavailable"}: the checkout is not a checkout of the key's account, is inactive, or its store domain is paused or archived. {"error":"Checkout host unavailable"}: `domain` is not the verified, active published host of this checkout (nor an allowed domain of the pinned saved link). {"error":"Confirmation unavailable"}: not a standalone checkout, missing cookie, or no unexpired matching session.
- `413` {"error":"Request body is too large"}: body over the 1 MB global limit.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per API instance), shared with every route that has no budget of its own.
- `500` {"error":"Internal Server Error","requestId":"..."}: an unexpected failure.

**Gotchas**

- Never call this route from browser JavaScript and never put the key in a URL: the server that renders the checkout calls it with an API key of the checkout's account and forwards the buyer cookie.
- Answers carry cache-control: no-store.

##### `POST /v5/wire/check`

**Scope** `charges.write` - **Check a bank wire (storefront)**

Storefront runtime: read the wire session of the buyer (by orderId or sessionId) and, when a bank reconciler is registered, ask it for verified receipts (at most every 3 seconds); only an exact account, reference, amount and currency match settles it once. Expired sessions turn expired. A buyer "I paid" click never confirms payment.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string (max 253, lowercase host) | **yes** | Exact serving host of the session; no scheme or path. |
| `orderId` | uuid | no | Order of the wire session. |
| `sessionId` | uuid | no | Wire session id. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Cookie` | string | **yes** | The buyer's checkout session cookie, forwarded by the server that renders the checkout (the session the wire payment was started in). |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "pay.example.com",
  "sessionId": "11111111-1111-4111-8111-111111111111"
}
```

**Response**

```json
{
  "sessionId": "11111111-1111-4111-8111-111111111111",
  "orderId": "22222222-2222-4222-8222-222222222222",
  "status": "pending",
  "reference": "KT7Q2M9X",
  "amountCents": 5499,
  "currency": "USD",
  "details": [
    {
      "key": "account_holder",
      "label": "Beneficiary",
      "value": "Example Merchant LLC"
    },
    {
      "key": "account_number",
      "label": "Account number",
      "value": "000123456789"
    }
  ],
  "pollAfterMs": 10000,
  "monitorMode": "unconfigured",
  "flow": false,
  "shopId": null,
  "cartToken": ""
}
```

| response field | type | description |
|---|---|---|
| `sessionId / orderId` | uuid | Wire session and order. |
| `status` | string | pending \| paid \| failed \| expired. |
| `reference` | string | Payment reference the buyer must put on the transfer. |
| `amountCents / currency` | integer / string | Amount in minor units and currency. |
| `details[]` | object[] | Receiving bank details {key, label, value} (beneficiary, account number, routing number, IBAN, SWIFT, bank name and addresses, as configured). |
| `pollAfterMs` | integer | Suggested polling interval (10000). |
| `monitorMode` | string | connected when a bank reconciler is registered, else unconfigured (status then stays pending). |
| `flow / shopId / cartToken` | boolean / string \| null / string | Session context. |

**Errors**

- `400` Invalid wire request (any body validation failure, strict body); or Invalid checkout host.
- `401` {"error":"Charge authentication required"}: no `Authorization: Bearer` or `X-Api-Key` header; {"error":"Invalid API key"}: unknown or inactive key; {"error":"Checkout session unavailable"}: no buyer session cookie, or one of another session.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Wire payment not found; Checkout unavailable; or Checkout host unavailable.
- `409` Bank receipt identity conflicts; or Wire payment state conflicts.
- `413` Body larger than 2 KB.
- `502` Bank adapter returned another account.

**Gotchas**

- With no reconciler configured (monitorMode unconfigured) the status stays pending until settled by other means.

##### `POST /v5/wire/start`

**Scope** `charges.write` - **Start or resume a bank wire (storefront)**

Storefront runtime: for the prepared pending order of the buyer session, claim the payment for bank wire, pick a receiving bank account of the account (reserved 7 days) and return the transfer instructions. Calling again for the same order returns the same instructions. Never accepts an amount or a paid claim from the client.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Checkout of the key's account, matching the buyer session. |
| `domain` | string (max 253, lowercase host) | **yes** | Exact serving host of the session; no scheme or path. |
| `orderId` | uuid | **yes** | The order prepared for this session. |

**Request body**

```json
{
  "checkoutId": "11111111-1111-4111-8111-111111111111",
  "domain": "pay.example.com",
  "orderId": "22222222-2222-4222-8222-222222222222"
}
```

**Response**

```json
{
  "sessionId": "11111111-1111-4111-8111-111111111111",
  "orderId": "22222222-2222-4222-8222-222222222222",
  "status": "pending",
  "reference": "KT7Q2M9X",
  "amountCents": 5499,
  "currency": "USD",
  "details": [
    {
      "key": "account_holder",
      "label": "Beneficiary",
      "value": "Example Merchant LLC"
    },
    {
      "key": "account_number",
      "label": "Account number",
      "value": "000123456789"
    }
  ],
  "pollAfterMs": 10000,
  "monitorMode": "unconfigured",
  "flow": false,
  "shopId": null,
  "cartToken": ""
}
```

| response field | type | description |
|---|---|---|
| `sessionId / orderId` | uuid | Wire session and order. |
| `status` | string | pending \| paid \| failed \| expired. |
| `reference` | string | Payment reference the buyer must put on the transfer. |
| `amountCents / currency` | integer / string | Amount in minor units and currency. |
| `details[]` | object[] | Receiving bank details {key, label, value} (beneficiary, account number, routing number, IBAN, SWIFT, bank name and addresses, as configured). |
| `pollAfterMs` | integer | Suggested polling interval (10000). |
| `monitorMode` | string | connected when a bank reconciler is registered, else unconfigured (status then stays pending). |
| `flow / shopId / cartToken` | boolean / string \| null / string | Session context. |

**Errors**

- `400` Invalid wire request (any body validation failure, strict body); or Invalid checkout host.
- `401` Charge authentication required; Invalid API key; or Checkout session expired (no or foreign buyer cookie).
- `402` A paid platform subscription is required (code subscription_required): the key owner account has no paid or granted platform subscription. Also: The account has reached its monthly sales allowance. (or the subscription USD conversion rates are missing) for a live order.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"charges.write"} when the key's scopes lack charges.write; {"error":"Charge access denied"} when the key owner is banned.
- `404` Checkout unavailable; or Checkout host unavailable.
- `409` Wire order unavailable; or Another payment is already in progress.
- `413` Body larger than 2 KB.
- `422` This checkout requires a card (subscription opt-in or card storage consent); Checkout countries unavailable; Country is not supported by this checkout; Discount reservation expired; refresh the checkout; No bank account is available for this payment; or Bank account unavailable.

### KontrolPay

KontrolPay, the native payment processing product: the merchant application, balances and payouts, the reserve and the ledger.

#### Onboarding

The KontrolPay overview and the merchant application: steps, sealed values, documents, requests, the agreement, submission and withdrawal.

##### `GET /v1/kontrolpay`

**Scope** `kontrolpay.read` - **Read the KontrolPay overview**

Every KontrolPay application and account of the main account, what needs attention, whether a new application may be added, the default pricing and what to prepare. One call feeds the onboarding list, the menu count and the account switcher.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "applicationId": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
      "accountId": null,
      "gatewayId": null,
      "gatewayName": null,
      "dbaName": "Northwind Outfitters",
      "legalName": "Northwind Outfitters LLC",
      "primaryHost": "northwind.example",
      "label": "Northwind Outfitters",
      "applicationStatus": "draft",
      "accountStatus": null,
      "payoutsPaused": false,
      "displayStatus": "draft",
      "message": null,
      "payoutsPausedMessage": null,
      "openRequests": 0,
      "dueAt": null,
      "overdue": false,
      "progress": {
        "done": 4,
        "total": 6,
        "next": "documents"
      },
      "nextAction": "continue",
      "copiedFrom": null,
      "createdAt": "2026-11-18T10:00:00.000Z",
      "updatedAt": "2026-11-18T10:12:00.000Z"
    }
  ],
  "hasActivatedAccount": false,
  "accounts": [],
  "attention": [],
  "eligibility": {
    "canApply": true,
    "reason": "ok",
    "message": null,
    "openApplications": 1,
    "maxOpenApplications": 10
  },
  "pricing": {
    "currency": "USD",
    "discountRateBps": 790,
    "transactionFeeMinor": 45,
    "reserveRateBps": 1000,
    "reserveHoldDays": 90,
    "payoutDelayDays": 3,
    "payoutMinimumMinor": 0,
    "chargebackFeeMinor": 2500,
    "refundFeeMinor": 0
  },
  "requirements": {
    "eligibility": [
      "For companies registered in the United States",
      "A Kontrol account with an active subscription",
      "Every person listed lives in the United States, and every phone number is a United States number"
    ],
    "prepare": [
      "EIN",
      "For the director and each owner of 25% or more: Social Security number, date of birth, home address and a government ID",
      "Articles of incorporation and EIN letter",
      "Processing volumes and history"
    ],
    "prohibited": [
      "Example business that is not accepted"
    ]
  },
  "copySources": [
    {
      "applicationId": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
      "label": "Northwind Outfitters",
      "legalName": "Northwind Outfitters LLC"
    }
  ],
  "can": {
    "manage": true,
    "own": true,
    "reason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | One row per application, and its account once approved: ids, DBA, legal name, host, label, applicationStatus, accountStatus, displayStatus, shown message, open requests, due date, overdue, progress, nextAction. |
| `rows[].displayStatus` | enum | One word computed by the API: draft, in_review, action_required, declined, withdrawn, activation_pending, active, suspended, terminated, closed. |
| `rows[].nextAction` | enum | continue, sign, submit, answer, view or none, for this caller (role and ownership). An API key acts as the owner, so it can read sign here although only the owner in person can sign. |
| `hasActivatedAccount` | boolean | True once one account has been activated. |
| `accounts` | object[] | Approved accounts, for the account switcher of the three money pages. |
| `attention` | object[] | What needs the merchant, most urgent first: kind (terminated, suspended, payout_failed, action_required, payouts_paused, negative_balance, pricing_changed), label, message, dueAt, amountMinor, payoutId. |
| `eligibility` | object | canApply, reason, the sentence to show when false, open applications and their limit. |
| `pricing` | object | Platform defaults shown before an application exists. |
| `requirements` | object | Who can apply, what to prepare, what is not accepted. |
| `copySources` | object[] | Applications a new one can be copied from. |
| `can` | object | manage, own and the reason shown when a control is disabled. |

**Errors**

- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.read"} when the key's scopes lack kontrolpay.read; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `429` Rate limited per client address (the general limit of the API).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- A main account opens any number of KontrolPay accounts: one application is one business line, one account and one gateway.
- Gateway screens do not need this call: GET /v1/accounts carries the KontrolPay state of each gateway row.
- A terminated or closed account raises no payouts_paused item (its row still carries payoutsPaused). negative_balance is raised only when the balance of the account was already negative at 00:00 UTC today and still is: a refund of the day that pending sales cover is not an item.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- The response is private, no-store.

##### `POST /v1/kontrolpay/applications`

**Scope** `kontrolpay.write` - **Add an application**

Create a draft application with its DBA and first website, optionally as a server copy of the company and people of another application of the same main account. Returns HTTP 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `dbaName` | string 1..120 | **yes** | Doing-business-as name, 1 to 120 characters. Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `websiteUrl` | string | no | First website of this business line, normalised to https://<host><path> (format error otherwise). "" or null = none. |
| `copyFrom` | uuid | no | Application of the SAME main account to copy from, in any status. |

**Request body**

```json
{
  "dbaName": "Northwind Kids",
  "websiteUrl": "https://kids.northwind.example",
  "copyFrom": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01"
}
```

**Response** `201`

```json
{
  "application": {
    "id": "1b7e4d2a-9c3f-4a5b-8e6d-7f0a1b2c3d02",
    "label": "Northwind Kids",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 1,
    "updatedAt": "2026-11-18T10:00:00.000Z",
    "submittedAt": null,
    "message": null,
    "copiedFrom": {
      "applicationId": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
      "label": "Northwind Outfitters"
    }
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": false,
      "missing": [
        "businessCategory",
        "productDescription"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": false,
      "missing": [
        "monthlyVolumeMinor"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 2,
    "total": 6,
    "next": "activity",
    "canSubmit": false,
    "blocking": [
      "activity",
      "processing",
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "copied": {
    "fields": [
      "entityType",
      "legalName",
      "registeredAddress"
    ],
    "persons": 1,
    "sensitive": 5,
    "documents": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |
| `copied` | object \| null | What the server copied, by name and count only: fields, persons, sensitive, documents. Null without copyFrom. |

**Errors**

- `400` invalid_request: Check the highlighted fields. ; identity_in_free_text: Do not enter identity or tax numbers in this field.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` copy_source_not_found: The application to copy was not found.
- `409` applications_closed: KontrolPay is not accepting new applications right now. ; applications_blocked: New KontrolPay applications are not available for this account. Contact support. ; too_many_open_applications: You already have {n} applications in progress. Wait for a decision or withdraw one before adding another.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `422` document_quota: Document limit reached. Remove a file first.
- `429` Rate limited per client address: 10 requests per minute on this route.
- `503` vault_unavailable: Identity data and documents cannot be saved right now. Nothing was stored. Try again later.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- A copy duplicates the business step, the persons, every sealed value (re-sealed for the new application) and the active formation, tax, address and identity documents. It never copies the activity or processing steps, the agreement, requests, notes, events or decisions. Nothing sealed is returned.
- The limit of applications in progress (draft, submitted, in review, information requested) is counted per main account.
- vault_unavailable and document_quota can only be answered with copyFrom; nothing is created then.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `GET /v1/kontrolpay/applications/:id`

**Scope** `kontrolpay.read` - **Read one application**

The complete view of one application: values, masks, documents, requests, agreement summary, steps, progress, what the caller may do, and the account sheet once approved.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 7,
    "copiedFrom": null,
    "createdAt": "2026-11-18T10:00:00.000Z",
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "decidedAt": null,
    "purgedAt": null,
    "message": null,
    "values": {
      "business": {
        "entityType": "llc",
        "legalName": "Northwind Outfitters LLC",
        "taxIdType": "ein",
        "formationState": "DE",
        "formationDate": "2021-03-15",
        "registeredAddress": {
          "line1": "100 Example Street",
          "line2": null,
          "city": "Wilmington",
          "state": "DE",
          "postalCode": "19801",
          "country": "US"
        },
        "operatingAddress": {
          "line1": "100 Example Street",
          "line2": null,
          "city": "Wilmington",
          "state": "DE",
          "postalCode": "19801",
          "country": "US"
        },
        "businessPhone": "+13025550100",
        "businessEmail": "office@northwind.example"
      },
      "activity": {
        "dbaName": "Northwind Outfitters",
        "otherDbaNames": [],
        "businessCategory": "example_category",
        "websiteUrls": [
          "https://northwind.example"
        ],
        "productDescription": "Outdoor clothing sold online.",
        "statementDescriptor": "NORTHWIND",
        "supportEmail": "support@northwind.example",
        "supportPhone": "+13025550101",
        "billingModels": [
          "one_time"
        ],
        "goodsType": "physical",
        "fulfilment": {
          "by": "self",
          "shipsFrom": "US",
          "averageDeliveryDays": 4
        },
        "refundPolicyDays": 30,
        "refundPolicyUrl": null,
        "nonUsBuyersSharePct": 5,
        "marketingChannels": [
          "paid_social",
          "email"
        ]
      },
      "processing": {
        "monthlyVolumeMinor": 12000000,
        "averageTicketMinor": 6500,
        "highestTicketMinor": 24000,
        "recurringSharePct": 0,
        "hasProcessedBefore": true,
        "processors": [
          {
            "processorName": "Example Processor",
            "from": "2022-01-01",
            "to": null
          }
        ],
        "chargebackRateBps": 40,
        "refundRateBps": 300,
        "everTerminated": false,
        "terminationDetails": null,
        "inMonitoringProgram": false
      },
      "people": {
        "persons": [
          {
            "id": "2a7c9e1b-5d3f-4b8a-9c6e-1f2a3b4c5d06",
            "position": 0,
            "roles": [
              "director",
              "beneficial_owner",
              "signer"
            ],
            "firstName": "Jane",
            "middleInitial": null,
            "lastName": "Example",
            "title": "Managing member",
            "ownershipBps": 10000,
            "email": "jane@northwind.example",
            "phone": "+13025550102",
            "residenceCountry": "US",
            "idDocumentType": "passport",
            "idIssuer": "US",
            "idExpiresOn": "2031-06-30"
          }
        ],
        "allOwnersListed": true
      }
    },
    "sensitive": {
      "business": {
        "ein": {
          "set": true,
          "last4": "0000"
        }
      },
      "persons": {
        "2a7c9e1b-5d3f-4b8a-9c6e-1f2a3b4c5d06": {
          "ssn": {
            "set": true,
            "last4": "0000"
          },
          "dob": {
            "set": true
          },
          "idNumber": {
            "set": true,
            "last4": "0000"
          },
          "homeAddress": {
            "set": true
          }
        }
      }
    },
    "documents": [
      {
        "id": "9d4e6f8a-2b1c-4d3e-8f7a-6b5c4d3e2f10",
        "kind": "ein_letter",
        "subject": "business",
        "contentType": "application/pdf",
        "sizeBytes": 182044,
        "displayName": "ein-letter.pdf",
        "uploadedAt": "2026-11-18T10:12:00.000Z",
        "copied": false
      }
    ],
    "requiredDocuments": [
      {
        "kind": "articles_of_incorporation",
        "subject": "business",
        "label": "Articles of incorporation",
        "minimum": 1,
        "satisfied": false
      },
      {
        "kind": "ein_letter",
        "subject": "business",
        "label": "EIN letter",
        "minimum": 1,
        "satisfied": true
      }
    ],
    "agreement": null,
    "requests": []
  },
  "account": null,
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 4,
    "total": 6,
    "next": "documents",
    "canSubmit": false,
    "blocking": [
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "prefill": {
    "refundPolicyUrl": {
      "options": [
        "https://northwind.example/refunds"
      ],
      "source": "stores"
    }
  },
  "catalog": {
    "entityTypes": [
      {
        "value": "llc",
        "label": "LLC"
      },
      {
        "value": "c_corp",
        "label": "C corporation"
      }
    ],
    "categories": [
      {
        "value": "example_category",
        "label": "Example category"
      }
    ],
    "usStates": [
      {
        "value": "DE",
        "label": "Delaware"
      }
    ],
    "documentKinds": [
      {
        "value": "ein_letter",
        "label": "EIN letter"
      },
      {
        "value": "articles_of_incorporation",
        "label": "Articles of incorporation"
      }
    ],
    "personRoles": [
      {
        "value": "director",
        "label": "Director"
      },
      {
        "value": "beneficial_owner",
        "label": "Beneficial owner"
      },
      {
        "value": "signer",
        "label": "Signer"
      }
    ],
    "idDocumentTypes": [
      {
        "value": "passport",
        "label": "Passport"
      }
    ],
    "billingModels": [
      {
        "value": "one_time",
        "label": "One-time"
      }
    ],
    "goodsTypes": [
      {
        "value": "physical",
        "label": "Physical"
      }
    ],
    "marketingChannels": [
      {
        "value": "paid_social",
        "label": "Paid social"
      },
      {
        "value": "email",
        "label": "E-mail"
      }
    ],
    "reasonCodes": [
      {
        "value": "unreadable",
        "label": "Unreadable"
      }
    ],
    "limits": {
      "documentMaxBytes": 10485760,
      "documentsPerKind": 6,
      "documentsPerApplication": 60,
      "documentBytesPerAccount": 2147483648,
      "persons": 10,
      "websiteUrls": 10
    },
    "prohibited": [
      "Example business that is not accepted"
    ]
  },
  "pricing": {
    "currency": "USD",
    "discountRateBps": 790,
    "transactionFeeMinor": 45,
    "reserveRateBps": 1000,
    "reserveHoldDays": 90,
    "payoutDelayDays": 3,
    "payoutMinimumMinor": 0,
    "chargebackFeeMinor": 2500,
    "refundFeeMinor": 0
  },
  "timeline": [
    {
      "id": "1042",
      "at": "2026-11-18T10:00:00.000Z",
      "action": "application_created",
      "label": "Application created",
      "message": null
    }
  ],
  "copySources": []
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |

**Errors**

- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.read"} when the key's scopes lack kontrolpay.read; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` not_found: Not found.
- `429` Rate limited per client address (the general limit of the API).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Sealed values (EIN, SSN, date of birth, ID number, home address) are never returned: only { set, last4 }, and set alone for the date of birth and the home address.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- The response is private, no-store.

##### `GET /v1/kontrolpay/applications/:id/agreement`

**Scope** `kontrolpay.read` - **Read the agreement**

The agreement of the application as it stands: unavailable with what is missing, a preview to sign, or the signed text.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Response**

```json
{
  "agreement": {
    "state": "preview",
    "contentHash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "snapshot": {
      "product": "kontrolpay",
      "title": "KontrolPay Merchant Agreement",
      "version": "example-1",
      "provisional": true,
      "provider": {
        "name": "Example Provider",
        "address": "1 Example Way, Example City"
      },
      "client": {
        "legalName": "Northwind Outfitters LLC",
        "dbaName": "Northwind Outfitters",
        "entityType": "llc",
        "registeredAddress": {
          "line1": "100 Example Street",
          "line2": null,
          "city": "Wilmington",
          "state": "DE",
          "postalCode": "19801",
          "country": "US"
        },
        "signer": {
          "firstName": "Jane",
          "lastName": "Example",
          "title": "Managing member",
          "email": "owner@example.test"
        }
      },
      "pricing": {
        "currency": "USD",
        "discountRateBps": 790,
        "transactionFeeMinor": 45,
        "reserveRateBps": 1000,
        "reserveHoldDays": 90,
        "payoutDelayDays": 3,
        "payoutMinimumMinor": 0,
        "chargebackFeeMinor": 2500,
        "refundFeeMinor": 0
      },
      "consents": [
        {
          "key": "electronicRecords",
          "label": "Consent text served by the agreement template."
        },
        {
          "key": "accuracyAndAuthority",
          "label": "Consent text served by the agreement template."
        },
        {
          "key": "screening",
          "label": "Consent text served by the agreement template."
        },
        {
          "key": "taxpayerCertification",
          "label": "Consent text served by the agreement template."
        },
        {
          "key": "agreement",
          "label": "Consent text served by the agreement template."
        },
        {
          "key": "acceptableUse",
          "label": "Consent text served by the agreement template."
        }
      ],
      "sections": [
        {
          "title": "1. Scope",
          "paragraphs": [
            "The response contains the complete agreement text."
          ]
        }
      ]
    },
    "missing": [],
    "id": null,
    "signedAt": null,
    "signature": null,
    "signerEmail": null
  },
  "canSign": true,
  "revision": 7
}
```

| response field | type | description |
|---|---|---|
| `agreement.state` | unavailable \| preview \| signed | unavailable lists the field keys still missing in agreement.missing. |
| `agreement.contentHash` | string \| null | 64 lower-case hex characters: the hash to send back when signing. |
| `agreement.snapshot` | object \| null | Title, version, provisional flag, provider, client block, pricing, the six consents and the complete sections. |
| `canSign` | boolean | True for the main account owner in person when a preview exists and the application is editable; always false for an API key (a key cannot sign). |
| `revision` | integer | Application revision to send as expectedRevision. |

**Errors**

- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.read"} when the key's scopes lack kontrolpay.read; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` not_found: Not found.
- `429` Rate limited per client address (the general limit of the API).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- This route never answers 409: an agreement that cannot be generated yet is state "unavailable".
- snapshot.provisional true means the text is provisional: the final agreement is presented for acceptance before activation.
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- The response is private, no-store.

##### `GET /v1/kontrolpay/applications/:id/agreement/pdf`

**Scope** `kontrolpay.read` - **Download the agreement PDF**

The agreement as a PDF file (content-type application/pdf): the signed text when signed, else the preview.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Response** `200` (application/pdf)

No example body: see the purpose above for what the response carries.

**Errors**

- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.read"} when the key's scopes lack kontrolpay.read; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` not_found: Not found.
- `409` agreement_unavailable: Complete the previous steps to generate the agreement.
- `429` Rate limited per client address (the general limit of the API).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- The response is bytes, not JSON, sent as an attachment named KontrolPay-Agreement-<DBA slug>-<first 8 characters of the application id>.pdf.
- agreement_unavailable while the previous steps are incomplete.
- The response is private, no-store.

##### `POST /v1/kontrolpay/applications/:id/agreement/sign`

**Scope** `kontrolpay.write` - **Sign the agreement**

The main account owner signs the agreement he read. The signature evidence is kept and never rewritten.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedRevision` | integer >= 1 | **yes** | The revision last read. A stale value answers 409 and changes nothing. |
| `contentHash` | string | **yes** | The contentHash of the preview that was read (64 lower-case hex characters). |
| `signature` | string 1..201 | **yes** | Full name of the signatory exactly as printed in the agreement (signature_mismatch otherwise). Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `consents` | object | **yes** | Strict object of the six consents below, each literally true. |
| `consents.electronicRecords` | true | **yes** | Consent "electronicRecords", must be literally true (false or absent = required). |
| `consents.accuracyAndAuthority` | true | **yes** | Consent "accuracyAndAuthority", must be literally true (false or absent = required). |
| `consents.screening` | true | **yes** | Consent "screening", must be literally true (false or absent = required). |
| `consents.taxpayerCertification` | true | **yes** | Consent "taxpayerCertification", must be literally true (false or absent = required). |
| `consents.agreement` | true | **yes** | Consent "agreement", must be literally true (false or absent = required). |
| `consents.acceptableUse` | true | **yes** | Consent "acceptableUse", must be literally true (false or absent = required). |

**Request body**

```json
{
  "expectedRevision": 7,
  "contentHash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "signature": "Jane Example",
  "consents": {
    "electronicRecords": true,
    "accuracyAndAuthority": true,
    "screening": true,
    "taxpayerCertification": true,
    "agreement": true,
    "acceptableUse": true
  }
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 8,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null,
    "agreement": {
      "id": "e5f6a7b8-c9d0-4e1f-a2b3-c4d5e6f7a818",
      "version": "example-1",
      "provisional": true,
      "contentHash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "signedAt": "2026-11-19T09:30:00.000Z",
      "signerName": "Jane Example",
      "signerEmail": "owner@example.test"
    }
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 6,
    "total": 6,
    "next": null,
    "canSubmit": true,
    "blocking": []
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": true,
    "withdraw": true,
    "copy": true,
    "reason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |

**Errors**

- `400` signature_mismatch: Type the full name of the signatory shown in the agreement. ; invalid_request: Check the highlighted fields.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay."; api_key_refused: "Sign the KontrolPay agreement in the dashboard. An API key cannot sign it." for any API key, before anything is read; owner_required: "Only the main account owner can sign, submit or withdraw an application.".
- `404` not_found: Not found.
- `409` agreement_stale: The agreement changed. Reload it and sign again. ; agreement_unavailable: Complete the previous steps to generate the agreement. ; agreement_signed: This agreement is already signed. ; application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; application_changed: This application changed. Reload before saving.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 5 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- agreement_stale: the agreement changed since it was read; read it again and sign the new hash.
- A later save that changes the client block or the pricing clears the signature.
- Evidence kept: who signed, when, the client address, the user agent, the content hash and an evidence hash.
- Signing content that was already signed keeps the first evidence record; the repeated act is journaled with its own client address and user agent.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `POST /v1/kontrolpay/applications/:id/documents`

**Scope** `kontrolpay.write` - **Upload a document**

Upload one file of an application. The request body is the file bytes (content-type application/octet-stream); the parameters travel in the query. Returns HTTP 201, or 200 when the same bytes already exist for that kind and subject.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum | **yes** | articles_of_incorporation, ein_letter, government_id_front, government_id_back, proof_of_address, processing_statement, business_license or other. |
| `subject` | string 1..60 | **yes** | "business" or "person:<uuid>" of a person of this application. |
| `replaces` | uuid | no | Document of this application that the upload replaces. |
| `requestId` | uuid | no | Request item of this application that the upload answers. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(file bytes)` | binary, 1 byte to 10485760 bytes | **yes** | The raw file: PDF, JPEG or PNG, recognised from its first bytes. Empty = 400 document_empty; larger = 413 document_too_large. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-kontrolpay-filename` | string | no | encodeURIComponent(file name), at most 1024 bytes. An undecodable value means no name; an upload is never refused for its name. |
| `Content-Type` | "application/octet-stream" | no | The only accepted declared type (absent is accepted too). Any other value answers 415 document_type_refused before the body is read. |

**Response** `201`

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 7,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null,
    "documents": [
      {
        "id": "9d4e6f8a-2b1c-4d3e-8f7a-6b5c4d3e2f10",
        "kind": "ein_letter",
        "subject": "business",
        "contentType": "application/pdf",
        "sizeBytes": 182044,
        "displayName": "ein-letter.pdf",
        "uploadedAt": "2026-11-18T10:12:00.000Z",
        "copied": false
      }
    ],
    "requiredDocuments": [
      {
        "kind": "articles_of_incorporation",
        "subject": "business",
        "label": "Articles of incorporation",
        "minimum": 1,
        "satisfied": false
      },
      {
        "kind": "ein_letter",
        "subject": "business",
        "label": "EIN letter",
        "minimum": 1,
        "satisfied": true
      }
    ]
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 4,
    "total": 6,
    "next": "documents",
    "canSubmit": false,
    "blocking": [
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "document": {
    "id": "9d4e6f8a-2b1c-4d3e-8f7a-6b5c4d3e2f10",
    "kind": "ein_letter",
    "subject": "business",
    "contentType": "application/pdf",
    "sizeBytes": 182044,
    "displayName": "ein-letter.pdf",
    "uploadedAt": "2026-11-18T10:12:00.000Z",
    "copied": false
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |
| `document` | object | The stored document: id, kind, subject, contentType, sizeBytes, displayName (sanitised by the server), uploadedAt, copied. |

**Errors**

- `400` document_empty: The file is empty. ; invalid_request: Check the highlighted fields.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` document_not_found: Document not found. ; unknown_person: Unknown person. ; not_found: Not found.
- `409` request_closed: This request is closed. ; application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; field_locked: Only the requested items can be changed.
- `413` document_too_large: The file is larger than 10 MB.
- `415` document_type_refused: Only PDF, JPEG and PNG files are accepted.
- `422` document_quota: Document limit reached. Remove a file first.
- `429` Rate limited per client address: 30 requests per minute on this route.
- `503` vault_unavailable: Identity data and documents cannot be saved right now. Nothing was stored. Try again later.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Accepted types are PDF, JPEG and PNG, recognised from the first bytes, up to 10 MB (10485760 bytes).
- Limits: 6 active files per kind and subject, 60 rows per application, and a byte quota per main account (catalog.limits).
- In an application never submitted, replaces deletes the old file at once; after a submission the old file is kept as replaced.
- Files are stored encrypted. A merchant can list a document but not download it.
- A declared content-type other than application/octet-stream answers 415 document_type_refused before the body is read.
- A subject that names a person who is not a person of this application answers 404 unknown_person and stores nothing.
- A requestId that names a closed item answers 409 request_closed; one that names an item of another kind or subject answers 400 invalid_request. The item of a Documents step requested as a whole is answered by an upload of any document of the application.
- With a requestId, a file the application already holds for that kind and subject is accepted as the answer: the route answers 200 with the stored document and the item becomes submitted. The reviewer can reject it again.
- An upload that answers a document item replaces the file that item names, and requests[].documentId then names the new file: the next answer replaces that one. A replaces value that names the file of the item, or an earlier file of that kind and subject that was already replaced, is accepted; any other unknown file answers 404 document_not_found.
- While information is requested only the keys of steps[].editable can change: the requested items, and what an answer made required and is still missing (a field, a sealed value, a document). A value that is held stays locked. A write on anything else is refused whole with field_locked.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.
- The query is strict: an unknown query parameter answers invalid_request.

##### `DELETE /v1/kontrolpay/applications/:id/documents/:documentId`

**Scope** `kontrolpay.write` - **Remove a document**

Remove a document from an application that was never submitted. The file is deleted for good.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |
| `documentId` | uuid | **yes** | Document id of this application. |

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 7,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null,
    "documents": [
      {
        "id": "9d4e6f8a-2b1c-4d3e-8f7a-6b5c4d3e2f10",
        "kind": "ein_letter",
        "subject": "business",
        "contentType": "application/pdf",
        "sizeBytes": 182044,
        "displayName": "ein-letter.pdf",
        "uploadedAt": "2026-11-18T10:12:00.000Z",
        "copied": false
      }
    ]
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 4,
    "total": 6,
    "next": "documents",
    "canSubmit": false,
    "blocking": [
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |
| `ok` | boolean | Always true on success. |

**Errors**

- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` document_not_found: Document not found. ; not_found: Not found.
- `409` application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; field_locked: Only the requested items can be changed.
- `429` Rate limited per client address: 30 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- After a first submission a document is replaced by a new upload, never removed.
- A document of another application answers 404 document_not_found and changes nothing.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `POST /v1/kontrolpay/applications/:id/requests/:requestId/answer`

**Scope** `kontrolpay.write` - **Answer a request item**

Answer one information request item: a written answer to a question, or a confirmation for an item resolved elsewhere.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |
| `requestId` | uuid | **yes** | Request item id of this application. An item of another application answers 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `answer` | string 1..2000 | no | Answer to a question item. Exactly one of answer and confirm (both or neither = invalid_request, needs_one). Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `confirm` | boolean | no | Literally true, for an item that needs no text. |

**Request body**

```json
{
  "answer": "The store ships from our own warehouse in Delaware."
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "info_requested",
    "displayStatus": "action_required",
    "revision": 11,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null,
    "requests": [
      {
        "id": "4e2f6a8c-0b1d-4c3e-9a7f-5d6e7f8a9b12",
        "kind": "question",
        "stepKey": null,
        "fieldKey": null,
        "personId": null,
        "documentKind": null,
        "documentId": null,
        "label": "Question",
        "message": "Where do you ship from?",
        "status": "submitted",
        "reasonCode": null,
        "reasonText": null,
        "dueAt": "2026-11-25T23:59:59.000Z",
        "overdue": false,
        "requestedAt": "2026-11-20T15:00:00.000Z",
        "answeredAt": "2026-11-20T15:00:00.000Z",
        "answer": "The store ships from our own warehouse in Delaware."
      }
    ]
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 6,
    "total": 6,
    "next": null,
    "canSubmit": true,
    "blocking": []
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": true,
    "withdraw": true,
    "copy": true,
    "reason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |

**Errors**

- `400` invalid_request: Check the highlighted fields. ; identity_in_free_text: Do not enter identity or tax numbers in this field.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` not_found: Not found.
- `409` request_closed: This request is closed. ; wrong_answer_kind: This item is answered from its own form. ; application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 30 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- What each item kind takes here: a question takes answer; a field, a sealed field or a step takes confirm: true (the stored value is correct as it stands).
- A document item is answered by an upload and an agreement item by the signature: this route then answers wrong_answer_kind. Text sent to an item that is not a question, or confirm sent to a question, answers the same.
- A field, a sealed field or a step is also answered from its own form: a step save marks the step item of that step and each field item whose value it changed, a sealed save marks the sealed items it saved and the step item of its subject.
- When no item is left open the owner sends the application back with POST .../submit.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `PUT /v1/kontrolpay/applications/:id/sensitive`

**Scope** `kontrolpay.write` - **Save sealed values**

Seal identity values of the business or of one person. Nothing sealed is ever returned: the response carries masks.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `subject` | string 1..60 | **yes** | "business" (accepts ein) or "person:<uuid>" of a person of THIS application (accepts ssn, dob, idNumber, homeAddress). A field the subject does not accept is not_allowed. |
| `sensitive` | object | **yes** | Strict object of the values to seal, at least one key (none = invalid_request with fieldErrors.sensitive = required). null clears a value (in a draft only). Never logged, never echoed: the answer carries masks. |
| `sensitive.ein` | string <= 64 \| null | no | Subject business only: 9 digits (spaces and hyphens allowed), not nine times the same digit. |
| `sensitive.ssn` | string <= 64 \| null | no | Subject person only: 9 digits; area not 000, 666 or 9xx, group not 00, serial not 0000. |
| `sensitive.dob` | string <= 64 \| null | no | Subject person only: date of birth YYYY-MM-DD, a real day, not in the future, age 18 to 120. |
| `sensitive.idNumber` | string <= 64 \| null | no | Subject person only: identity document number, 4 to 40 letters and digits once spaces and hyphens are removed (stored upper case). |
| `sensitive.homeAddress` | object \| null | no | Subject person only: US address object, strict: line1 (required, <= 120, no PO box), line2 (<= 120), city (required, <= 80), state (required, a US state, district or territory code), postalCode (required, 12345 or 12345-6789), country (required, "US"). Another key is not_allowed; errors are keyed by line, for example registeredAddress.line1. Errors are keyed homeAddress.<part>. |
| `sensitive.homeAddress.line1` | string <= 120 | no | Subject person only: Street line, no PO box. Required inside the object. |
| `sensitive.homeAddress.line2` | string <= 120 | no | Subject person only: Second line. |
| `sensitive.homeAddress.city` | string <= 80 | no | Subject person only: City. Required inside the object. |
| `sensitive.homeAddress.state` | string | no | Subject person only: A US state, district or territory code. Required inside the object. |
| `sensitive.homeAddress.postalCode` | string | no | Subject person only: 12345 or 12345-6789. Required inside the object. |
| `sensitive.homeAddress.country` | string | no | Subject person only: Always "US". Required inside the object. |

**Request body**

```json
{
  "subject": "person:2a7c9e1b-5d3f-4b8a-9c6e-1f2a3b4c5d06",
  "sensitive": {
    "dob": "1980-01-01",
    "homeAddress": {
      "line1": "100 Example Street",
      "line2": null,
      "city": "Wilmington",
      "state": "DE",
      "postalCode": "19801",
      "country": "US"
    }
  }
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 7,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null,
    "sensitive": {
      "business": {
        "ein": {
          "set": true,
          "last4": "0000"
        }
      },
      "persons": {
        "2a7c9e1b-5d3f-4b8a-9c6e-1f2a3b4c5d06": {
          "ssn": {
            "set": true,
            "last4": "0000"
          },
          "dob": {
            "set": true
          },
          "idNumber": {
            "set": true,
            "last4": "0000"
          },
          "homeAddress": {
            "set": true
          }
        }
      }
    }
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 4,
    "total": 6,
    "next": "documents",
    "canSubmit": false,
    "blocking": [
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "masked": {
    "dob": {
      "set": true
    },
    "homeAddress": {
      "set": true
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |
| `masked` | object | The masks of the fields just saved: { set, last4 }; set alone for dob and homeAddress. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |

**Errors**

- `400` invalid_request: Check the highlighted fields.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` unknown_person: Unknown person. ; not_found: Not found.
- `409` application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; field_locked: Only the requested items can be changed.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 20 requests per minute on this route.
- `503` vault_unavailable: Identity data and documents cannot be saved right now. Nothing was stored. Try again later.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Without the identity vault the route answers 503 vault_unavailable and stores nothing.
- While information is requested, a sealed save also answers the open step item of its subject: the Business step for the EIN, the People step for a person.
- While information is requested only the keys of steps[].editable can change: the requested items, and what an answer made required and is still missing (a field, a sealed value, a document). A value that is held stays locked. A write on anything else is refused whole with field_locked.
- A subject of another application answers 404 unknown_person and changes nothing.
- No expectedRevision on this route; the application revision is not changed.
- Bank account numbers are not accepted in this release.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `PUT /v1/kontrolpay/applications/:id/steps/:step`

**Scope** `kontrolpay.write` - **Save a form step**

Save the plain fields of one of the four form steps. The status never changes on a save.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |
| `step` | business \| activity \| processing \| people | **yes** | The step to save. Any other value answers 400 unknown_step. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedRevision` | integer >= 1 | **yes** | The revision last read. A stale value answers 409 and changes nothing. |
| `values` | object | **yes** | Fields of that step (strict: a key of another step or an unknown key is refused), listed below with their step in brackets. Every field is optional (absent = unchanged) and nullable (null or "" clears it), except dbaName (never emptied) and the required keys inside persons[] and fulfilment. |
| `values.entityType` | llc \| c_corp \| s_corp \| partnership \| sole_proprietorship \| non_profit | no | [business] Legal form. |
| `values.legalName` | string <= 160 | no | [business] Registered legal name. Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.taxIdType` | ein \| ssn | no | [business] Which tax id the business uses. |
| `values.formationState` | US state code | no | [business] State of formation (upper-cased). |
| `values.formationDate` | YYYY-MM-DD | no | [business] Formation date, a real calendar day. |
| `values.registeredAddress` | object | no | [business] US address object, strict: line1 (required, <= 120, no PO box), line2 (<= 120), city (required, <= 80), state (required, a US state, district or territory code), postalCode (required, 12345 or 12345-6789), country (required, "US"). Another key is not_allowed; errors are keyed by line, for example registeredAddress.line1. |
| `values.registeredAddress.line1` | string <= 120 | no | [business] Street line, no PO box. Required inside the object. |
| `values.registeredAddress.line2` | string <= 120 | no | [business] Second line. |
| `values.registeredAddress.city` | string <= 80 | no | [business] City. Required inside the object. |
| `values.registeredAddress.state` | string | no | [business] A US state, district or territory code. Required inside the object. |
| `values.registeredAddress.postalCode` | string | no | [business] 12345 or 12345-6789. Required inside the object. |
| `values.registeredAddress.country` | string | no | [business] Always "US". Required inside the object. |
| `values.operatingAddress` | object | no | [business] Same shape as registeredAddress. |
| `values.operatingAddress.line1` | string <= 120 | no | [business] Street line, no PO box. Required inside the object. |
| `values.operatingAddress.line2` | string <= 120 | no | [business] Second line. |
| `values.operatingAddress.city` | string <= 80 | no | [business] City. Required inside the object. |
| `values.operatingAddress.state` | string | no | [business] A US state, district or territory code. Required inside the object. |
| `values.operatingAddress.postalCode` | string | no | [business] 12345 or 12345-6789. Required inside the object. |
| `values.operatingAddress.country` | string | no | [business] Always "US". Required inside the object. |
| `values.businessPhone` | string <= 40 | no | [business] A US phone number; stored as +1 followed by 10 digits. |
| `values.businessEmail` | e-mail <= 254 | no | [business] Business e-mail. |
| `values.dbaName` | string 1..120 | no | [activity] Doing-business-as name (names the row everywhere). Can change, never be emptied: null or "" is refused. Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.otherDbaNames` | string[] <= 10 (each <= 120) | no | [activity] Other trade names. |
| `values.businessCategory` | string | no | [activity] One of catalog.categories[].value (in the application view); anything else is not_allowed. |
| `values.websiteUrls` | string[] <= 20 | no | [activity] Websites, each normalised to https://<host><path> (no query, fragment, port or credentials, <= 300 characters). |
| `values.productDescription` | string <= 2000 | no | [activity] What is sold. Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.statementDescriptor` | string 5..22 | no | [activity] Card statement descriptor: letters, digits, space, ".", "&", "-", with at least one letter. |
| `values.supportEmail` | e-mail <= 254 | no | [activity] Customer support e-mail. |
| `values.supportPhone` | string <= 40 | no | [activity] Customer support US phone (stored +1 and 10 digits). |
| `values.billingModels` | (one_time \| subscription \| trial \| upsell \| preorder)[] | no | [activity] Billing models used. |
| `values.goodsType` | physical \| digital \| both | no | [activity] Kind of goods. |
| `values.fulfilment` | object | no | [activity] Strict object: by (required: self \| supplier \| third_party_logistics), shipsFrom (country code), averageDeliveryDays (required, integer 0..120). |
| `values.fulfilment.by` | enum: self \| supplier \| third_party_logistics | no | [activity] Who ships the orders. Required inside the object. |
| `values.fulfilment.shipsFrom` | string | no | [activity] Country code the orders ship from. |
| `values.fulfilment.averageDeliveryDays` | integer 0..120 | no | [activity] Average delivery time in days. Required inside the object. |
| `values.refundPolicyDays` | integer 0..365 | no | [activity] Refund window in days. |
| `values.refundPolicyUrl` | URL | no | [activity] Refund policy page (normalised like websiteUrls). |
| `values.nonUsBuyersSharePct` | integer 0..100 | no | [activity] Share of buyers outside the US, percent. |
| `values.marketingChannels` | (paid_social \| search \| email \| affiliates \| telemarketing \| other)[] | no | [activity] Acquisition channels. |
| `values.monthlyVolumeMinor` | integer 0..1000000000000 | no | [processing] Expected monthly volume in minor units (cents). |
| `values.averageTicketMinor` | integer 0..1000000000000 | no | [processing] Average ticket in minor units. |
| `values.highestTicketMinor` | integer 0..1000000000000 | no | [processing] Highest ticket in minor units. |
| `values.recurringSharePct` | integer 0..100 | no | [processing] Share of recurring sales, percent. |
| `values.hasProcessedBefore` | boolean | no | [processing] Whether the business processed cards before. |
| `values.processors` | object[] <= 10 | no | [processing] Processing history, each strict: processorName (required, <= 120), from (required, YYYY-MM or YYYY-MM-DD), to (same format, optional). |
| `values.processors[].processorName` | string <= 120 | no | [processing] Name of a processor used before. Required in each item. |
| `values.processors[].from` | string YYYY-MM or YYYY-MM-DD | no | [processing] Start of that processing relationship. Required in each item. |
| `values.processors[].to` | string YYYY-MM or YYYY-MM-DD | no | [processing] End of it; omit while it is ongoing. |
| `values.chargebackRateBps` | integer 0..10000 | no | [processing] Chargeback rate in basis points (100 = 1 %). |
| `values.refundRateBps` | integer 0..10000 | no | [processing] Refund rate in basis points. |
| `values.everTerminated` | boolean | no | [processing] Ever terminated by a processor. |
| `values.terminationDetails` | string <= 1000 | no | [processing] Details of a termination. Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.inMonitoringProgram` | boolean | no | [processing] Currently in a card-network monitoring program. |
| `values.persons` | object[] <= 5 | no | [people] The whole list of people: when sent it REPLACES the stored list (a stored person left out is removed, see gotchas). Ownership over all persons must not exceed 10000 bps (sum_over_100); director and signer may each be held by one person only (needs_one). |
| `values.persons[].id` | uuid | no | [people] A stored person of this application; absent = a new person. Another application's person = 404 unknown_person. Unique in the list. |
| `values.persons[].position` | integer 0..99 | **yes** | [people] Display order, unique in the list. |
| `values.persons[].roles` | (director \| beneficial_owner \| control_person \| signer)[] 1..4 | **yes** | [people] Roles, no repeats. |
| `values.persons[].firstName` | string <= 80 | no | [people] Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.persons[].middleInitial` | one letter | no | [people] Middle initial. |
| `values.persons[].lastName` | string <= 80 | no | [people] Free text: no control characters; an identity or tax number inside is refused (identity_in_free_text). |
| `values.persons[].title` | string <= 100 | no | [people] Job title. |
| `values.persons[].ownershipBps` | integer 0..10000 | no | [people] Ownership in basis points (2500 = 25 %). |
| `values.persons[].email` | e-mail <= 254 | no | [people] E-mail. |
| `values.persons[].phone` | string <= 40 | no | [people] US phone (stored +1 and 10 digits). |
| `values.persons[].residenceCountry` | "US" | no | [people] Country of residence; only US residents are accepted in this release. |
| `values.persons[].idDocumentType` | passport \| drivers_license \| national_id | no | [people] Identity document type. |
| `values.persons[].idIssuer` | US state code or country code | no | [people] Issuer of the identity document. |
| `values.persons[].idExpiresOn` | YYYY-MM-DD | no | [people] Expiry of the identity document; a past day is refused (expired). |
| `values.allOwnersListed` | boolean | no | [people] Confirms that every owner of the business is listed. |

**Request body**

```json
{
  "expectedRevision": 7,
  "values": {
    "refundPolicyDays": 30,
    "refundPolicyUrl": "https://northwind.example/refunds"
  }
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "draft",
    "displayStatus": "draft",
    "revision": 8,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": null,
    "message": null
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": false,
      "missing": [
        "document:articles_of_incorporation"
      ],
      "editable": true,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": false,
      "missing": [
        "agreement"
      ],
      "editable": true,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 4,
    "total": 6,
    "next": "documents",
    "canSubmit": false,
    "blocking": [
      "documents",
      "agreement"
    ]
  },
  "can": {
    "edit": true,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  },
  "agreementInvalidated": false
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |
| `agreementInvalidated` | boolean | True when the save changed a field of the agreement (client block or pricing): the signature is cleared and the agreement must be signed again. |

**Errors**

- `400` unknown_step: Unknown step. ; invalid_request: Check the highlighted fields. ; identity_in_free_text: Do not enter identity or tax numbers in this field.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay.".
- `404` unknown_person: Unknown person. ; not_found: Not found.
- `409` application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; field_locked: Only the requested items can be changed. ; application_changed: This application changed. Reload before saving.
- `413` A request body over the limit of this route (262144 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 60 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Sealed values are never part of a step: use PUT /v1/kontrolpay/applications/:id/sensitive.
- A save merges: a key that is absent keeps its stored value, null clears it. In the people step a persons list that is sent replaces the whole list, and every person carries position and roles.
- A stored person left out of the persons list is removed with its sealed values, its documents and its open request items: in an application never submitted, and while the People step is requested as a whole. When only some of its fields are requested, a save that leaves a person out is refused whole with field_locked.
- While information is requested only the keys of steps[].editable can change: the requested items, and what an answer made required and is still missing (a field, a sealed value, a document). A value that is held stays locked. A write on anything else is refused whole with field_locked.
- invalid_request carries fieldErrors: field key to a reason code (required, format, too_short, too_long, not_allowed, po_box, in_future, in_past, under_18, expired, sum_over_100, duplicate, needs_one, mismatch). Never a received value.
- Identity or tax numbers typed in a free text field are refused with identity_in_free_text; the refusal carries fieldErrors with the key of each field that holds such a number, reason not_allowed. Never a received value. An address is named by its line: registeredAddress.line1, operatingAddress.city.
- When the signature of a submitted application is voided (a correction, a rejected signature), the application keeps the pricing it signed: the new agreement is built with it, not with platform defaults changed since.
- The revision increases by 1.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `POST /v1/kontrolpay/applications/:id/submit`

**Scope** `kontrolpay.write` - **Submit the application**

Send a complete draft to review, or send it back once every requested item is answered.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedRevision` | integer >= 1 | **yes** | The revision last read. A stale value answers 409 and changes nothing. |

**Request body**

```json
{
  "expectedRevision": 8
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "submitted",
    "displayStatus": "in_review",
    "revision": 9,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": "2026-11-19T09:30:00.000Z",
    "message": null
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 6,
    "total": 6,
    "next": null,
    "canSubmit": false,
    "blocking": []
  },
  "can": {
    "edit": false,
    "sign": false,
    "submit": false,
    "withdraw": true,
    "copy": true,
    "reason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |

**Errors**

- `400` invalid_request: Check the highlighted fields.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay."; owner_required: "Only the main account owner can sign, submit or withdraw an application.".
- `404` not_found: Not found.
- `409` applications_blocked: New KontrolPay applications are not available for this account. Contact support. ; application_incomplete: Complete every step before submitting. ; agreement_stale: The agreement changed. Reload it and sign again. ; requests_open: Answer every requested item before sending the application back. ; application_locked: This application is in review and cannot be edited. ; application_closed: This application is closed. Add a new application. ; application_changed: This application changed. Reload before saving.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 5 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- application_incomplete carries missing: [{ step, fields }].
- After the submission the application is read-only until information is requested.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

##### `POST /v1/kontrolpay/applications/:id/withdraw`

**Scope** `kontrolpay.write` - **Withdraw the application**

Withdraw an application that has no decision yet. A draft that was never submitted is discarded with its identity values and documents.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Application id, as returned by GET /v1/kontrolpay or by the creation. An id of another main account answers the same 404 as an unknown id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedRevision` | integer >= 1 | **yes** | The revision last read. A stale value answers 409 and changes nothing. |
| `confirm` | boolean | **yes** | Literally true. |

**Request body**

```json
{
  "expectedRevision": 9,
  "confirm": true
}
```

**Response**

```json
{
  "application": {
    "id": "6f1d2c9e-4b7a-4e0f-9a3d-2c5b8e7f1a01",
    "label": "Northwind Outfitters",
    "status": "withdrawn",
    "displayStatus": "withdrawn",
    "revision": 10,
    "updatedAt": "2026-11-18T10:12:00.000Z",
    "submittedAt": "2026-11-19T09:30:00.000Z",
    "message": null
  },
  "steps": [
    {
      "n": 1,
      "key": "business",
      "label": "Business",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 2,
      "key": "activity",
      "label": "Activity",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 3,
      "key": "processing",
      "label": "Processing",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 4,
      "key": "people",
      "label": "People",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 5,
      "key": "documents",
      "label": "Documents",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    },
    {
      "n": 6,
      "key": "agreement",
      "label": "Agreement",
      "done": true,
      "missing": [],
      "editable": false,
      "openRequests": 0
    }
  ],
  "progress": {
    "done": 6,
    "total": 6,
    "next": null,
    "canSubmit": false,
    "blocking": []
  },
  "can": {
    "edit": false,
    "sign": false,
    "submit": false,
    "withdraw": false,
    "copy": true,
    "reason": null
  }
}
```

| response field | type | description |
|---|---|---|
| `application` | object | id, label, status, displayStatus, revision, dates, the plain values of the four form steps, the masks of the sealed values ({ set, last4 }), documents, requiredDocuments, the signed agreement summary or null, and the information request items. last4 is null for an identity document number shorter than 8 characters: its mask shows no character. |
| `account` | object \| null | The account sheet once the application is approved: gateway, status, monthly limit, pricing in force and its history, signed pricing, number of ATRI pools. Never an internal reason or an author. |
| `steps` | object[] | The six steps (business, activity, processing, people, documents, agreement) with done, missing field keys, editable (true, false, or the list of field keys open while information is requested: the requested items, and what is required and still missing) and openRequests. |
| `progress` | object | done, total, next step, canSubmit and what still blocks the submission. |
| `can` | object | edit, sign, submit, withdraw, copy for THIS caller, with the reason shown on a disabled control. edit is also true while a request item can be answered, even when no step is editable (a request made of questions only). |
| `prefill` | object \| null | Only while draft, only for fields still empty: suggested values or pick lists with their source. Never a sealed value. |
| `catalog` | object | Option lists, the document and application limits, and the businesses that are not accepted. |
| `pricing` | object | The pricing offered to this application, or the pricing it signed when its signature was voided; else the platform defaults; the version in force once approved. |
| `timeline` | object[] | Merchant-visible events, newest first: the first element is the latest event. label is the words of the action ("Application submitted"), never the name of the business; message is the text written for the merchant. |

**Errors**

- `400` invalid_request: Check the highlighted fields.
- `401` {"error":"Missing bearer token"} (answered before the body is read when no Authorization: Bearer header is sent), or {"error":"Invalid API key"} / an invalid credential.
- `402` The Kontrol subscription of the account gives no access (answer of the subscription gate, unchanged).
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"kontrolpay.write"} when the key's scopes lack kontrolpay.write; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} from the gate for role user or refund; forbidden: "An account administrator is required to use KontrolPay."; owner_required: "Only the main account owner can sign, submit or withdraw an application.".
- `404` not_found: Not found.
- `409` application_closed: This application is closed. Add a new application. ; application_changed: This application changed. Reload before saving.
- `413` A request body over the limit of this route (16384 bytes) answers the code document_too_large with its sentence "The file is larger than 10 MB.": the JSON routes share the code of the upload.
- `429` Rate limited per client address: 5 requests per minute on this route.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Withdrawn is final. Open request items are canceled. A new application can be added afterwards.
- Every KontrolPay refusal answers { "error": <sentence>, "code": <code> }; tolerate an unknown or missing code and fall back to error. invalid_request, and identity_in_free_text when a field of the body holds the number, also carry fieldErrors: field key to a reason code.
- The response is private, no-store.
- The example is abridged to what this route changes. The response is the complete application view, shown in full on GET /v1/kontrolpay/applications/:id.

#### Balance and payouts

Balances and payouts.

- The Pending tab count is the sum of the three pending totals of `GET /v1/kontrolpay/balances`. Exports are built in the browser from `GET /v1/kontrolpay/payouts`.

##### `GET /v1/kontrolpay/balances`

**Scope** `kontrolpay.read` - **Read balances**

Pending, available, reserve and in-transit figures of one KontrolPay account or of all of them.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `account` | uuid | no | KontrolPay account id (UUID). Absent: every KontrolPay account of the main account. An id that is not one of them answers 404. |

**Response**

```json
{
  "currency": "USD",
  "totals": {
    "pendingMinor": 8165,
    "availableMinor": 0,
    "reserveHeldMinor": 1000,
    "inTransitMinor": 0,
    "totalMinor": 9165,
    "negativeMinor": 0
  },
  "accounts": [
    {
      "pendingMinor": 8165,
      "availableMinor": 0,
      "reserveHeldMinor": 1000,
      "inTransitMinor": 0,
      "totalMinor": 9165,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "displayStatus": "active",
      "payoutsPaused": false,
      "nextPayoutOn": "2026-12-02",
      "reserveRateBps": 1000,
      "reserveHoldDays": 90,
      "payoutDelayDays": 3,
      "payoutMinimumMinor": 0
    }
  ],
  "hasAccount": true,
  "live": true
}
```

| response field | type | description |
|---|---|---|
| `totals` | object | pendingMinor, availableMinor, reserveHeldMinor, inTransitMinor, totalMinor and negativeMinor over the selected accounts. |
| `totals.availableMinor` | integer | Sum of the POSITIVE account balances: payouts are per account and never net one account against another. The negative ones are summed in negativeMinor. |
| `accounts` | object[] | The same figures per account, with label, displayStatus, payoutsPaused, nextPayoutOn and the payout and reserve terms. |
| `hasAccount` | boolean | At least one approved account in the selection. |
| `live` | boolean | False until one account of the selection has been activated: every figure is then a true zero. |

**Errors**

- `400` {"error":"Check the highlighted fields.","code":"invalid_request","fieldErrors":{"<query key>":"<reason>"}}: an invalid value or an unknown query key (the query is strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"An account administrator is required to use KontrolPay.","code":"forbidden"}: the caller is not an administrator of the account.
- `404` {"error":"Not found.","code":"not_found"}: account is not a KontrolPay account of this main account (another account's id answers the same as an unknown one).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- totalMinor = pending + available + reserve held. What is still owed = totalMinor + inTransitMinor.
- Balances are derived at read time from the ledger and the clock; nothing is stored.
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Account ids are the accountId values of GET /v1/kontrolpay/balances (or of the overview GET /v1/kontrolpay).
- hasAccount is false until an application is approved; live is false, with every figure zero, until an account is activated.
- Answers carry cache-control: private, no-store and pragma: no-cache.

##### `GET /v1/kontrolpay/payouts`

**Scope** `kontrolpay.read` - **List payouts**

Payout batches of one account or of all of them, server paged and sorted, with totals over the whole filtered list.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `account` | uuid | no | KontrolPay account id (UUID). Absent: every KontrolPay account of the main account. An id that is not one of them answers 404. |
| `status` | scheduled \| paid \| failed \| canceled | no | Filter by status. |
| `page` | integer; default `1` | no | Page number, from 1. |
| `pageSize` | integer; default `50` | no | Rows per page, 1 to 10000. |
| `sort` | string; default `createdAt` | no | Sort key: createdAt, expectedOn, status, label, amountMinor, salesMinor, refundsMinor, chargebacksMinor, feesMinor, reserveMinor, reference. An unknown key answers 400 invalid_request. |
| `dir` | asc \| desc; default `desc` | no | Sort direction. |

**Response**

```json
{
  "payouts": [
    {
      "id": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "status": "scheduled",
      "amountMinor": 8165,
      "currency": "USD",
      "cutoffAt": "2026-12-04T00:00:00.000Z",
      "expectedOn": "2026-12-04",
      "itemCount": 4,
      "summary": {
        "salesMinor": 10000,
        "refundsMinor": 0,
        "chargebacksMinor": 0,
        "feesMinor": -835,
        "reserveHeldMinor": -1000,
        "reserveReleasedMinor": 0,
        "adjustmentsMinor": 0,
        "returnedPayoutsMinor": 0
      },
      "reference": null,
      "failureMessage": null,
      "paidAt": null,
      "createdAt": "2026-12-04T00:05:12.000Z"
    }
  ],
  "totals": {
    "salesMinor": 10000,
    "refundsMinor": 0,
    "chargebacksMinor": 0,
    "feesMinor": -835,
    "reserveHeldMinor": -1000,
    "reserveReleasedMinor": 0,
    "adjustmentsMinor": 0,
    "returnedPayoutsMinor": 0,
    "amountMinor": 8165
  },
  "page": {
    "page": 1,
    "pageSize": 50,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `payouts[].summary` | object | Eight fields that sum to amountMinor: salesMinor, refundsMinor, chargebacksMinor, feesMinor, reserveHeldMinor, reserveReleasedMinor, adjustmentsMinor, returnedPayoutsMinor. |
| `payouts[].reference` | string \| null | Bank reference recorded when the payout was confirmed paid. |
| `totals` | object | The same eight fields and amountMinor over the WHOLE filtered list, not the page. |
| `page` | object | page, pageSize, total. |

**Errors**

- `400` {"error":"Check the highlighted fields.","code":"invalid_request","fieldErrors":{"<query key>":"<reason>"}}: an invalid value or an unknown query key (the query is strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"An account administrator is required to use KontrolPay.","code":"forbidden"}: the caller is not an administrator of the account.
- `404` {"error":"Not found.","code":"not_found"}: account is not a KontrolPay account of this main account (another account's id answers the same as an unknown one).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- A payout is scheduled until it is confirmed paid, marked failed or canceled; a resolved payout is final.
- The money of a failed or canceled payout is payable again in a later payout.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Account ids are the accountId values of GET /v1/kontrolpay/balances (or of the overview GET /v1/kontrolpay).
- Answers carry cache-control: private, no-store and pragma: no-cache.

##### `GET /v1/kontrolpay/payouts/:payoutId`

**Scope** `kontrolpay.read` - **Read one payout**

One payout with the ledger entries it pays and its timeline.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `payoutId` | uuid | **yes** | Payout id. |

**Response**

```json
{
  "payout": {
    "id": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
    "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
    "label": "Northwind Outfitters",
    "status": "scheduled",
    "amountMinor": 8165,
    "currency": "USD",
    "cutoffAt": "2026-12-04T00:00:00.000Z",
    "expectedOn": "2026-12-04",
    "itemCount": 4,
    "summary": {
      "salesMinor": 10000,
      "refundsMinor": 0,
      "chargebacksMinor": 0,
      "feesMinor": -835,
      "reserveHeldMinor": -1000,
      "reserveReleasedMinor": 0,
      "adjustmentsMinor": 0,
      "returnedPayoutsMinor": 0
    },
    "reference": null,
    "failureMessage": null,
    "paidAt": null,
    "createdAt": "2026-12-04T00:05:12.000Z"
  },
  "entries": [
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e01",
      "sequence": 1,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "transaction_fee",
      "amountMinor": -45,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "in_payout",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e02",
      "sequence": 2,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "sale",
      "amountMinor": 10000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "in_payout",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e03",
      "sequence": 3,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "discount_fee",
      "amountMinor": -790,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "in_payout",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e04",
      "sequence": 4,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "reserve_hold",
      "amountMinor": -1000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "in_payout",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": "7b5d3f1a-9c8e-4a2b-b6d4-0e1f2a3b4c14",
      "memo": null
    }
  ],
  "timeline": [
    {
      "id": "1102",
      "at": "2026-12-04T00:05:12.000Z",
      "action": "payout_scheduled",
      "label": "Payout scheduled",
      "message": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `payout` | object | The payout, as in the list. |
| `entries` | object[] | The ledger entries paid by this payout. |
| `timeline` | object[] | Merchant-visible events of the payout, newest first. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"An account administrator is required to use KontrolPay.","code":"forbidden"}: the caller is not an administrator of the account.
- `404` {"error":"Not found.","code":"not_found"}: payoutId is not a UUID, unknown, or a payout of another main account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- entries are the ledger entries this payout paid, oldest first, at most 10000 (not paged); timeline holds at most 200 events, newest first.
- A payout of another main account answers the same 404 as an unknown id.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Answers carry cache-control: private, no-store and pragma: no-cache.

#### Reserve

The rolling reserve: schedule, activity and terms.

##### `GET /v1/kontrolpay/reserve`

**Scope** `kontrolpay.read` - **Read the reserve**

Reserve held and released, the release schedule by day, the reserve terms per account and the reserve activity.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `account` | uuid | no | KontrolPay account id (UUID). Absent: every KontrolPay account of the main account. An id that is not one of them answers 404. |
| `page` | integer; default `1` | no | Page number, from 1. |
| `pageSize` | integer; default `50` | no | Rows per page, 1 to 10000. |
| `sort` | string; default `occurredAt` | no | Sort key: occurredAt, kind, amountMinor, availableAt, label. An unknown key answers 400 invalid_request. |
| `dir` | asc \| desc; default `desc` | no | Sort direction. |

**Response**

```json
{
  "currency": "USD",
  "heldMinor": 1000,
  "releasedMinor": 0,
  "releasingIn30DaysMinor": 0,
  "nextReleaseOn": "2027-03-01",
  "terms": [
    {
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "reserveRateBps": 1000,
      "reserveHoldDays": 90,
      "since": "2026-11-20T15:00:00.000Z"
    }
  ],
  "schedule": [
    {
      "releaseOn": "2027-03-01",
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "amountMinor": 1000,
      "holds": 1
    }
  ],
  "activity": [
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e05",
      "sequence": 5,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "reserve",
      "kind": "reserve_hold",
      "amountMinor": 1000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2027-03-01T00:00:00.000Z",
      "state": "held",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    }
  ],
  "activityTotalMinor": 1000,
  "page": {
    "page": 1,
    "pageSize": 50,
    "total": 1
  },
  "hasAccount": true,
  "live": true
}
```

| response field | type | description |
|---|---|---|
| `schedule` | object[] | One row per release day (UTC) and account; never paged. |
| `activity` | object[] | Entries of the reserve bucket, paged and sorted by the query. |
| `activityTotalMinor` | integer | Total of the whole activity list. |
| `terms` | object[] | Reserve rate and hold days in force per account, and since when. |

**Errors**

- `400` {"error":"Check the highlighted fields.","code":"invalid_request","fieldErrors":{"<query key>":"<reason>"}}: an invalid value or an unknown query key (the query is strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"An account administrator is required to use KontrolPay.","code":"forbidden"}: the caller is not an administrator of the account.
- `404` {"error":"Not found.","code":"not_found"}: account is not a KontrolPay account of this main account (another account's id answers the same as an unknown one).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- A reserve entry counts as held until its availableAt, then as released; no job moves it.
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Account ids are the accountId values of GET /v1/kontrolpay/balances (or of the overview GET /v1/kontrolpay).
- hasAccount is false until an application is approved; live is false, with every figure zero, until an account is activated.
- Answers carry cache-control: private, no-store and pragma: no-cache.

#### Transactions

The ledger of KontrolPay money movements.

##### `GET /v1/kontrolpay/transactions`

**Scope** `kontrolpay.read` - **List ledger transactions**

The KontrolPay ledger of one account or of all of them: the money entries, not the charge list.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `account` | uuid | no | KontrolPay account id (UUID). Absent: every KontrolPay account of the main account. An id that is not one of them answers 404. |
| `kind` | enum | no | sale, discount_fee, transaction_fee, reserve_hold, refund, refund_fee, chargeback, chargeback_fee, reversal, payout, payout_reversal or adjustment. |
| `state` | enum | no | pending, available, held, in_payout, paid or returned. |
| `from` | YYYY-MM-DD \| ISO 8601 | no | Start of the range, included: a calendar day (UTC), or an instant with its offset. At most 40 characters; another format answers 400 invalid_request. |
| `to` | YYYY-MM-DD \| ISO 8601 | no | End of the range, included: a calendar day (UTC, the whole day), or an instant with its offset. At most 40 characters; another format answers 400 invalid_request. |
| `page` | integer; default `1` | no | Page number, from 1. |
| `pageSize` | integer; default `50` | no | Rows per page, 1 to 10000. |
| `sort` | string; default `occurredAt` | no | Sort key: occurredAt, kind, label, amountMinor, availableAt, state. An unknown key answers 400 invalid_request. |
| `dir` | asc \| desc; default `desc` | no | Sort direction. |

**Response**

```json
{
  "currency": "USD",
  "entries": [
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e01",
      "sequence": 1,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "transaction_fee",
      "amountMinor": -45,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "pending",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e02",
      "sequence": 2,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "sale",
      "amountMinor": 10000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "pending",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e03",
      "sequence": 3,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "discount_fee",
      "amountMinor": -790,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "pending",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e04",
      "sequence": 4,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "balance",
      "kind": "reserve_hold",
      "amountMinor": -1000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2026-12-04T00:00:00.000Z",
      "state": "pending",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    },
    {
      "id": "5c0f1e2d-3b4a-4c5d-9e6f-7a8b9c0d1e05",
      "sequence": 5,
      "accountId": "b3a9d7e2-1c4f-4a6b-8d2e-9f0a1b2c3d04",
      "label": "Northwind Outfitters",
      "bucket": "reserve",
      "kind": "reserve_hold",
      "amountMinor": 1000,
      "currency": "USD",
      "occurredAt": "2026-12-01T10:00:00.000Z",
      "availableAt": "2027-03-01T00:00:00.000Z",
      "state": "held",
      "transactionId": "a9b0c1d2-e3f4-4a5b-86d7-e8f9a0b1c222",
      "refundId": null,
      "payoutId": null,
      "memo": null
    }
  ],
  "totals": {
    "grossMinor": 10000,
    "feesMinor": -835,
    "reserveMinor": -1000,
    "netMinor": 9165,
    "amountMinor": 9165
  },
  "page": {
    "page": 1,
    "pageSize": 50,
    "total": 5
  },
  "hasAccount": true,
  "live": true
}
```

| response field | type | description |
|---|---|---|
| `entries` | object[] | Ledger entries: one row per component (sale, each fee, each side of the reserve, refund, chargeback, payout), signed; positive credits the merchant. |
| `entries[].state` | enum | Derived at read time: pending, available, held (reserve not yet released), in_payout, paid, returned. |
| `entries[].transactionId` | uuid \| null | The charge the entry comes from. |
| `totals` | object | Over the whole filtered list: grossMinor (sales), feesMinor (the four fee kinds), reserveMinor (balance side of the reserve), netMinor = amountMinor (every entry except payout and payout_reversal). |

**Errors**

- `400` {"error":"Check the highlighted fields.","code":"invalid_request","fieldErrors":{"<query key>":"<reason>"}}: an invalid value or an unknown query key (the query is strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"An account administrator is required to use KontrolPay.","code":"forbidden"}: the caller is not an administrator of the account.
- `404` {"error":"Not found.","code":"not_found"}: account is not a KontrolPay account of this main account (another account's id answers the same as an unknown one).
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Fees are those in force on the day of each sale: a later pricing change never rewrites an entry.
- The per-attempt fee is one entry per authorization attempt that reached the processor, approved or declined.
- The ledger is append-only: a correction is a reversal entry, never an edit.
- Example values are invented. The pricing in force is the one this API returns and the agreement states.
- Amounts are integers in USD minor units, rates are basis points, instants are ISO 8601 and calendar days are YYYY-MM-DD (UTC).
- Account ids are the accountId values of GET /v1/kontrolpay/balances (or of the overview GET /v1/kontrolpay).
- hasAccount is false until an application is approved; live is false, with every figure zero, until an account is activated.
- Answers carry cache-control: private, no-store and pragma: no-cache.

### Subscriptions

The Subscriptions menu: schedules, monitoring, subscription products, Rebill Flows, subscribers, the charge log, retry profiles, settings and metrics.

#### Schedules

The billing schedules: list, calendar, one schedule and its charges, manual jobs (Force bill, Sample), overrides, routes, bulk operations and analysis.

- List and Calendar figures computed in the browser from `GET /v1/subscription/schedules` and `GET /v1/subscription/schedules/calendar`: Declined = failed - blocked; Pending = scheduled + processing; the Total row sums the rows; the status label combines status and date (a past day still scheduled reads overdue).
- Schedule details (`GET /v1/subscription/schedules/:id` and its `analysis`): reached = success + failed - blocked (the attempts that reached a MID); approval rate = success / reached; processed % = (success + failed + rejected + cancelled + missed) / total; pending = scheduled + processing. Approved volume = the analysis `gross_cents`, else the day's `approved_cents`; only when both are missing it is estimated as success x the first configured amount (and shown as an estimate). Net = the analysis `volume.net_cents`.
- Exports of the list, calendar month, details ledger, analytics, subs and transactions pages are built in the browser.

##### `GET /v1/subscription/jobs/:jobId`

**Scope** `subscriptions.read` - **Get a schedule billing job (Force bill / Sample)**

Reads a schedule billing job (the Force bill or Sample run of a schedule day); subscription bulk-edit jobs are read with GET /v1/subscription/bulk-jobs/:jobId. Returns one manual job by id (account-scoped) - the polling endpoint for a running Force bill / Sample: counters, heartbeat, phase flags, error and logs.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Job id; another account's job is a 404. |

**Response**

```json
{
  "job": {
    "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
    "owner_email": "ops@example.com",
    "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "kind": "force",
    "sample_size": null,
    "test_mode": false,
    "status": "running",
    "control": null,
    "worker": "srv-1:4821",
    "heartbeat_at": "2026-09-19T14:02:40.000Z",
    "cursor_entry_id": "9b7e6d5c-1111-4f22-a333-444455556666",
    "total": 202,
    "sent": 120,
    "success": 101,
    "failed": 17,
    "rejected": 2,
    "skipped": 0,
    "generation_done": true,
    "dispatch_done": false,
    "post_dispatch_done": false,
    "error": null,
    "logs": [
      "> force bill - 202 charges",
      "... batch 12/21: 10 sent, 8 approved"
    ],
    "started_at": "2026-09-19T14:00:02.000Z",
    "finished_at": null,
    "created_at": "2026-09-19T14:00:01.000Z",
    "updated_at": "2026-09-19T14:02:40.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job row. |
| `job.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `job.schedule_id` | uuid | The schedule being dispatched. |
| `job.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `job.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `job.test_mode` | boolean | Simulated results, nothing charged. |
| `job.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `job.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `job.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `job.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `job.blocked` | integer | Of `failed`, the entries claimed by the job that were refused before any MID or left no transaction row (cumulative across pause / resume). Declined = failed - blocked. |
| `job.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `job.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `job.logs` | string[] | Human log lines (capped at 2000). |
| `job.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- A 'running' job whose heartbeat_at is older than ~30 s is considered crashed and will be re-claimed by a worker (it resumes from cursor_entry_id).
- status 'paused' with error 'Subscription dispatch is OFF for this account' = paused by the kill switch; resume it after re-enabling.

##### `POST /v1/subscription/jobs/:jobId/cancel`

**Scope** `subscriptions.write` - **Cancel a schedule billing job**

Cancels a schedule billing job (Force bill / Sample); a subscription bulk-edit job is cancelled with POST /v1/subscription/bulk-jobs/:jobId/cancel. Cancels an active job: a queued / paused job is closed at once (status 'cancelled', error 'Cancelled by user', finished_at set); a running job gets control = 'cancel' and stops between batches. The schedule status is recomputed from its entries and a 'job_cancelled' history row is written. Returns the job row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Job id; must belong to the caller's account and be ACTIVE (queued / running / paused). |

**Response**

```json
{
  "job": {
    "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
    "owner_email": "ops@example.com",
    "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "kind": "force",
    "sample_size": null,
    "test_mode": false,
    "status": "running",
    "control": "cancel",
    "worker": "srv-1:4821",
    "heartbeat_at": "2026-09-19T14:02:40.000Z",
    "cursor_entry_id": "9b7e6d5c-1111-4f22-a333-444455556666",
    "total": 202,
    "sent": 120,
    "success": 101,
    "failed": 17,
    "rejected": 2,
    "skipped": 0,
    "generation_done": true,
    "dispatch_done": false,
    "post_dispatch_done": false,
    "error": null,
    "logs": [
      "> force bill - 202 charges",
      "... batch 12/21: 10 sent, 8 approved"
    ],
    "started_at": "2026-09-19T14:00:02.000Z",
    "finished_at": null,
    "created_at": "2026-09-19T14:00:01.000Z",
    "updated_at": "2026-09-19T14:02:40.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job row re-read after the control was written. |
| `job.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `job.schedule_id` | uuid | The schedule being dispatched. |
| `job.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `job.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `job.test_mode` | boolean | Simulated results, nothing charged. |
| `job.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `job.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `job.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `job.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `job.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `job.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `job.logs` | string[] | Human log lines (capped at 2000). |
| `job.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found or not active"} - unknown id, another account's job, or the job is not in a state this control applies to (cancelled / done / error; for resume: anything but paused).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- For a running job the response shows status 'running' with control 'cancel' - poll until 'cancelled'.
- Pending charges are untouched: the schedule returns to pending / partial and the auto dispatcher resumes them if the day is today/yesterday. Use POST .../cancel-processing to cancel the job AND the charges.
- The charges the job already sent keep their results.

##### `POST /v1/subscription/jobs/:jobId/pause`

**Scope** `subscriptions.write` - **Pause a schedule billing job**

Pauses a schedule billing job (Force bill / Sample) between batches; subscription bulk-edit jobs cannot be paused. Requests a pause of an active job (queued / running / paused): control = 'pause' is written and the runner honours it between batches, after which the job status becomes 'paused'. Nothing is charged after the current batch. Returns the job row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Job id; must belong to the caller's account and be ACTIVE (queued / running / paused). |

**Response**

```json
{
  "job": {
    "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
    "owner_email": "ops@example.com",
    "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "kind": "force",
    "sample_size": null,
    "test_mode": false,
    "status": "running",
    "control": "pause",
    "worker": "srv-1:4821",
    "heartbeat_at": "2026-09-19T14:02:40.000Z",
    "cursor_entry_id": "9b7e6d5c-1111-4f22-a333-444455556666",
    "total": 202,
    "sent": 120,
    "success": 101,
    "failed": 17,
    "rejected": 2,
    "skipped": 0,
    "generation_done": true,
    "dispatch_done": false,
    "post_dispatch_done": false,
    "error": null,
    "logs": [
      "> force bill - 202 charges",
      "... batch 12/21: 10 sent, 8 approved"
    ],
    "started_at": "2026-09-19T14:00:02.000Z",
    "finished_at": null,
    "created_at": "2026-09-19T14:00:01.000Z",
    "updated_at": "2026-09-19T14:02:40.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job row re-read after the control was written. |
| `job.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `job.schedule_id` | uuid | The schedule being dispatched. |
| `job.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `job.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `job.test_mode` | boolean | Simulated results, nothing charged. |
| `job.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `job.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `job.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `job.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `job.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `job.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `job.logs` | string[] | Human log lines (capped at 2000). |
| `job.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found or not active"} - unknown id, another account's job, or the job is not in a state this control applies to (cancelled / done / error; for resume: anything but paused).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Asynchronous: the response still shows status 'running' with control 'pause'; poll GET /v1/subscription/jobs/:jobId until status = 'paused'.
- Charges already claimed by the current batch complete normally.
- The schedule stays 'dispatching' while the job is paused; the auto dispatcher keeps skipping it.

##### `POST /v1/subscription/jobs/:jobId/resume`

**Scope** `subscriptions.write` - **Resume a schedule billing job**

Resumes a paused schedule billing job (Force bill / Sample) from its cursor. Re-queues a 'paused' job (status -> 'queued', control cleared) so a worker picks it up again and continues from its cursor; the force budget is unchanged (charges created before the original start). Writes a 'job_resumed' history row on the schedule. Returns the job row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Job id; must belong to the caller's account and be ACTIVE (queued / running / paused). |

**Response**

```json
{
  "job": {
    "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
    "owner_email": "ops@example.com",
    "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "kind": "force",
    "sample_size": null,
    "test_mode": false,
    "status": "queued",
    "control": null,
    "worker": "srv-1:4821",
    "heartbeat_at": "2026-09-19T14:02:40.000Z",
    "cursor_entry_id": "9b7e6d5c-1111-4f22-a333-444455556666",
    "total": 202,
    "sent": 120,
    "success": 101,
    "failed": 17,
    "rejected": 2,
    "skipped": 0,
    "generation_done": true,
    "dispatch_done": false,
    "post_dispatch_done": false,
    "error": null,
    "logs": [
      "> force bill - 202 charges",
      "... batch 12/21: 10 sent, 8 approved"
    ],
    "started_at": "2026-09-19T14:00:02.000Z",
    "finished_at": null,
    "created_at": "2026-09-19T14:00:01.000Z",
    "updated_at": "2026-09-19T14:02:40.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job row re-read after the control was written. |
| `job.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `job.schedule_id` | uuid | The schedule being dispatched. |
| `job.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `job.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `job.test_mode` | boolean | Simulated results, nothing charged. |
| `job.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `job.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `job.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `job.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `job.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `job.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `job.logs` | string[] | Human log lines (capped at 2000). |
| `job.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found or not active"} - unknown id, another account's job, or the job is not in a state this control applies to (cancelled / done / error; for resume: anything but paused).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only status 'paused' resumes - a running or queued job answers 404 'Not found or not active'.
- A job paused by the kill switch pauses itself again immediately if the switch is still off.

##### `GET /v1/subscription/schedules`

**Scope** `subscriptions.read` - **List schedules**

Pages through the account's schedules (one per product x New York day, plus legacy manual / auto days) with per-status entry counts, hover stats, the active-job flag, a source label and dispatch-split numbering. v3.9.15 - filtered by THE unified catalog on the schedule grain; under filters each row also carries `filtered`, its figures over the charges that match (FD23). Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: success\|declines\|retry\|subscription | no | Filter on kind (success \| declines \| retry \| subscription) - the endpoint's own param, beside the catalog. Legacy retry children are excluded anyway. |
| `sort` | enum: run_day\|name\|status\|total_clients\|created_at\|kind\|schedule_type; default `run_day` | no | Sort column. Absent -> run_day. Anything else is a 400 {"error":"Invalid sort","allowed":[...]} listing the accepted columns - it no longer falls back silently to run_day (a direction passed as the key, `sort=desc`, used to return the default order). Ties break on created_at desc; nulls last. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |
| `limit` | integer; default `10` | no | Page size, 1..10000. |
| `offset` | integer; default `0` | no | Rows to skip, >= 0. |
| `from` | string (YYYY-MM-DD) | no | Filter catalog (Date): first New York run / charge day of the range, inclusive. An ISO instant is a 400 on this endpoint. |
| `to` | string (YYYY-MM-DD) | no | Filter catalog (Date): last New York run / charge day of the range, inclusive. An ISO instant is a 400 on this endpoint. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "owner_email": "ops@example.com",
      "name": "VIP Monthly - 2026-09-19",
      "kind": "subscription",
      "schedule_type": "subscription",
      "run_day": "2026-09-19",
      "source": {
        "kind": "approved",
        "subscription": "VIP Monthly"
      },
      "amounts_cents": [
        6999
      ],
      "atri_split": null,
      "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
      "parent_schedule_id": null,
      "child_step": 0,
      "total_clients": 412,
      "auto_dispatch_enabled": false,
      "forced_at": null,
      "test_mode": false,
      "scrub_bypass": false,
      "generated_at": "2026-09-01T14:02:11.000Z",
      "status": "partial",
      "error_message": null,
      "safeguard_tripped_at": null,
      "safeguard_reason": null,
      "overrides": [],
      "created_at": "2026-09-01T14:02:11.000Z",
      "updated_at": "2026-09-19T13:40:02.000Z",
      "stats": {
        "sources": {
          "sale": 380,
          "sweep": 12,
          "ops@example.com": 20
        },
        "decided": 210,
        "success": 176,
        "approved_cents": 1231824,
        "planned_cents": 1413798,
        "first_pending_at": "2026-09-19T13:41:00.000Z",
        "errors": 0,
        "missed": 0,
        "force_ended": false
      },
      "entry_counts": {
        "scheduled": 202,
        "rebill_success": 176,
        "rebill_failed": 34
      },
      "has_active_job": false,
      "total": 57,
      "sourceLabel": "Subscription - VIP Monthly",
      "split": null
    }
  ],
  "total": 57,
  "timezone": "America/New_York",
  "today": "2026-09-19"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The page of schedules (snake_case DB rows plus computed fields). |
| `rows[].id` | uuid | Schedule id. |
| `rows[].name` | string | Display name; subscription days are named '<product> - <run_day>'. UNIQUE per account (owner_email, name). |
| `rows[].kind` | enum: success\|declines\|retry\|subscription | 'subscription' = a day of a subscription product; success / declines / retry = legacy hand-made or auto-imported schedules. |
| `rows[].schedule_type` | enum: auto\|manual\|subscription | How the schedule came to exist. |
| `rows[].run_day` | string (YYYY-MM-DD) | The New York calendar day the charges belong to. |
| `rows[].source` | object | {kind:'approved'\|'declined', from, to (UTC purchase days), storefront?, brand?, country?, excludeScheduled?, subscription?: <product name>} - the order-selection criteria (for a subscription day: {kind: attach_on, subscription: name}). |
| `rows[].amounts_cents` | integer[] | Price points of the schedule in cents (a subscription day carries the product amount at creation; the real charge amount is on each entry). |
| `rows[].atri_split` | array\|null | [{id, name, pct}] ATRI routing split for the charges; null = the account default ATRI. |
| `rows[].subscription_id` | uuid\|null | The subscription product this day belongs to (null on legacy schedules). |
| `rows[].retry_profile_id` | uuid\|null | Retry profile copied from the product (legacy: used by the post-dispatch retry child). |
| `rows[].parent_schedule_id` | uuid\|null | Set on legacy retry children spawned from a parent schedule. |
| `rows[].total_clients` | integer | Distinct customers (orders) ever planned into the day, whatever became of their charge. |
| `rows[].status` | enum: pending\|dispatching\|partial\|done\|cancelled\|error\|paused | Derived from the entries (pending = nothing processed, partial = some, done = all) except 'dispatching' (an active manual job) and the sticky 'cancelled' / 'error'. v3.9.12: + the sticky 'paused' (the operator's Pause - nothing of the day is sent until Resume). |
| `rows[].test_mode` | boolean | Simulated results only - never charges. |
| `rows[].scrub_bypass` | boolean | The BIN scrub is skipped for this schedule (retry of scrubbed cards on purpose). |
| `rows[].safeguard_tripped_at` | string (ISO-8601)\|null | Set when Safe-Guard cancelled the day (approval rate under the account threshold); safeguard_reason explains. |
| `rows[].overrides` | array | Bulk overrides recorded on the day: [{field:'amount_cents'\|'run_day'\|'status', from, to, at, by}]. Non-empty = shown as '(edited)'. |
| `rows[].stats` | object | {sources: {<attached_by\|source\|legacy>: n}, decided, success, blocked, processed_first, processed_last, approved_cents, planned_cents, first_pending_at, errors, missed, force_ended} - approval so far and volume (approved / still planned), then what decides the day's chip: errors = UNRESOLVED technical errors (a charge that ended in an ERROR, not a decline, and was not followed by a later attempt of the same charge - a later attempt resolves it, whatever its result); missed = charges never dispatched within a day of their slot; force_ended = a Force bill ran through the day, which makes the day FINISHED before its New York day is over (the chip reads Partial only on a finished day that is incomplete). blocked: as entry_counts.blocked. v3.9.9 - processed_first / processed_last: the first / last decision instant of the decided entries (null before any) - the day range of the schedule's /transactions links ([day(first) - 1, day(last)] in the display timezone: a charge's transaction is created before its decision). |
| `rows[].created_at` | string (ISO-8601) | Creation instant (updated_at likewise). |
| `rows[].entry_counts` | object | {<entry status>: n, blocked: n} - e.g. {scheduled: 202, rebill_success: 176, rebill_failed: 34, blocked: 12}. Statuses with zero rows are absent; blocked is always present and is NOT a status: the rebill_failed entries refused before any MID (rebill_entries.blocked, v3.9 section 1) or - v3.9.9 - left without a transaction row, inside rebill_failed. v3.9.9 (D3) - blocked = refused before any MID OR left without a transaction row ("No card on file", an order of another account, an unresolved duplicate): inside rebill_failed, outside Charges; Charges = success + rebill_failed - blocked = the /transactions schedule=<id> rows. |
| `rows[].has_active_job` | boolean | A manual job (queued / running / paused) exists for the day. |
| `rows[].sourceLabel` | string | 'Subscription - <name>' or 'Approved\|Declined orders <from> -> <to>'. |
| `rows[].split` | object\|null | {index, of} when >= 2 sibling schedules (same source, no parent) are in the page - the dispatch-split numbering; else null. |
| `rows[].total` | integer | Per-row copy of the window count (count(*) over()). Prefer the top-level total. |
| `total` | integer | Matching schedules across all pages. 0 when the page is empty (offset past the end) because it is derived from the returned rows. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `today` | string (YYYY-MM-DD) | Today's New York day. |
| `rows[].route_override` | object\|null | The day's persistent route override (migration 176): { kind: "atri", atriId, name } \| { kind: "mid", midId, name } (+ via: "merge" when a Resume / Change date merge kept the charge's former day's ATRI) \| null. Re-resolved at each charge; unusable -> the ATRI split (recorded on the charge). |
| `rows[].filtered` | object \| absent | Present ONLY when a catalog key narrows (hasFilters: every key but from / to / tz / refundBasis and refundTest=exclude): the figures of the row restricted to its charges matching the filters - total, scheduled, processing, pending (= scheduled + processing), success, failed, declined (= rebill_failed with a transaction row), blocked (refused before any MID or without a row), rejected, cancelled, missed, decided, approved_cents, planned_cents, processed_first / processed_last (the decided span - the /transactions link range). The row's own entry_counts / stats stay the WHOLE day's (they drive its status, progress bar and hover). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key (a legacy name included) or closed-vocabulary value, an instant `from` / `to` (days only), a reversed range, limit out of 1..10 000.
- `400` {"error":"Invalid sort","allowed":[...]} - `sort` is not one of the allowed columns (the body lists them). Absent `sort` is fine (default order).
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- BREAKING: search -> q, view -> scheduleStatus, type -> scheduleType, subscriptionId -> subscription; status and hideDone retire (status is now the CHARGE status, through the day's charges - the raw schedule status is the scheduleStatus view). A legacy name is a 400.
- `from` / `to` are RUN days (YYYY-MM-DD, New York): an ISO instant is a 400 - never a guessed day (FD24).
- Under filters: `total` counts the matching DAYS; the day's Success / Declined / Blocked / Pending / amounts matching the filters are in rows[].filtered - entry_counts / stats stay the whole day's (the day status, progress and hover).
- A charge-own key (status, gateway, 3DS...) reads the entry's own transaction: a still-scheduled charge has none, so status=approved lists only days with decided charges (FD11).
- An unknown `sort` is a 400 that lists the allowed columns. Default page size is 10 - pass limit explicitly (max 10000).
- Legacy retry children (schedule_type != 'subscription' and kind = 'retry') never appear here, even with kind=retry; their charges are still in the charge log.
- run_day and today are New York calendar days; created_at / stats.first_pending_at are UTC instants.
- The status of a 'dispatching' schedule whose job died is NOT self-healed here - only GET /v1/subscription/schedules/:id does that.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/subscription/schedules/:id`

**Scope** `subscriptions.read` - **Get a schedule**

Returns one schedule with everything the detail page needs: per-status entry counts, hover stats, legacy children and dispatch-split siblings, the active manual job, the next due slot, the count of overdue charges and its parent. Side effect: a schedule stuck in 'dispatching' with no active job is self-healed (status recomputed from its entries and persisted). v3.9.12: `stop` - the open stop of a paused / cancelled / errored day (who stopped it, when, and what a cancel stopped: what Resume restores); `activeJob.route`. v3.9.15 (FD23) - with catalog keys (the Subs tab's filters) the payload adds `filtered`: the day's figures over its charges matching them; `counts` and schedule.stats stay the whole day's. The Analytics read (GET .../:id/analysis) stays day-level.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id, must belong to the caller's account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): Start of the page range (inclusive): the grain's own date. A bare day is read in tz. |
| `to` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): End of the page range (inclusive). A bare day is read in tz. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "schedule": {
    "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "owner_email": "ops@example.com",
    "name": "VIP Monthly \u2014 2026-09-19",
    "kind": "subscription",
    "schedule_type": "subscription",
    "run_day": "2026-09-19",
    "source": {
      "kind": "approved",
      "subscription": "VIP Monthly"
    },
    "amounts_cents": [
      6999
    ],
    "atri_split": null,
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "parent_schedule_id": null,
    "child_step": 0,
    "total_clients": 412,
    "auto_dispatch_enabled": false,
    "forced_at": null,
    "test_mode": false,
    "scrub_bypass": false,
    "generated_at": "2026-09-01T14:02:11.000Z",
    "status": "partial",
    "error_message": null,
    "safeguard_tripped_at": null,
    "safeguard_reason": null,
    "overrides": [],
    "created_at": "2026-09-01T14:02:11.000Z",
    "updated_at": "2026-09-19T13:40:02.000Z",
    "stats": {
      "sources": {
        "sale": 380,
        "sweep": 12,
        "ops@example.com": 20
      },
      "decided": 210,
      "success": 176,
      "approved_cents": 1231824,
      "planned_cents": 1413798,
      "first_pending_at": "2026-09-19T13:41:00.000Z",
      "errors": 0,
      "missed": 0,
      "force_ended": false
    },
    "sourceLabel": "Subscription \u00b7 VIP Monthly"
  },
  "counts": {
    "total": 412,
    "scheduled": 202,
    "processing": 0,
    "success": 176,
    "failed": 34,
    "rejected": 0,
    "cancelled": 0,
    "missed": 0
  },
  "children": [],
  "siblings": [],
  "activeJob": null,
  "nextDue": "2026-09-19T13:41:00.000Z",
  "overdue": 0,
  "parent": null,
  "timezone": "America/New_York",
  "today": "2026-09-19",
  "stop": null,
  "transactionTotal": 210
}
```

| response field | type | description |
|---|---|---|
| `schedule` | object | The schedule row (snake_case) + overrides (always an array), stats and sourceLabel. |
| `schedule.id` | uuid | Schedule id. |
| `schedule.name` | string | Display name; subscription days are named '<product> - <run_day>'. UNIQUE per account (owner_email, name). |
| `schedule.kind` | enum: success\|declines\|retry\|subscription | 'subscription' = a day of a subscription product; success / declines / retry = legacy hand-made or auto-imported schedules. |
| `schedule.schedule_type` | enum: auto\|manual\|subscription | How the schedule came to exist. |
| `schedule.run_day` | string (YYYY-MM-DD) | The New York calendar day the charges belong to. |
| `schedule.source` | object | {kind:'approved'\|'declined', from, to (UTC purchase days), storefront?, brand?, country?, excludeScheduled?, subscription?: <product name>} - the order-selection criteria (for a subscription day: {kind: attach_on, subscription: name}). |
| `schedule.amounts_cents` | integer[] | Price points of the schedule in cents (a subscription day carries the product amount at creation; the real charge amount is on each entry). |
| `schedule.atri_split` | array\|null | [{id, name, pct}] ATRI routing split for the charges; null = the account default ATRI. |
| `schedule.subscription_id` | uuid\|null | The subscription product this day belongs to (null on legacy schedules). |
| `schedule.retry_profile_id` | uuid\|null | Retry profile copied from the product (legacy: used by the post-dispatch retry child). |
| `schedule.parent_schedule_id` | uuid\|null | Set on legacy retry children spawned from a parent schedule. |
| `schedule.total_clients` | integer | Distinct customers (orders) ever planned into the day, whatever became of their charge. |
| `schedule.status` | enum: pending\|dispatching\|partial\|done\|cancelled\|error\|paused | Derived from the entries (pending = nothing processed, partial = some, done = all) except 'dispatching' (an active manual job) and the sticky 'cancelled' / 'error'. v3.9.12: + the sticky 'paused' (the operator's Pause - nothing of the day is sent until Resume). |
| `schedule.test_mode` | boolean | Simulated results only - never charges. |
| `schedule.scrub_bypass` | boolean | The BIN scrub is skipped for this schedule (retry of scrubbed cards on purpose). |
| `schedule.safeguard_tripped_at` | string (ISO-8601)\|null | Set when Safe-Guard cancelled the day (approval rate under the account threshold); safeguard_reason explains. |
| `schedule.overrides` | array | Bulk overrides recorded on the day: [{field:'amount_cents'\|'run_day'\|'status', from, to, at, by}]. Non-empty = shown as '(edited)'. |
| `schedule.stats` | object | {sources: {<attached_by\|source\|legacy>: n}, decided, success, blocked, processed_first, processed_last, approved_cents, planned_cents, first_pending_at, errors, missed, force_ended} - approval so far and volume (approved / still planned), then what decides the day's chip: errors = UNRESOLVED technical errors (a charge that ended in an ERROR, not a decline, and was not followed by a later attempt of the same charge - a later attempt resolves it, whatever its result); missed = charges never dispatched within a day of their slot; force_ended = a Force bill ran through the day, which makes the day FINISHED before its New York day is over (the chip reads Partial only on a finished day that is incomplete). blocked: see counts. v3.9.9 - processed_first / processed_last: the first / last decision instant of the decided entries (null before any) - the day range of the schedule's /transactions links ([day(first) - 1, day(last)] in the display timezone: a charge's transaction is created before its decision). |
| `schedule.created_at` | string (ISO-8601) | Creation instant (updated_at likewise). |
| `counts` | object | {total, scheduled, processing, success, failed, rejected, cancelled, missed, blocked, errors} entry counts. v3.9.9 (D3) - blocked = refused before any MID OR left without a transaction row ("No card on file", an order of another account, an unresolved duplicate): inside rebill_failed, outside Charges; Charges = success + rebill_failed - blocked = the /transactions schedule=<id> rows. errors = the unresolved technical errors. |
| `children` | array | Legacy retry children spawned from this schedule (schedule rows), ordered by run_day, kind. |
| `siblings` | array | Dispatch-split siblings (same source, no parent) INCLUDING this schedule - only when there are >= 2, else []. |
| `activeJob` | object\|null | The queued / running / paused manual job, or null. |
| `activeJob.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `activeJob.schedule_id` | uuid | The schedule being dispatched. |
| `activeJob.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `activeJob.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `activeJob.test_mode` | boolean | Simulated results, nothing charged. |
| `activeJob.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `activeJob.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `activeJob.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `activeJob.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `activeJob.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `activeJob.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `activeJob.logs` | string[] | Human log lines (capped at 2000). |
| `activeJob.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |
| `nextDue` | string (ISO-8601)\|null | Earliest scheduled slot still in the future. |
| `overdue` | integer | 'scheduled' entries whose slot already passed. |
| `parent` | object\|null | {id, name, kind} of the parent schedule (legacy children only). |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `today` | string (YYYY-MM-DD) | Today's New York day. |
| `stop` | object\|null | The open stop of a paused / cancelled / errored day (rebill_schedule_stops, the latest not resumed): {kind: 'pause' \| 'cancel', stoppedAt, stoppedBy (the operator's e-mail, or 'safeguard'), reason (Safe-Guard's, else null), charges (the charges a cancel cancelled - what Resume restores), subs (the subs it paused)}. null otherwise, and for a day stopped before v3.9.12 (no record). |
| `schedule.route_override` | object\|null | The day's persistent route override (migration 176): { kind: "atri", atriId, name } \| { kind: "mid", midId, name } (+ via: "merge" when a Resume / Change date merge kept the charge's former day's ATRI) \| null; null = its ATRI split. Written by POST .../:id/route and POST .../schedules/bulk action route; never touched by product edits or Resume. |
| `filtered` | object \| absent | Present ONLY when a catalog key narrows (hasFilters: every key but from / to / tz / refundBasis and refundTest=exclude): the figures of the row restricted to its charges matching the filters - total, scheduled, processing, pending (= scheduled + processing), success, failed, declined (= rebill_failed with a transaction row), blocked (refused before any MID or without a row), rejected, cancelled, missed, decided, approved_cents, planned_cents, processed_first / processed_last (the decided span - the /transactions link range). The row's own entry_counts / stats stay the WHOLE day's (they drive its status, progress bar and hover). |
| `transactionTotal` | integer | Distinct existing transactions linked to this schedule and visible to its account, across all entry states. Independent of Subs filters and analytics drill-down filters. Used by the Transactions tab badge; entries without a transaction are excluded. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key or closed-vocabulary value, hour without tz, a reversed pair.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Schedule status controls are busy. Retry shortly.","requestId":"<id>"} (Retry-After: 1) when the self-repair of a stuck dispatching status is saturated; retry shortly.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- This GET can WRITE: a 'dispatching' schedule with no active job gets its status recomputed and a 'status_changed' history row (actor 'dispatch').
- An id belonging to another account is a 404, not a 403.
- Entries are not included - page them with GET /v1/subscription/schedules/:id/entries.
- Strict query: an unknown key is a 400 (checked before the 404).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `DELETE /v1/subscription/schedules/:id`

**Scope** `subscriptions.write` - **Delete a schedule**

Hard-deletes a schedule and, by cascade, its entries, jobs and history. Refused for 'done' / 'dispatching' schedules, when a manual job is active, or while any entry is 'processing'.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"Cannot delete active schedules"} - status done or dispatching, or a manual job is active.
- `409` {"error":"Entries are processing"} - at least one charge is in flight.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Cascade delete: rebill_entries, rebill_dispatch_jobs and rebill_schedule_history of the day are erased - the 'deleted' history row written just before is gone too. Prefer POST /cancel to keep the trail.
- DANGER on a subscription day: rebill_subs.current_entry_id has no foreign key, so the subs pinned to the deleted charges keep a dangling pin and are never re-planned by the engine (it only heals pins whose entry row still exists). Cancel the day instead (it pauses the subs), or pause/resume the affected subs afterwards.
- 'done' schedules cannot be deleted at all - history is kept.
- Pending charges are deleted, not cancelled: nothing is written to the subs.

##### `GET /v1/subscription/schedules/:id/analysis`

**Scope** `subscriptions.read` - **Analysis of one schedule**

Computes the analysis tables of one schedule (decline reasons, approval per amount / brand / MID / hour, volume with real net and fees, last 50 results, every segment breakdown) plus the pending charges per New York hour, the next due slot and the overdue count. Read-only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `refresh` | UUID | no | Optional fresh-read reference. Different references do not share pending analysis work. Use after mutations and explicit Refresh; omit on background polls. |

**Response**

```json
{
  "declineReasons": [
    {
      "reason": "Insufficient funds",
      "status": "rebill_failed",
      "count": 21
    }
  ],
  "byAmount": [
    {
      "amount_cents": 6999,
      "total": 210,
      "success": 176,
      "revenue_cents": 1231824
    }
  ],
  "byBrand": [
    {
      "brand": "VISA",
      "total": 130,
      "success": 112,
      "revenue_cents": 783888
    }
  ],
  "byMid": [
    {
      "mid_name": "MID US 02",
      "total": 210,
      "success": 176,
      "revenue_cents": 1231824
    }
  ],
  "byHour": [
    {
      "hour": 9,
      "total": 30,
      "success": 26,
      "revenue_cents": 181974
    }
  ],
  "volume": {
    "gross_cents": 1231824,
    "net_cents": 1190310,
    "fees_cents": 41514,
    "charged_count": 176,
    "planned_cents": 1413798
  },
  "recent": [
    {
      "order_id": "ORD-118842",
      "status": "rebill_success",
      "decline_reason": null,
      "processed_at": "2026-09-19T15:07:05.210Z"
    }
  ],
  "segments": [
    {
      "dim": "hour",
      "label": "Approval per hour",
      "rows": [
        {
          "key": "09:00",
          "total": 30,
          "success": 26,
          "revenue_cents": 181974
        }
      ]
    }
  ],
  "pendingByHour": [
    {
      "hour": 14,
      "count": 40
    },
    {
      "hour": 15,
      "count": 62
    }
  ],
  "nextDue": "2026-09-19T13:41:00.000Z",
  "overdue": 0,
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `declineReasons` | array | [{reason, status, count, blocked}] over failed + rejected charges; blocked = of count, the attempts refused before any MID (rebill_entries.blocked, v3.9 section 1) or - v3.9.9 - left without a transaction row - never a gateway decline. |
| `byAmount` | array | [{amount_cents, total, success, revenue_cents}] - total = decided (success + failed) charges. |
| `byBrand` | array | [{brand, total, success, revenue_cents}] card brand from bin_info or the card number prefix. |
| `byMid` | array | [{mid_name, total, success, revenue_cents}] per gateway. |
| `byHour` | array | [{hour (0-23, New York), total, success, revenue_cents}] by processing hour. |
| `volume` | object | {gross_cents, net_cents, fees_cents, charged_count, planned_cents} - approved volume with real net / fees from the transactions, plus what is still pending. |
| `recent` | array | [{order_id, status, decline_reason, processed_at}] last 50 processed charges. |
| `segments` | array | [{dim, label, rows: [{key, total, success, blocked, revenue_cents, ref?}]}] - every approval breakdown of the Subscription report over the decided charges (rebill_success / rebill_failed), v3.9.12 in the dashboard's tab order: Subscription - subscription ('Approval per subscription product': the day's product, rebill_schedules.subscription_id; '(legacy)' on a legacy day; `ref` = the product id, rows grouped on it), cycle, price_point, initial_value, hour - Routing - mid, category (the charge's MID's PRIMARY category - its first by name, the list's primaryCategory; '(none)' without one), mcc ('(none)'), acquirer, processor, company ('(unset)' = a gateway without that reference) - Cards - issuer ('Approval per bank (issuer)'), card_brand, card_type, card_level, bin - Traffic - traffic, store, product, geo, device, os - Declines - decline_category. v3.9.9 (F11): EVERY row (no 60-row cap), each with `blocked`, so a dimension's rows add up to the schedule's decided / success / blocked totals. |
| `pendingByHour` | array | [{hour (0-23 New York), count}] of 'scheduled' charges by slot hour. |
| `nextDue` | string (ISO-8601)\|null | Earliest future scheduled slot. |
| `overdue` | integer | 'scheduled' charges whose slot already passed. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |

**Errors**

- `400` {"error":"Invalid refresh reference"}: refresh is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: no schedule with this id in the account (another account's id answers the same).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Schedule analysis is temporarily unavailable. Please refresh shortly."}: analysis capacity, a statement or the whole-operation budget was exhausted (also for a malformed id); nothing partial is cached.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Segment 'hour' and byHour use the PROCESSING time in New York; pendingByHour uses the planned slot.
- v3.9.6 live fees: volume.net_cents / fees_cents are computed at read time from the MIDs' CURRENT settings (discount + reserve + the attempts' flat fees + the 3DS rate; net = amount - those), never from the deprecated transactions.net_cents / total_fee_cents snapshots - a fee edit re-prices past schedules.
- Heavy endpoint (~ 25 queries) - do not poll it every second.
- Every breakdown carries `blocked` (refused before any MID or no transaction row) inside its `total`: Charges = total - blocked (the /transactions schedule=<ids> rows), approval = success / (total - blocked).
- The Routing tables category / mcc / acquirer / processor / company read the charge's OWN transaction and its gateway (txFilters GATEWAY_REF_JOIN: the final MID, else the wallet provider): '(no gateway)' holds the blocked entries (no transaction row) and the charges that ended on no MID and no wallet provider. mid reads the entry's MID (' - ' for none); card and traffic families read the original sale; subscription reads the day's product. The dashboard shows them in contained tabs Subscription - Routing - Cards - Traffic - Declines (the decline reasons sit in Declines) - `?view=` on the schedule page's Analytics tab, local state in the bulk Analytics modal.
- Schedule analysis uses two dedicated DB connections per process, at most four queued distinct reads and 128 observers per identical read. Keys include authenticated actor/role/ATRI grants, effective owner, schedule and optional refresh reference.
- Enabled read has a25s admission-to-result deadline,5s per SQL statement and at most2s extra connection teardown; existing authentication middleware runs before this budget. Each observer disconnects independently; last observer cancels shared SQL.
- Analysis reads one repeatable-read snapshot. A failed dimension returns 503 instead of a partial successful response; all documented analysis fields and SQL semantics are retained.

##### `POST /v1/subscription/schedules/:id/cancel`

**Scope** `subscriptions.write` - **Cancel a schedule**

Cancels a day - v3.9.12, THE recorded cancel (rebill/scheduleStop.ts cancelSchedule): the status flips to the sticky 'cancelled' FIRST (nothing claims the day from that instant), then in one statement every 'scheduled' charge becomes 'cancelled' (decline_reason 'schedule cancelled') and the live subs pinned to them are PAUSED (not lost; one sub.paused event each, the operator as actor) - and the ids of both are RECORDED (rebill_schedule_stops kind 'cancel', migration 171), so POST .../resume restores exactly them. A charge in flight ('processing') is left to complete and record its result: since v3.9.12 it is no longer reverted to 'scheduled' (the revert lost the result of a charge the gateway was processing - its write-back is guarded on 'processing' - and a later re-plan charged the cycle again). A status override is recorded and a 'cancelled' history row written. Refused while a manual job is active.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "cancelled": 202,
  "reverted": 0,
  "paused": 202
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `cancelled` | integer | 'scheduled' charges turned 'cancelled' - the ones the stop records. |
| `reverted` | integer | Always 0 since v3.9.12 (a charge in flight is no longer reverted: it completes); kept for the shape. |
| `paused` | integer | Subs paused because their current charge was in this day (0 on legacy schedules) - the ones the stop records. A sub whose charge is in flight is not paused: its result decides it. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"Cancel the running job first"} - a manual job is queued / running / paused on the day; v3.9.12: {"error":"Schedule is already cancelled"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- No status precondition but one: a pending, partial, paused, done or error day is cancelled just the same (its status flips to 'cancelled'); v3.9.12: an already cancelled day is 409 {"error":"Schedule is already cancelled"}.
- A charge in flight completes: its result is written on the entry and applied to its sub; `reverted` is always 0.
- Subs are paused, not ended: POST .../resume (or .../uncancel) brings back EXACTLY the recorded charges and subs, placed over the rest of today; a paused sub plans nothing until resumed.
- Only subs whose CURRENT charge is in this day are paused; a sub whose old charge here was already re-planned elsewhere is untouched.
- 'cancelled' is sticky: the engine never derives another status from the entries until POST .../resume. GET /v1/subscription/schedules/:id carries the open stop in `stop` (kind 'cancel', the charges and subs it recorded).

##### `POST /v1/subscription/schedules/:id/cancel-processing`

**Scope** `subscriptions.write` - **Cancel the schedule and its running job**

The dashboard's "cancel processing": cancels the active manual job if any (a queued / paused one closes immediately, a running one stops between batches), then runs THE recorded cancel of POST .../cancel (v3.9.12, rebill/scheduleStop.ts cancelSchedule, without its job check): the status flips to the sticky 'cancelled' first, every 'scheduled' charge is cancelled and the subs pinned to them paused, both recorded for POST .../resume; a charge in flight completes. Records a status override and a 'processing_cancelled' history row ({cancelled, paused}).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "cancelled": 82,
  "reverted": 0
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `cancelled` | integer | 'scheduled' charges turned 'cancelled' - the ones the stop records. |
| `reverted` | integer | Always 0 since v3.9.12 (a charge in flight is no longer reverted: it completes); kept for the shape. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"Schedule is already cancelled"} - v3.9.12.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Same as POST .../cancel but WITHOUT the 409 on an active job - the job is cancelled too. The response has no `paused` count although subs are paused just the same (the history row carries it).
- A running job may still finish its current batch (a handful of charges) after this call returns: those charges complete and record their result.
- No status precondition but one: an already cancelled day is 409. POST .../resume restores exactly what this cancel recorded.

##### `GET /v1/subscription/schedules/:id/entries`

**Scope** `subscriptions.read` - **List the charges of a schedule**

Pages through the charges (rebill_entries) of one schedule joined to the original sale (customer, card, BIN info, storefront, device) and to the order's next live charge elsewhere. Also returns the schedule's decline-reason histogram (over failed / rejected / cancelled / missed charges, independent of the filters).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `15` | no | Page size 1..10000. |
| `offset` | integer; default `0` | no | >= 0. |
| `dir` | enum: asc\|desc; default `asc` | no | Order by scheduled_at. |
| `from` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): Start of the page range (inclusive): the grain's own date. A bare day is read in tz. |
| `to` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): End of the page range (inclusive). A bare day is read in tz. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "id": "9b7e6d5c-1111-4f22-a333-444455556666",
      "owner_email": "ops@example.com",
      "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "order_id": "ORD-118842",
      "run_day": "2026-09-19",
      "scheduled_at": "2026-09-19T15:07:00.000Z",
      "amount_cents": 6999,
      "currency": "USD",
      "rebill_number": 2,
      "rebill_type": "recurring",
      "preferred_mid": null,
      "is_test": false,
      "status": "rebill_success",
      "decline_reason": null,
      "decline_normalized": null,
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "mid_id": "5f0e...",
      "mid_name": "MID US 02",
      "order_id_supplier": "ORD-118842-R2",
      "attempt_count": 0,
      "claimed_at": "2026-09-19T15:07:03.000Z",
      "claim_job": "auto:2026-09-19T15:07:00.000Z",
      "processed_at": "2026-09-19T15:07:05.210Z",
      "created_at": "2026-09-01T14:02:12.000Z",
      "sub_id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "email": "jane@example.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "masked_card": "411111******1111",
      "bin": "411111",
      "storefront_url": "https://shop.example.com/checkout",
      "country": "US",
      "ip_address": "203.0.113.7",
      "purchase_at": "2026-08-19T15:07:44.000Z",
      "card_brand": "VISA",
      "card_type": "CREDIT",
      "card_country": "US",
      "card_issuer": "JPMORGAN CHASE",
      "card_level": "CLASSIC",
      "card_prepaid": false,
      "card_currency": "USD",
      "ccexp": "0928",
      "fbclid": null,
      "ttclid": null,
      "useragent": "Mozilla/5.0 (iPhone...)",
      "sale_mid": "MID US 01",
      "sale_amount_cents": 4999,
      "next_schedule_id": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
      "next_schedule_name": "VIP Monthly - 2026-10-19",
      "next_run_day": "2026-10-19",
      "total": 0
    }
  ],
  "total": 412,
  "reasons": [
    {
      "reason": "Insufficient funds",
      "count": 21
    },
    {
      "reason": "Do not honor",
      "count": 9
    }
  ],
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The page of charges, each joined to its original sale. |
| `rows[].id` | uuid | Charge (rebill_entries) id. |
| `rows[].schedule_id` | uuid | The day the charge belongs to. |
| `rows[].order_id` | string | The original sale order id (card on file). |
| `rows[].sub_id` | uuid\|null | The customer sub this charge belongs to; null on legacy charges. |
| `rows[].run_day` | string (YYYY-MM-DD) | New York day of the slot. |
| `rows[].scheduled_at` | string (ISO-8601) | UTC instant the charge fires (minute-truncated). |
| `rows[].amount_cents` | integer | Amount to charge, in cents; currency alongside (USD). |
| `rows[].rebill_number` | integer | Cycle number of the charge (retries of a cycle keep it). |
| `rows[].rebill_type` | enum: first\|recurring\|insufficient_funds | 'insufficient_funds' = a dunning retry at the retry profile's amount. |
| `rows[].status` | enum: scheduled\|processing\|rebill_success\|rebill_failed\|cancelled\|rejected\|missed | rejected = refused by the BIN scrub before any attempt; missed = never dispatched within a day of its slot. |
| `rows[].decline_reason` | string\|null | Gateway decline text, or the internal reason for cancelled / missed / rejected. |
| `rows[].decline_normalized` | string\|null | Normalised decline (e.g. 'insufficient_funds', 'expired_card') when known. |
| `rows[].transaction_id` | uuid\|null | The transactions row created by the charge (success or decline). |
| `rows[].mid_name` | string\|null | Gateway (MID) that processed the charge; preferred_mid = the same-MID preference, if any. |
| `rows[].attempt_count` | integer | Transport-level attempts (reverts to scheduled). |
| `rows[].claimed_at` | string\|null | Claim instant while processing; claim_job = 'auto:<iso>' or 'job:<job id>'. |
| `rows[].processed_at` | string (ISO-8601)\|null | When the result was written. |
| `rows[].is_test` | boolean | Simulated charge (test schedule). |
| `rows[].email` | string\|null | Customer of the original sale (first_name / last_name alongside). |
| `rows[].masked_card` | string\|null | Masked card of the sale; bin = its first 6 digits; ccexp = expiry as stored (MMYY). |
| `rows[].card_brand` | string\|null | From bin_info: card_brand, card_type, card_country, card_issuer, card_level, card_prepaid, card_currency. |
| `rows[].storefront_url` | string\|null | Original sale storefront; country, ip_address, useragent, fbclid, ttclid likewise from the sale. |
| `rows[].purchase_at` | string (ISO-8601)\|null | Original sale instant; sale_mid / sale_amount_cents = the MID and amount of that sale. |
| `rows[].next_schedule_id` | uuid\|null | The order's next live charge elsewhere (next_schedule_name, next_run_day) - null when none. |
| `rows[].total` | integer | Per-row copy of the total in some queries (0 when the count was computed separately) - use the top-level total. |
| `total` | integer | Charges matching the filters (all pages). |
| `reasons` | array | [{reason, count}] decline reasons over failed / rejected / cancelled / missed charges of the WHOLE schedule (filters ignored), most frequent first. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `rows[].route_override` | object\|null | This charge's own route override (beats the day's): { kind: "atri", atriId, name } \| { kind: "mid", midId, name } (+ via: "merge" when a Resume / Change date merge kept the charge's former day's ATRI) \| null. Written while scheduled; follows the same cycle's retry / re-plan, never the next cycle. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key (a legacy name included) or closed-vocabulary value, limit out of range, dir not asc|desc.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Default page size is 15. rows[].total is 0 - read the top-level `total`.
- `reasons` lists the day's decline reasons (entryReason values, exact text).
- BREAKING: status -> entryStatus (+ declined / blocked, the report classification), reason -> entryReason (CSV now), search -> q; `status` is now the CHARGE status of the entry's transaction. A legacy name is a 400.
- Every filter reads the entry alone (EXISTS probes on its transaction / its sale): the count and the ids never pay the per-entry detail joins.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/subscription/schedules/:id/entries/:entryId`

**Scope** `subscriptions.read` - **Get one charge of a schedule**

Returns one charge (rebill_entries row) of the schedule with the same sale / card / next-charge joins as the list. The entry must belong to the given schedule.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |
| `entryId` | uuid | **yes** | Charge id; must belong to schedule :id. |

**Response**

```json
{
  "id": "9b7e6d5c-1111-4f22-a333-444455556666",
  "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
  "order_id": "ORD-118842",
  "sub_id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
  "run_day": "2026-09-19",
  "scheduled_at": "2026-09-19T15:07:00.000Z",
  "amount_cents": 6999,
  "currency": "USD",
  "rebill_number": 2,
  "rebill_type": "recurring",
  "status": "rebill_failed",
  "decline_reason": "Insufficient funds",
  "decline_normalized": "insufficient_funds",
  "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
  "mid_name": "MID US 02",
  "processed_at": "2026-09-19T15:07:05.210Z",
  "email": "jane@example.com",
  "first_name": "Jane",
  "last_name": "Doe",
  "masked_card": "411111******1111",
  "bin": "411111",
  "card_brand": "VISA",
  "card_type": "CREDIT",
  "purchase_at": "2026-08-19T15:07:44.000Z",
  "sale_amount_cents": 4999,
  "next_schedule_id": null,
  "next_schedule_name": null,
  "next_run_day": null,
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `(root)` | object | The EntryDetailRow itself - NOT wrapped in {entry}. |
| `id` | uuid | Charge (rebill_entries) id. |
| `schedule_id` | uuid | The day the charge belongs to. |
| `order_id` | string | The original sale order id (card on file). |
| `sub_id` | uuid\|null | The customer sub this charge belongs to; null on legacy charges. |
| `run_day` | string (YYYY-MM-DD) | New York day of the slot. |
| `scheduled_at` | string (ISO-8601) | UTC instant the charge fires (minute-truncated). |
| `amount_cents` | integer | Amount to charge, in cents; currency alongside (USD). |
| `rebill_number` | integer | Cycle number of the charge (retries of a cycle keep it). |
| `rebill_type` | enum: first\|recurring\|insufficient_funds | 'insufficient_funds' = a dunning retry at the retry profile's amount. |
| `status` | enum: scheduled\|processing\|rebill_success\|rebill_failed\|cancelled\|rejected\|missed | rejected = refused by the BIN scrub before any attempt; missed = never dispatched within a day of its slot. |
| `decline_reason` | string\|null | Gateway decline text, or the internal reason for cancelled / missed / rejected. |
| `decline_normalized` | string\|null | Normalised decline (e.g. 'insufficient_funds', 'expired_card') when known. |
| `transaction_id` | uuid\|null | The transactions row created by the charge (success or decline). |
| `mid_name` | string\|null | Gateway (MID) that processed the charge; preferred_mid = the same-MID preference, if any. |
| `attempt_count` | integer | Transport-level attempts (reverts to scheduled). |
| `claimed_at` | string\|null | Claim instant while processing; claim_job = 'auto:<iso>' or 'job:<job id>'. |
| `processed_at` | string (ISO-8601)\|null | When the result was written. |
| `is_test` | boolean | Simulated charge (test schedule). |
| `email` | string\|null | Customer of the original sale (first_name / last_name alongside). |
| `masked_card` | string\|null | Masked card of the sale; bin = its first 6 digits; ccexp = expiry as stored (MMYY). |
| `card_brand` | string\|null | From bin_info: card_brand, card_type, card_country, card_issuer, card_level, card_prepaid, card_currency. |
| `storefront_url` | string\|null | Original sale storefront; country, ip_address, useragent, fbclid, ttclid likewise from the sale. |
| `purchase_at` | string (ISO-8601)\|null | Original sale instant; sale_mid / sale_amount_cents = the MID and amount of that sale. |
| `next_schedule_id` | uuid\|null | The order's next live charge elsewhere (next_schedule_name, next_run_day) - null when none. |
| `total` | integer | Per-row copy of the total in some queries (0 when the count was computed separately) - use the top-level total. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - schedule not in the account, or the entry is not in that schedule.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The response is the bare entry object (no wrapper key), unlike most other routes.
- An entry that moved to another schedule (run-day override / merge) is a 404 under its old schedule id - its schedule_id changed.

##### `POST /v1/subscription/schedules/:id/entries/bulk`

**Scope** `subscriptions.write` - **Bulk action on the charges of a schedule**

Applies one action to many charges of a schedule (the customers table). For a charge that belongs to a sub, pause / resume / cancel / change_subscription / amount act on THE SUB (pause drops the pending charge, amount re-plans it...); 'cancel_charge' cancels the scheduled charge AND ends its sub (end_cause 'user'); 'amount' on a legacy charge (no sub) edits the charge itself. Runs 8 charges at a time, refreshes the day's client count, and returns done / skipped counts. Optional async:true creates a durable bulk-edit job and returns202 {jobId,job}. The legacy synchronous contract remains supported.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `action` | enum: pause\|resume\|cancel\|change_subscription\|amount\|cancel_charge\|credential_mode\|route | no | pause / resume / cancel / change_subscription / amount act on the SUB behind each charge (amount on a legacy charge edits the charge); cancel_charge drops the scheduled charge and ends its sub; credential_mode (migration 171) sets the scheduled charges' CIT / MIT override; route sets the scheduled charges' ROUTE override. Required in synchronous mode or when async actions[] is absent. |
| `subscriptionId` | uuid | no | change_subscription: the target product (must be one of the account's, else 422). |
| `keepAmount` | boolean; default `false` | no | change_subscription: keep the sub's current amount instead of taking the new product's. |
| `amountCents` | integer | no | Single positive price in cents for action=amount. Mutually exclusive with amountCentsList; omit when supplying the price list. |
| `reason` | string | no | cancel / cancel_charge: cancel_reason stored on the sub (<= 200 chars). Defaults to 'cancelled in bulk by <actor>' / 'charge cancelled from schedule by <actor>'. |
| `credentialMode` | enum: mit\|cit\|auto | no | migration 171 - with action credential_mode (required then): mit / cit force the charge's mode; auto clears the override (the account settings decide). Only a charge still scheduled is changed (a sent charge's mode is history). |
| `route` | { atriId: uuid } \| { midId: uuid } \| null | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `route.atriId` | uuid | no | Inside route: Route through this ATRI of the account (active, with an activated card-capable MID). Not with midId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `route.midId` | uuid | no | Inside route: Pin this activated MID of the account (it must belong to an active ATRI; NMI and Convesio MIDs with a supported card adapter). Not with atriId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `async` | boolean; default `false` | no | true submits a durable background job and returns HTTP 202 {jobId,job}; false uses the legacy synchronous operation. |
| `requestId` | uuid | no | Async idempotency key; same key and identical payload returns the original job; changed payload returns 409. |
| `actions` | object[] (1..8) | no | Async mode: ordered compound actions. Each action has action plus its fields. Use this instead of a single top-level action. |
| `amountCentsList` | integer[] (1..10000) | no | Prices in minor currency units, each 1..2147483647, for action=amount. Send exactly one of amountCents or amountCentsList. Supported synchronously and asynchronously. |
| `entryIds` | uuid[] | **yes** | Selected scheduled charge IDs: 1..10000 synchronous, 1..100000 async. Async mode deduplicates IDs and rejects stale or foreign selections. |
| `actions[].action` | enum: amount\|pause\|resume\|cancel\|change_subscription\|cancel_charge\|credential_mode\|route | no | Async mode: one step of the compound edit. |
| `actions[].amountCents` | integer | no | amount: one price in cents, 1..2147483647 (or amountCentsList, not both). |
| `actions[].amountCentsList` | integer[] | no | amount: 1..10000 prices spread over the selection. |
| `actions[].subscriptionId` | uuid | no | change_subscription: target product of the account. |
| `actions[].keepAmount` | boolean; default `false` | no | change_subscription: keep each sub's amount. |
| `actions[].reason` | string | no | cancel / cancel_charge: reason, up to 200 characters. |
| `actions[].credentialMode` | enum: mit\|cit\|auto | no | credential_mode: required for it. |
| `actions[].route` | { atriId: uuid } \| { midId: uuid } \| null | no | route: required for it; null clears the charges' route override. |
| `actions[].route.atriId` | uuid | no | Inside actions[].route: Route through this ATRI of the account (active, with an activated card-capable MID). Not with midId. The object holds exactly one of atriId or midId; send actions[].route: null to clear the override. |
| `actions[].route.midId` | uuid | no | Inside actions[].route: Pin this activated MID of the account (it must belong to an active ATRI; NMI and Convesio MIDs with a supported card adapter). Not with atriId. The object holds exactly one of atriId or midId; send actions[].route: null to clear the override. |

**Request body**

```json
{
  "async": true,
  "requestId": "00000000-0000-4000-8000-000000000001",
  "entryIds": [
    "00000000-0000-4000-8000-000000000001"
  ],
  "actions": [
    {
      "action": "amount",
      "amountCentsList": [
        1999,
        2999,
        3999,
        4999
      ]
    }
  ]
}
```

**Response**

```json
{
  "done": 2,
  "skipped": 0
}
```

| response field | type | description |
|---|---|---|
| `done` | integer | Charges (or their subs) the action applied to. |
| `skipped` | integer | Charges where nothing applied: wrong sub state (pause on a paused sub, resume on an active one...), legacy charge with a sub-only action, non-scheduled charge for cancel_charge / amount, or an error (swallowed). |
| `distribution` | {amountCents:number,planned:number,done:number}[] | Synchronous price-list response only: planned and successfully changed eligible targets per input price. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - unknown action, entryIds empty / > 10000 / non-uuid, amountCents <= 0.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `400` Async mode: {"error":"Invalid bulk edit","details":...}, {"error":"Select at least one item"} or {"error":"Invalid action","details":...}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` Async mode: {"error":"No account"}.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` Async mode: {"error":"Another bulk edit is already running for this account","jobId":"<id>"}.
- `413` Body larger than 8 MiB.
- `422` {"error":"Unknown subscription"} - change_subscription without a valid product of the account.
- `422` {"error":"Amount required"} - action amount without amountCents.
- `422` {"error":"Route required: { atriId } | { midId } | null"} - action route without `route`.
- `422` {"error":"Credential mode required"} - action credential_mode without credentialMode.
- `422` Unknown/inactive ATRI, ATRI without an activated card-capable MID, disabled MID, unsupported card adapter, MID outside active ATRIs, or both atriId and midId supplied.
- `422` {"error":"Use a price list only with the amount action, without amountCents"}; async mode also {"error":"Route required"} style action errors and the route resolution errors.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 'cancel_charge' on a sub's charge ENDS THE SUB (status cancelled, end_cause 'user') - it is not just this charge.
- 'amount' / 'change_subscription' / 'resume' on a sub re-plan its pending charge: the old entry is cancelled and a NEW entry id is created (possibly in this same schedule) - refresh the list.
- 'pause' / 'resume' / 'cancel' / 'change_subscription' on a legacy charge (no sub_id) are skipped; only 'amount' and 'cancel_charge' work on legacy charges.
- done + skipped may be lower than entryIds.length: ids of other schedules are silently dropped.
- Errors per charge are swallowed into `skipped` - the call never fails half-way, but you do not learn why an item was skipped.
- 'resume' re-activates a paused / failed sub at its stored next_charge_at if still in the future, else NOW (charged within minutes / today's window).
- A charge-level route override beats the day's; it is COPIED onto the same cycle's retry and any re-plan of that cycle (an amount / subscription edit, a pause + resume), and onto a legacy NSF child - never onto the next cycle. The dashboard's Edit applies `route` FIRST so the re-plans that follow inherit it.
- action route answers { done, skipped } where skipped = the ids that are not scheduled charges of this day.
- Send requestId(UUID) for idempotent submission and actions[] (up to 8) for a compound edit. Selection supports up to 100000 IDs. All actions for one subscription commit atomically; separate items allow partial success. Only one active bulk edit per account is accepted; conflicts409 include jobId. Read progress and failures at /v1/subscription/bulk-jobs. Jobs persist30days after completion. No release flag controls admission.
- Send numeric cents as a JSON array, not a comma-delimited string: [1999,2999,3999,4999]. The dashboard converts its comma-separated input before calling the API.
- Price lists distribute eligible distinct subscriptions evenly (1000 eligible subscriptions / four prices = 250 per price); leftover items differ by at most one. Multiple entries belonging to one subscription do not apply multiple prices. Async assignments are snapshotted once and survive retries.
- Async jobs process each subscription atomically across all requested actions. Partial success is reported through job counters and /v1/subscription/bulk-jobs/:jobId/errors. Cancellation retains completed edits.
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.
- Synchronous mode returns {done, skipped} (plus distribution[] {amountCents, planned, done} with amountCentsList); async mode returns 202 {jobId, job}, followed with GET /v1/subscription/bulk-jobs/:jobId.

##### `GET /v1/subscription/schedules/:id/entries/ids`

**Scope** `subscriptions.read` - **Ids of a day's charge list**

The ids of GET .../:id/entries for the SAME query (every catalog key - entryStatus, entryReason, q, ...; limit / offset ignored), in the list's order, at most 10 000 - what "Select all N matching" of /subscriptions/schedules/:id selects. Shares the list's WHERE builder (db/rebill.ts entryListWhere), so it can never select outside the filters on screen. 0.2 s for a 3 407-charge day (the list through its detail joins: 1.8-2.8 s).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (owner-scoped). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `15` | no | Validated like the list (1..10000, else 400) and then ignored: the ids of the whole filtered list come back, at most 10 000. |
| `offset` | integer; default `0` | no | Validated like the list (>= 0, else 400) and then ignored. |
| `dir` | enum: asc\|desc; default `asc` | no | Order by scheduled_at. |
| `from` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): Start of the page range (inclusive): the grain's own date. A bare day is read in tz. |
| `to` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): End of the page range (inclusive). A bare day is read in tz. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "ids": [
    "3f7c...",
    "9a12..."
  ],
  "capped": false
}
```

| response field | type | description |
|---|---|---|
| `ids` | uuid[] | The charges of the filtered list, in its order (scheduled_at, `dir`), <= 10 000. |
| `capped` | boolean | True when the list has 10 000 or more charges (only the first 10 000 are returned). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key (a legacy name included) or closed-vocabulary value, limit out of range, dir not asc|desc.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - not a schedule of the caller's account.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- The static path `ids` ranks above GET .../entries/:entryId (find-my-way) - the literal path is part of the contract.
- EXACTLY the list's where (db/rebill.ts entryListWhere): "Select all N matching" = the list; limit / offset are accepted and ignored (cap 10 000).
- BREAKING: status -> entryStatus (+ declined / blocked, the report classification), reason -> entryReason (CSV now), search -> q; `status` is now the CHARGE status of the entry's transaction. A legacy name is a 400.
- Every filter reads the entry alone (EXISTS probes on its transaction / its sale): the count and the ids never pay the per-entry detail joins.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/subscription/schedules/:id/history`

**Scope** `subscriptions.read` - **Schedule history**

Returns the audit trail of a schedule (rebill_schedule_history): every user action and engine status change with its actor and a JSON `changes` payload, newest first, capped at 200 rows.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "rows": [
    {
      "id": "5e6f7a8b-9c0d-4e1f-a2b3-c4d5e6f7a8b9",
      "action": "override",
      "actor": "ops@example.com",
      "changes": {
        "field": "amount_cents",
        "from": 6999,
        "to": 4999,
        "at": "2026-09-19T12:00:00.000Z",
        "by": "ops@example.com",
        "entries": 202
      },
      "note": null,
      "created_at": "2026-09-19T12:00:00.120Z"
    },
    {
      "id": "6f7a8b9c-0d1e-4f2a-b3c4-d5e6f7a8b9c0",
      "action": "status_changed",
      "actor": "dispatch",
      "changes": {
        "from": "pending",
        "to": "partial"
      },
      "note": null,
      "created_at": "2026-09-19T13:41:05.000Z"
    },
    {
      "id": "7a8b9c0d-1e2f-4a3b-c4d5-e6f7a8b9c0d1",
      "action": "created",
      "actor": "subscriptions",
      "changes": {
        "subscription": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
        "runDay": "2026-09-19"
      },
      "note": null,
      "created_at": "2026-09-01T14:02:11.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Newest first, max 200. |
| `rows[].action` | string | created \| status_changed \| cancelled \| processing_cancelled \| decline_retry_reset \| post_dispatch_rerun \| rescheduled \| rescheduled_today \| test_reset \| override \| merged \| deleted \| job_cancelled \| job_resumed \| force_bill_sub \| v3.9.12: paused \| resumed (the Pause / Resume of the day) ... |
| `rows[].actor` | string | The operator e-mail, 'apikey:<name>'-style key identity, or an engine actor ('dispatch', 'subscriptions', 'dispatch:post'); 'user' when the caller has no e-mail. |
| `rows[].changes` | object\|null | Action-specific JSON (counts, from/to, job id...). |
| `rows[].note` | string\|null | Free-text note some actions add. |
| `rows[].created_at` | string (ISO-8601) | When it happened. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- History writes are fire-and-forget: a row can be missing if its insert failed, and rows may arrive a few ms after the action response.
- Deleting the schedule erases its history (cascade).
- No pagination - only the 200 most recent rows are ever returned.

##### `GET /v1/subscription/schedules/:id/jobs`

**Scope** `subscriptions.read` - **List the jobs of a schedule**

Returns the manual jobs (Force bill / Sample) ever started on a schedule, newest first, capped at 50, with their counters, phase flags and log lines. v3.9.9 (F5) - each job carries `blocked`: its failed entries refused before any MID or left without a transaction row (the console shows Declined = failed - blocked and Blocked apart; the persisted `failed` counter keeps them all).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "rows": [
    {
      "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
      "owner_email": "ops@example.com",
      "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "kind": "force",
      "sample_size": null,
      "test_mode": false,
      "status": "done",
      "control": null,
      "worker": "srv-1:4821",
      "heartbeat_at": "2026-09-19T14:02:40.000Z",
      "cursor_entry_id": "9b7e6d5c-1111-4f22-a333-444455556666",
      "total": 202,
      "sent": 202,
      "success": 171,
      "failed": 29,
      "rejected": 2,
      "skipped": 0,
      "generation_done": true,
      "dispatch_done": true,
      "post_dispatch_done": true,
      "error": null,
      "logs": [
        "> force bill - 202 charges",
        "... batch 12/21: 10 sent, 8 approved"
      ],
      "started_at": "2026-09-19T14:00:02.000Z",
      "finished_at": "2026-09-19T14:21:10.000Z",
      "created_at": "2026-09-19T14:00:01.000Z",
      "updated_at": "2026-09-19T14:02:40.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Job rows, newest first (max 50). |
| `rows[].id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `rows[].schedule_id` | uuid | The schedule being dispatched. |
| `rows[].kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `rows[].sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `rows[].test_mode` | boolean | Simulated results, nothing charged. |
| `rows[].route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `rows[].status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `rows[].control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `rows[].total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `rows[].blocked` | integer | Of `failed`, the entries claimed by the job that were refused before any MID or left no transaction row (cumulative across pause / resume). Declined = failed - blocked. |
| `rows[].generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `rows[].error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `rows[].logs` | string[] | Human log lines (capped at 2000). |
| `rows[].started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |
| `rows[].drip_delay_seconds` | integer | Persisted pacing delay in seconds; 0 means normal dispatch. |
| `rows[].next_dispatch_at` | timestamp \| null | Earliest next dispatch time for a paced job. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- At most one job is active per schedule (partial unique index) - the rest are history.
- logs can hold up to 2000 lines per job; the payload can be large.

##### `POST /v1/subscription/schedules/:id/jobs`

**Scope** `subscriptions.write` - **Start a manual job (Force bill / Sample)**

Creates a manual dispatch job on a pending / partial schedule and flips the schedule to 'dispatching'. kind 'force' charges every pending charge that exists when the job starts (its budget); kind 'sample' sends only sampleSize charges. The job is executed asynchronously by the job worker (poll GET /v1/subscription/jobs/:jobId). If an active job already exists it is returned instead (200, resumed: true). Refused when the account's dispatch kill switch is off (423). v3.9.12 - the operator (2026-09-28: " laisse moi choisir le MID/ATRI ou juste Use original en l'affichant "): an optional ROUTE for every charge of the job (rebill/manualRoute.ts) - an ATRI (`atriId`: that ATRI replaces the split's pick and its routing chooses the MID - its profiles apply) or a MID (`midId`: that MID is the ONLY attempt - pinOnly, the dashboard Retry's rule, no cascade - , inside the active ATRI that holds it: the day's own ATRI split first, then the account default, then the oldest); neither = "Use original" (the day's ATRI split, else the account's default ATRI - the engine's own path, unchanged). Validated before the job exists and stored on it (`job.route`).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped), status pending or partial. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: force\|sample; default `force` | no | 'force' = bill every pending charge; 'sample' = only sampleSize charges (unbounded by the force budget). |
| `sampleSize` | integer; default `5` | no | 1..100. Charges a sample job sends. Ignored (stored as null) for force. |
| `testMode` | boolean; default `false` | no | Simulate results without charging. OR-ed with the schedule's own test_mode (a test schedule always runs in test mode). |
| `atriId` | uuid | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `midId` | uuid | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `dripDelaySeconds` | integer 0..86400; default `0` | no | Delay between successive rebills. 0 retains normal dispatch; a positive value dispatches serially and persists the next dispatch time across pauses/restarts. |

**Request body**

```json
{
  "kind": "sample",
  "sampleSize": 5,
  "testMode": true,
  "dripDelaySeconds": 10
}
```

**Response**

```json
{
  "job": {
    "id": "d4e5f6a7-b8c9-4d0e-9f1a-2b3c4d5e6f70",
    "owner_email": "ops@example.com",
    "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
    "kind": "sample",
    "sample_size": 10,
    "test_mode": false,
    "route": {
      "atriId": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
      "atriName": "Main Rebill",
      "midId": null,
      "midName": null
    },
    "status": "queued",
    "control": null,
    "worker": null,
    "heartbeat_at": null,
    "cursor_entry_id": null,
    "total": 0,
    "sent": 0,
    "success": 0,
    "failed": 0,
    "rejected": 0,
    "skipped": 0,
    "generation_done": false,
    "dispatch_done": false,
    "post_dispatch_done": false,
    "error": null,
    "logs": [],
    "started_at": null,
    "finished_at": null,
    "created_at": "2026-09-19T14:00:01.000Z",
    "updated_at": "2026-09-19T14:00:01.000Z"
  },
  "resumed": false
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The created (or already active) job row. |
| `job.id` | uuid | Job id (poll GET /v1/subscription/jobs/:jobId). |
| `job.schedule_id` | uuid | The schedule being dispatched. |
| `job.kind` | enum: force\|sample | 'force' = Force bill (every pending charge that existed when the job started); 'sample' = only sample_size charges. |
| `job.sample_size` | integer\|null | Charges a sample job sends; null for force. |
| `job.test_mode` | boolean | Simulated results, nothing charged. |
| `job.route` | object\|null | The operator's route for every charge of the job (rebill_dispatch_jobs.route, migration 171): {atriId, atriName, midId, midName} - a MID route names its ATRI too; null = "Use original" (the day's ATRI split, else the account's default ATRI). |
| `job.status` | enum: queued\|running\|paused\|cancelled\|done\|error | Lifecycle; queued/running/paused are ACTIVE (one active job per schedule). |
| `job.control` | enum: pause\|cancel\|null | Pending control request picked up by the runner between batches. |
| `job.total` | integer | Charges in the budget; sent / success / failed / rejected / skipped are the running counters. |
| `job.generation_done` | boolean | Phase flags: generation_done, dispatch_done, post_dispatch_done. |
| `job.error` | string\|null | Error / pause reason (e.g. 'Cancelled by user', 'Subscription dispatch is OFF for this account'). |
| `job.logs` | string[] | Human log lines (capped at 2000). |
| `job.started_at` | string\|null | started_at / finished_at / heartbeat_at / created_at / updated_at instants; worker = runner id; cursor_entry_id = resume cursor. |
| `resumed` | boolean | false (HTTP 202): a new job was created. true (HTTP 200): an active job already existed and is returned untouched - your kind / sampleSize / testMode - and v3.9.12 route - were ignored (the route is still validated first). |
| `job.drip_delay_seconds` | integer | Persisted pacing delay in seconds; 0 means normal dispatch. |
| `job.next_dispatch_at` | timestamp \| null | Earliest next dispatch time for a paced job. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - kind not force|sample, sampleSize out of 1..100, testMode not boolean, atriId / midId not a uuid (v3.9.12).
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"The day changed meanwhile (paused or cancelled) - reload it"} - v3.9.12: a Pause / Cancel landed between the status check and the job: the flip to dispatching is a compare-and-set from pending / partial, the queued job is withdrawn (a runner that already claimed it stops on the day's status).
- `409` {"error":"The day was re-routed meanwhile - reload it"}: a day route was saved while the job was starting; the job was withdrawn, start it again.
- `409` {"error":"A job was starting on this day and has finished - retry"}: another job held the day and ended in between.
- `422` {"error":"Schedule is <status>"} - only pending / partial schedules can be dispatched (v3.9.12: a paused day is 422 {"error":"Schedule is paused"} - resume it first); {"error":"Choose one route: an ATRI or a MID"} (both given), {"error":"Unknown or inactive ATRI"}, {"error":"Unknown MID"}, {"error":"MID is disabled"}, {"error":"MID is not in any active ATRI"} - v3.9.12, the route refused before anything is written.
- `422` Unknown/inactive ATRI, ATRI without an activated card-capable MID, disabled MID, unsupported card adapter, MID outside active ATRIs, or both atriId and midId supplied.
- `423` {"error":"Subscription dispatch is OFF for this account"} - PATCH /v1/subscription/settings/global {enabled:true} first.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- This starts REAL card charges (rebills) of the day's pending charges, unless testMode is true or the schedule is a test schedule. It is not idempotent: a second call while a job is active returns that job (200, resumed: true) instead of starting another.
- 202 Accepted on creation, 200 when an active job was already there (resumed: true) - check the status code or `resumed`.
- The job runs on a worker: the response shows status 'queued' with zero counters; poll GET /v1/subscription/jobs/:jobId.
- Force bill budget = the charges that existed when the job STARTED: a 'retry soon' the engine plans during the run keeps its slot for the auto dispatcher and never steals the budget.
- While a job is active the auto dispatcher skips the schedule, and most schedule actions answer 409 / 422 until it ends.
- testMode charges nothing but still writes simulated results (reset them with POST .../reset-test on a test schedule).
- The schedule status becomes 'dispatching' immediately; it is recomputed when the job finishes or is cancelled.
- The route is the job's, for every charge it sends: the job log's first line names it ('> Force Bill started on <worker> - ATRI Main Rebill' / '- MID <name> (ATRI <name>)' / '- original route'), the 'status_changed' history row carries it. A retry the engine plans after a decline takes the original route.
- A chosen MID is still checked like any pin: the rebill routing constraints (docs/SUBSCRIPTIONS.md section 7 - a MID a rule rules out for this order is dropped), its monthly cap and the card's brand. A MID refused there is NOT sent and the charge ends as a technical error ('MID ... is not available for this charge') - no cascade to another MID; the engine then treats it like any technical error.
- With no route ("Use original"), each charge takes its own route override, else its day's, else the ATRI split (precedence: this route > charge > day > split).
- A sample is still capable of real charges unless testMode=true (or the schedule is already in test mode). Drip-feed is pacing, not an approval or cancellation safeguard.
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.

##### `POST /v1/subscription/schedules/:id/override`

**Scope** `subscriptions.write` - **Override the day or the amount of a schedule**

Bulk override of one day (migration 121). field 'amount_cents': every 'scheduled' charge of the day gets the amount (the subs keep their own amount - this day only). field 'run_day': the day moves to another New York day; its pending charges shift by the same number of days keeping their wall-clock, and their subs' next_charge_at follow. If the product already has a schedule on the target day the charges MERGE into it (duplicates cancelled, source cancelled, target reopened). Refused on done / dispatching days or while a job runs; the override is recorded on the schedule and in history.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `field` | enum: run_day\|amount_cents | **yes** | Discriminator: what to override. |
| `to` | string (YYYY-MM-DD) \| integer | **yes** | For run_day: a New York day matching ^\d{4}-\d{2}-\d{2}$, not the current day, not before today. For amount_cents: integer 1..1000000 (cents). |

**Request body**

```json
{
  "field": "run_day",
  "to": "2026-09-22"
}
```

**Response**

```json
{
  "ok": true,
  "field": "run_day",
  "days": 3,
  "mode": "merge",
  "targetId": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
  "moved": 198,
  "subs": 198,
  "duplicates": 4,
  "from": "2026-09-19",
  "to": "2026-09-22"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `field` | enum: run_day\|amount_cents | Echo of the override kind. |
| `to` | string\|integer | Echo of the new value. |
| `from` | string\|integer\|null | run_day: the previous day. amount_cents: the amount replaced (previous amount override, else the product amount, else the schedule price). |
| `entries` | integer | amount_cents only: 'scheduled' charges that received the amount. |
| `days` | integer | run_day only: signed day shift applied to every charge. |
| `mode` | enum: move\|merge | run_day only: 'merge' when the subscription already had a schedule on the target day (charges moved INTO it, this schedule cancelled); legacy schedules always 'move'. |
| `targetId` | uuid | run_day only: the schedule that now holds the charges (this id on move, the existing day on merge). |
| `moved` | integer | run_day only: charges shifted. |
| `subs` | integer | run_day only: subs whose next_charge_at followed their charge. |
| `duplicates` | integer | run_day only (merge): charges cancelled because the customer already had a live charge in the target day (their sub re-pinned to that one). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - bad discriminator, amount out of 1..1000000, day not YYYY-MM-DD.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `422` {"error":"Schedule is <status>"} - done or dispatching.
- `422` {"error":"A job is running - cancel it first"} - note 422 here, not 409.
- `422` {"error":"The schedule is already on this day"}.
- `422` {"error":"The day is over"} - target day before today (New York).
- `422` {"error":"A job is running on the target day - cancel it first"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Unlike the sub-level amount edit, an amount override changes the CHARGES of this day only: the subs keep their amount_cents and the next cycle is planned at the sub's price again.
- The amount override also overwrites dunning-retry charges (profile amount) present in the day.
- After a merge the schedule you called is 'cancelled' and empty; keep working with `targetId`. A done / cancelled target is reopened (status re-derived).
- On a move, a name ending in ' - <old run_day>' is renamed to the new day (best effort - kept if the name is taken).
- Moving to today places the charges at today's wall-clock of their old slot; slots already past today are then overdue and re-spread by the engine within minutes.
- Cancelled / error schedules CAN be overridden (only done / dispatching are refused) - moving a cancelled day moves 0 charges but still changes its run_day.
- Every override appends {field, from, to, at, by} to schedule.overrides (shown as "(edited)").

##### `POST /v1/subscription/schedules/:id/pause`

**Scope** `subscriptions.write` - **Pause a schedule**

The operator (2026-09-28): " une option pour pauser une Schedule et la reprendre quand je veux ". Stops a pending / partial day from sending and changes NOTHING else: its charges stay planned ('scheduled'), its subs stay active and pinned to them (rebill/scheduleStop.ts pauseSchedule). The status flips to the sticky 'paused' FIRST - one compare-and-set, refused while a manual job is queued / running / paused on the day: from that instant no claim takes a charge of the day (the auto dispatch claims pending / partial days, a Force bill / Sample job pending / partial / dispatching, a per-sub Force bill pending / partial - each reads the status in its own statement); a charge already claimed completes and records its result. markMissed never reads a paused day; Safe-Guard is not evaluated on it. The stop is recorded (rebill_schedule_stops, migration 171: kind 'pause', who, when, the status before), a status override {field: 'status', from, to: 'paused'} is appended and a 'paused' history row written. POST .../resume sends it again.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped), status pending or partial. |

**Response**

```json
{
  "ok": true,
  "status": "paused"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `status` | enum: paused | The day's new status. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"A job is running on this day - pause or cancel the job first"} - a Force bill / Sample job is queued / running / paused on the day (checked inside the flip's own statement).
- `422` {"error":"Schedule is <status> - only a pending or partial day can be paused"} - dispatching, done, cancelled, error, or already paused.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Nothing reaches a customer's timeline: a pause touches no sub and no charge (the customer-event registry allow-lists the route). The subs stay Active with their planned charge - only the day waits.
- While the day is paused: POST .../jobs answers 422 {"error":"Schedule is paused"}; POST /v1/subscription/subs/:id/charge-now answers 422 {"error":"The day of this charge is paused - resume the schedule first"} for a sub whose current charge sits in the day; product edits (name / ATRI split / retry profile) still reach it.
- 'paused' is sticky like 'cancelled' / 'error': the status derivation never leaves it - only POST .../resume does, or POST .../cancel, which cancels the paused day like any other (and records it). GET /v1/subscription/schedules/:id carries the open stop in `stop` (kind 'pause').
- The slots keep passing while the day waits: Resume re-spreads the past ones over the rest of today and moves an older day into today - never a burst.
- A running job is not paused by this route: pause the JOB (POST /v1/subscription/jobs/:jobId/pause - the day stays 'dispatching') or cancel it first.

##### `POST /v1/subscription/schedules/:id/rerun-post-dispatch`

**Scope** `subscriptions.write` - **Re-run post-dispatch (legacy retry child)**

Re-runs the legacy post-dispatch step for a 'done' / 'partial' schedule: when the schedule has a retry profile, its sub-less failed charges (all of them, or only insufficient-funds ones per the profile scope) are copied into a find-or-create '<name> - Retry' child schedule at processed_at + delay_hours. Idempotent (existing child entries are diffed). Subscription, retry and test schedules are skipped. Writes a 'post_dispatch_rerun' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "rebillChild": null,
  "retryChild": {
    "id": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
    "runDay": "2026-09-20",
    "added": 14
  }
}
```

| response field | type | description |
|---|---|---|
| `rebillChild` | null | Always null - recurring rebills are no longer spawned as children (customers continue through subs). |
| `retryChild` | object\|null | {id, runDay, added} of the (first) retry child touched; null when nothing was eligible (no profile, no failed sub-less charges, or none matching the scope). |
| `skipped` | string | Present when nothing ran: 'subscription schedules continue through their subs' \| 'retry schedules never spawn' \| 'test mode never spawns' \| 'gone'. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"A job is active"}.
- `422` {"error":"Schedule is <status>"} - only done / partial schedules.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Returns 200 with `skipped` set (and both children null) on a subscription day - the modern engine retries through the sub, so this endpoint is legacy-only.
- Failed charges may spread over several New York days (processed_at + delay): one child per day is created but only the first is returned.
- The child inherits the source and the profile amount / ATRI split; its entries are placed in the remaining window of their day (never in the past).

##### `POST /v1/subscription/schedules/:id/reschedule-now`

**Scope** `subscriptions.write` - **Re-spread overdue charges over the rest of today**

Moves the schedule's overdue 'scheduled' charges into what remains of today's New York day: charges of PAST run days whose slot passed get run_day = today, then every overdue charge of today is re-spread uniformly at random over (now + 2 min, next NY midnight] - never a burst. Only pending / partial schedules are affected by the re-spread. Writes a 'rescheduled' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "moved": 38
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `moved` | integer | Overdue charges given a new slot today. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The SCHEDULE's run_day is NOT changed: the auto dispatcher only picks schedules whose run_day is today or yesterday (New York), so on an older schedule the moved charges will not fire by themselves - use /reschedule-today (moves the day) or start a Force bill job.
- 'missed' charges are not revived here (only /reschedule-today does); no status or job precondition is checked.
- moved is 0 on a cancelled / done / dispatching schedule (the re-spread only touches pending / partial).
- A charge whose slot is within the next 2 minutes is left alone (grace for the dispatcher).

##### `POST /v1/subscription/schedules/:id/reschedule-today`

**Scope** `subscriptions.write` - **Reschedule undispatched charges to today**

Turns the charges a schedule never dispatched - 'missed' ones (sub-less or still pinned by their sub) and 'scheduled' ones of past days whose slot passed - into today's charges, spread uniformly at random over the remaining New York day, and moves the schedule itself to today (a 'done' day becomes 'partial'). Allowed on pending / partial / done schedules without an active job. Writes a 'rescheduled_today' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "missed": 38,
  "overdue": 4,
  "moved": 42,
  "run_day": "2026-09-19",
  "status": "partial"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `missed` | integer | 'missed' charges revived as 'scheduled'. |
| `overdue` | integer | 'scheduled' charges of past days pulled into today. |
| `moved` | integer | Charges that received a new random slot in the remaining day (normally missed + overdue + any other overdue charge of today). |
| `run_day` | string (YYYY-MM-DD) | The schedule's new run day (today, New York). |
| `status` | string\|null | Recomputed status. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"A manual job is running - cancel it first"}.
- `409` {"error":"A record with these details already exists."} - a SUBSCRIPTION day when the product already has a schedule for today (unique (subscription_id, run_day)); use POST .../override {field:"run_day"} which merges instead.
- `422` {"error":"Schedule is <status>"} - only pending / partial / done.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- On a subscription day whose product already has today's schedule, the run_day update trips the unique index -> 409. Use the run_day override (it merges the charges into today's day).
- A sub's missed charge is re-planned by the engine (materialise sweep) and is NOT revived here unless the sub is still pinned to it - missed can be lower than the count in /attention.
- The history note still says 'Auto Process ON' but nothing is toggled: dispatch is automatic for today/yesterday schedules.
- Charges are never fired immediately: the earliest new slot is now + 2 minutes, the latest just before New York midnight (or the next 10 minutes if called in the last minute of the day).
- Cancelled schedules are refused (422) - uncancel first.

##### `POST /v1/subscription/schedules/:id/reset-processing`

**Scope** `subscriptions.write` - **Revert in-flight charges**

Puts every 'processing' charge of the schedule back to 'scheduled' (claim cleared) and recomputes the schedule status - the manual fix for a stuck strip. Refused while a manual job is active. Writes a 'processing_cancelled' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "reverted": 3,
  "status": "partial"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `reverted` | integer | Charges moved processing -> scheduled. |
| `status` | enum: pending\|dispatching\|partial\|done\|cancelled\|error\|paused\|null | Recomputed schedule status. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"A job is active"} - cancel the manual job first.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- DOUBLE-CHARGE RISK: a charge that was actually sent to the gateway and is only waiting for its result becomes chargeable again. Use only for entries stuck for a long time (the engine already reverts auto-claimed entries stuck > 10 minutes).
- Reverted charges keep their slot: if it is already past they are re-claimed within the minute (auto dispatch) when the schedule is today/yesterday.

##### `POST /v1/subscription/schedules/:id/reset-test`

**Scope** `subscriptions.write` - **Reset a test schedule**

Wipes the simulated results of a test-mode schedule so it can be run again: every is_test charge that is not 'scheduled' returns to 'scheduled' with result fields cleared; the schedule goes back to 'pending' and its status is recomputed. Refused on a non-test schedule or while a job is active. Writes a 'test_reset' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped, test_mode must be true). |

**Response**

```json
{
  "ok": true,
  "reset": 25,
  "status": "pending"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `reset` | integer | Test charges put back to 'scheduled'. |
| `status` | string\|null | Recomputed status (pending when everything was reset). |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"A job is active"}.
- `422` {"error":"Not a test schedule"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only is_test charges are touched; a test schedule never charged anything real, so nothing is refunded or re-billed.
- Cancelled test charges are reset too (any status other than scheduled).

##### `POST /v1/subscription/schedules/:id/resume`

**Scope** `subscriptions.write` - **Resume a schedule**

The operator (2026-09-28): " la reprendre quand je veux ; sur cancel, la possibilite de la reprendre la ou elle a ete cancel ". Resumes a PAUSED day, or a CANCELLED / ERRORED one where its cancel left it (rebill/scheduleStop.ts resumeSchedule). 1. The day is held in 'paused' while it is put back (a compare-and-set on the status read: nothing claims it, nothing marks it missed). 2. A cancel's charges come back - EXACTLY the ones the cancel recorded (rebill_schedule_stops.entry_ids) that are still cancelled by it (status cancelled, decline_reason 'schedule cancelled'), one live charge per order and day (a charge whose order holds another live charge in the day stays cancelled); a day cancelled before v3.9.12 has no record and uses the older rule (every 'schedule cancelled' charge whose sub is still paused and unpinned). 3. The subs the cancel paused are re-activated and re-pinned - only those still paused, unpinned and not resumed since the cancel (a sub the operator moved meanwhile keeps its own state) - under Law (a) (docs/SUBSCRIPTIONS.md section 3.5). 4. The day's name / ATRI split / retry profile are refreshed from its product (a cancelled day missed its edits). 5. What is left is PLACED, never a burst: a slot already past (or within two minutes) is re-spread uniformly over the rest of today - a day of today or yesterday, whose charges then run today - ; an OLDER day's charges move into today with the day override (the day itself becomes today - 'move' - or merges into the product's day of today - 'merge'); a future day waits for its day. 6. The status leaves the hold ('pending', then what the charges say), the stop is stamped resumed (resumed_at / resumed_by / restored_entries / resumed_subs), a status override and a 'resumed' history row are written. A paused day skips 2 and 3: a pause stopped nothing else.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped), status paused, cancelled or error. |

**Response**

```json
{
  "ok": true,
  "status": "partial",
  "restored": 202,
  "resumed": 200,
  "refused": [
    "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d"
  ],
  "respread": 187,
  "moved": null
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `status` | enum: pending\|partial\|done\|dispatching\|cancelled | The day's status after the placement, recomputed from its charges. 'cancelled' = the day merged into the product's day of today (`moved.mode` 'merge' - its charges now live in `moved.target`). |
| `restored` | integer | Charges put back to 'scheduled' (0 for a paused day: a pause cancels nothing). |
| `resumed` | integer | Subs re-activated and re-pinned to their restored charge (0 for a paused day or a legacy schedule). |
| `refused` | uuid[] | The paused subs Law (a) kept paused: their customer already holds another live sub on any product and neither the sub nor the customer is flagged (docs/SUBSCRIPTIONS.md section 3.5). Their restored charge was cancelled again; a sub.charge.replanned event (payload resume_refused) says so. Allow several subscriptions for the customer (POST /v1/customers/:key/flag), then resume the sub. |
| `respread` | integer | Charges whose slot was past (or within two minutes) re-spread uniformly over the rest of today (New York); their run day is today now. |
| `moved` | object\|null | An OLDER day (before yesterday): {mode: 'move' (the day itself is today now) \| 'merge' (its charges went into the product's day of today), to: today's New York day (YYYY-MM-DD), target: the schedule id the charges belong to now (this day on 'move'), charges: the charges moved}. null for a day of today, yesterday or the future. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"The day changed meanwhile - reload it"} - its status changed between the read and the hold (a concurrent resume or cancel).
- `422` {"error":"Schedule is <status>"} - the day is not paused, cancelled or error.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Exactly what the stop stopped: a charge cancelled for any other reason (a blacklist, a sub paused or edited, a force-bill re-plan, a merge) never comes back, and a sub resumed, moved or ended since the cancel keeps its own state.
- Never a burst: the past slots are spread over the REST OF TODAY (New York), not sent at once; a day of next week resumed today charges nothing today - its charges go out on their day.
- Law (a) applies to the resume (v3.9.2 section 3): a paused sub whose customer holds another live sub stays paused and is listed in `refused` - the same refusal as POST /v1/subscription/subs/:id/resume answers 422 customer_has_live_sub; allow several subscriptions for the customer (POST /v1/customers/:key/flag), then resume the sub.
- Safe-Guard's stop is the same recorded cancel: Resume restores it. The safeguard_* stamp stays, and Safe-Guard trips a day ONCE - it never evaluates the resumed day again.
- On a merge the answer's `status` is the SOURCE day's ('cancelled' by the merge): follow `moved.target` for the charges.
- POST .../uncancel is this route limited to cancelled / error days (the older name, kept for callers).

##### `POST /v1/subscription/schedules/:id/retry-reason`

**Scope** `subscriptions.write` - **Retry the declines of one reason**

Re-queues the 'rebill_failed' charges of the schedule whose decline_reason equals the given text: they return to 'scheduled' with their result fields cleared. Only legacy charges and charges still pinned by their sub are eligible (a sub that already decided on the decline keeps its decision). Recomputes the status and writes a 'decline_retry_reset' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `reason` | string | **yes** | Exact (case-sensitive) decline text, <= 512 chars, matched against coalesce(decline_reason, ''). Use the values from GET .../entries `reasons[]`. An empty string targets failed charges with no reason. |

**Request body**

```json
{
  "reason": "Insufficient funds"
}
```

**Response**

```json
{
  "ok": true,
  "reset": 21,
  "status": "partial"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true. |
| `reset` | integer | Charges moved back to 'scheduled'. |
| `status` | string\|null | Recomputed schedule status. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - reason missing or > 512 chars.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Charges of subs whose sub has moved on (retry planned, sub ended) are NOT reset - reset may be lower than the reason count you saw.
- The reset charges keep their ORIGINAL slot: on a past day they are marked missed by the sweep unless you follow with /reschedule-today (or run a Force bill job).
- No job check here - a running Force bill job will pick the reset charges up if they were created before it started.
- Rejected (BIN-scrubbed) charges are not touched - only rebill_failed ones.

##### `POST /v1/subscription/schedules/:id/route`

**Scope** `subscriptions.write` - **Set a day's route override**

The operator: " donne moi "Pause" & "Cancel" & "Change ATRI/Gateway" comme option ". The DAY's persistent route (SPEC A3, migration 176 rebill_schedules.route_override): every charge of the day goes to this ATRI (its pool, its cascade) or this MID (the only attempt), unless the charge carries its own override. null = "Use original" = clear (the ATRI split). Stamped on the day (`overrides` field route -> "(edited)" + the hover line) and in its history (route_override). Product edits and Resume never touch it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (owner-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `route` | { atriId: uuid } \| { midId: uuid } \| null | **yes** | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `route.atriId` | uuid | no | Inside route: Route through this ATRI of the account (active, with an activated card-capable MID). Not with midId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `route.midId` | uuid | no | Inside route: Pin this activated MID of the account (it must belong to an active ATRI; NMI and Convesio MIDs with a supported card adapter). Not with atriId. The object holds exactly one of atriId or midId; send route: null to clear the override. |

**Request body**

```json
{
  "route": {
    "midId": "9a1b2c3d-0000-4000-8000-000000000003"
  }
}
```

**Response**

```json
{
  "ok": true,
  "route_override": {
    "kind": "mid",
    "midId": "9a1b2c3d-0000-4000-8000-000000000003",
    "name": "Acme 3"
  },
  "changed": true,
  "keepOwn": 2
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true. |
| `route_override` | object\|null | The stored override: { kind: "atri", atriId, name } \| { kind: "mid", midId, name } (+ via: "merge" when a Resume / Change date merge kept the charge's former day's ATRI) \| null. |
| `changed` | boolean | false when the day already had this route (nothing written, no stamp). |
| `keepOwn` | integer | The day's scheduled charges that carry their own route override and keep it (precedence charge > day). |

**Errors**

- `400` {"error":"Invalid request",...} - missing `route`, a non-uuid, an extra key.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}.
- `409` {"error":"A job is running"} - a Force bill / Sample job read the day once: a route written now would be ignored by it (refused rather than half-applied). Cancel or finish the job first.
- `422` {"error":"Schedule is done"} / {"error":"Schedule is error"}.
- `422` Unknown/inactive ATRI, ATRI without an activated card-capable MID, disabled MID, unsupported card adapter, MID outside active ATRIs, or both atriId and midId supplied.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Precedence at dispatch: a Force bill's job / charge-now route > the charge's override > the day's > the ATRI split. Re-resolved at each charge; unusable -> the next level, recorded on the charge's pipeline run (rebill_rules stage).
- A merge (Resume of an older day, Change date into a day that exists) keeps each moved charge's route: the source day's override becomes the charge's own; a source without one and a one-ATRI split is stamped as that ATRI (via "merge"); any other case takes the target's route and is counted (`rerouted`).
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.

##### `GET /v1/subscription/schedules/:id/transactions`

**Scope** `subscriptions.read` - **Schedule transactions and exact analytics drill-down**

List actual transactions linked to a schedule, with server pagination and exact analytics-row filters. Card and traffic dimensions use original-sale context; routing dimensions use the charged MID; hour uses the processing time in America/New_York. Reuses analytics SQL so a rebill BIN or creation hour is not mistaken for its source dimension.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule UUID, owned by the authenticated account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | Rows per page, 1-200. |
| `offset` | integer; default `0` | no | Zero-based offset, at least 0. |
| `segment` | string | no | Analytics dimension: subscription, cycle, price_point, initial_value, hour, mid, category, mcc, acquirer, processor, company, issuer, card_brand, card_type, card_level, bin, traffic, store, product, geo, device, os, decline_category. Requires key. |
| `key` | string | no | Exact key returned by the analysis row, up to 2000 characters; URL-encode special characters. Requires segment. |
| `ref` | uuid | no | Subscription row ref returned by analytics, when present. Send with segment=subscription to distinguish equal names. |
| `status` | enum | no | approved \| declined \| completed. Uses the entry outcome and excludes blocked/non-transaction attempts. Omit for every linked transaction. |
| `reason` | string | no | Exact decline reason, max 2000 characters. Separate from segment/key; returns declined transactions only. |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "order_id": "order-1",
      "created_at": "2026-10-20T12:00:00Z",
      "amount_cents": 2999,
      "currency": "USD",
      "status": "approved",
      "is_success": true,
      "final_account_name": "Example MID",
      "decline_reason": null,
      "card_brand": "Visa",
      "card_last4": "1234",
      "final_account_id": "00000000-0000-4000-8000-000000000003"
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Current page: id, order_id, created_at, integer amount_cents, currency, status, is_success, final_account_id (nullable gateway UUID), final_account_name, decline_reason, card_brand, card_last4. No full card or raw gateway payload. |
| `total` | integer | Exact count of matching distinct linked transactions, including when offset is beyond the final page. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: unknown query key, unknown segment, limit outside 1..200, negative offset, segment without key (or key without segment), ref without segment=subscription, or reason combined with a segment.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: no schedule with this id in the account (another account's id answers the same).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Read-only. Does not charge, retry, resume or change a schedule.
- Without analytics filters, includes every linked transaction; pending entries without a transaction cannot appear.
- All source/entry/transaction ownership checks remain enforced.
- Example: /v1/subscription/schedules/{id}/transactions?segment=bin&key=403163&status=declined&limit=50&offset=0
- For analytics totals use status=completed; for a subscription row include its ref if present.

##### `POST /v1/subscription/schedules/:id/uncancel`

**Scope** `subscriptions.write` - **Uncancel a schedule**

Reopens a 'cancelled' or 'error' day where its cancel left it - v3.9.12: the older name of POST .../resume, limited to those two statuses (a paused day is 422 here), with the same steps and the same answer (see POST /v1/subscription/schedules/:id/resume). EXACTLY the charges the cancel recorded come back (a day cancelled before v3.9.12: every 'schedule cancelled' charge whose sub is still paused and unpinned), EXACTLY the subs it paused are re-activated and re-pinned - under Law (a) (docs/SUBSCRIPTIONS.md section 3.5): a paused sub whose customer (e-mail  union  card) holds another live sub on any product stays paused unless the sub or the customer is flagged, its restored charge is cancelled again and its id is listed in `refused` - , the day's settings are refreshed from its product and what is left is placed over the rest of today (an older day moved into today), never a burst. Records a status override and a 'resumed' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Schedule id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "status": "partial",
  "restored": 202,
  "resumed": 200,
  "refused": [
    "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d"
  ],
  "respread": 187,
  "moved": null
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `status` | enum: pending\|partial\|done\|dispatching\|cancelled | The day's status after the placement, recomputed from its charges. 'cancelled' = the day merged into the product's day of today (`moved.mode` 'merge' - its charges now live in `moved.target`). |
| `restored` | integer | Charges put back to 'scheduled' (0 for a paused day: a pause cancels nothing). |
| `resumed` | integer | Subs re-activated and re-pinned to their restored charge (0 for a paused day or a legacy schedule). |
| `refused` | uuid[] | The paused subs Law (a) kept paused: their customer already holds another live sub on any product and neither the sub nor the customer is flagged (docs/SUBSCRIPTIONS.md section 3.5). Their restored charge was cancelled again; a sub.charge.replanned event (payload resume_refused) says so. Allow several subscriptions for the customer (POST /v1/customers/:key/flag), then resume the sub. |
| `respread` | integer | Charges whose slot was past (or within two minutes) re-spread uniformly over the rest of today (New York); their run day is today now. |
| `moved` | object\|null | An OLDER day (before yesterday): {mode: 'move' (the day itself is today now) \| 'merge' (its charges went into the product's day of today), to: today's New York day (YYYY-MM-DD), target: the schedule id the charges belong to now (this day on 'move'), charges: the charges moved}. null for a day of today, yesterday or the future. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the schedule id does not exist OR belongs to another account (indistinguishable on purpose).
- `409` {"error":"The day changed meanwhile - reload it"} - its status changed between the read and the hold (a concurrent resume or cancel).
- `422` {"error":"Schedule is <status>"} - the schedule is not cancelled / error (a paused day: POST .../resume).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only the charges the cancel cancelled come back (recorded since v3.9.12); charges cancelled for other reasons (blacklist, sub paused, merged...) stay cancelled.
- A sub's charge is restored only if the sub is still paused and unpinned and was not resumed since the cancel (nothing happened to it since); a sub resumed by hand or re-planned meanwhile keeps its own charge.
- Law (a) applies to the resume (v3.9.2 section 3): a paused sub whose customer holds another live sub stays paused and is listed in `refused` - the same refusal as POST /v1/subscription/subs/:id/resume answers 422 customer_has_live_sub; allow several subscriptions for the customer (POST /v1/customers/:key/flag), then resume the sub.
- Safe-Guard's stop is the same recorded cancel: Resume restores it. The safeguard_* stamp stays, and Safe-Guard trips a day ONCE - it never evaluates the resumed day again.
- Nothing to follow up on a past day: the past slots are re-spread over the rest of today, and an older day's charges move into today (`moved`); a future day waits for its day.

##### `POST /v1/subscription/schedules/analysis`

**Scope** `subscriptions.write` - **Analyse several schedules (background report)**

Queue a background analysis over the union of the charges of 1 to 500 schedules (the bulk "Analytics" of the Schedules list). Returns 202 {jobId, job} once the job is durably admitted. Poll GET /v1/metrics/jobs/:jobId, then read GET /v1/metrics/jobs/:jobId/result. Schedules not visible to the account are dropped at admission; losing access to a selected one later fails the whole calculation (never a partial result).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | uuid[] | **yes** | 1..500 schedule ids of the account (duplicates collapse; the set is sorted, so the order does not matter). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `x-request-id` | uuid; default `a random uuid` | no | Idempotency key of the admission: replaying the same id with the same ids returns the same job; the same id with other ids answers 409. Omitted: a new id each call. |

**Request body**

```json
{
  "ids": [
    "00000000-0000-4000-8000-000000000001",
    "00000000-0000-4000-8000-000000000002"
  ]
}
```

**Response** `202`

```json
{"jobId": "00000000-0000-4000-8000-000000000003", "job": {"id": "00000000-0000-4000-8000-000000000003", "kind": "schedule-selection", "status": "queued"}}
```

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} (ids missing, empty, over 500 or not uuids), {"error":"Invalid request reference"} (x-request-id not a uuid) or {"error":"Invalid schedule selection"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: none of the selected schedules is visible to the account.
- `409` {"error":"Three reports are already running for this account. Wait or cancel one."} or {"error":"Request ID already used for a different report"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Schedule background reports are temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when background workers or the report storage are unavailable; retry later.

**Gotchas**

- The result is the same breakdown family as GET /v1/subscription/schedules/:id/analysis, over all selected days. Results are kept 24 hours.

##### `GET /v1/subscription/schedules/attention`

**Scope** `subscriptions.read` - **Schedules needing attention**

Lists the account's schedules (status pending / partial / done) that still hold charges never dispatched: entries marked 'missed', or 'scheduled' entries whose slot passed more than 5 minutes ago. This drives the "reschedule today" alert. Read-only.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "name": "Approved orders 2026-09-10 -> 2026-09-12",
      "run_day": "2026-09-17",
      "status": "partial",
      "auto_dispatch_enabled": false,
      "test_mode": false,
      "missed": 38,
      "overdue": 0
    }
  ],
  "timezone": "America/New_York",
  "today": "2026-09-19"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Ordered by run_day, created_at. |
| `rows[].id` | uuid | Schedule id. |
| `rows[].missed` | integer | Entries with status 'missed' (not dispatched within a day of their slot). |
| `rows[].overdue` | integer | Entries still 'scheduled' whose slot is older than 5 minutes. |
| `rows[].status` | enum: pending\|partial\|done | Only these statuses are considered. |
| `rows[].auto_dispatch_enabled` | boolean | Legacy flag (dispatch is automatic for today/yesterday schedules since v3.0). |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `today` | string (YYYY-MM-DD) | Today's New York day. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Cancelled / error / dispatching schedules never show here even if they hold missed charges.
- The fix for a listed schedule is POST /v1/subscription/schedules/:id/reschedule-today.
- A sub's missed charge is re-planned by the engine itself; only sub-less or still-pinned charges are revived by the schedule actions.

##### `POST /v1/subscription/schedules/bulk`

**Scope** `subscriptions.write` - **Bulk Pause / Resume / Cancel / Change route of schedule days**

ONE endpoint for the /subscriptions/schedules bulk: pause, resume, cancel or set the route of up to 1 000 days. Each day goes through the single operation's own function (its audit: the stop row, the `overrides` stamp, the history - `by` = the operator); the eligibility is the row menu's. `preview: true` writes nothing and answers the same eligibility (the modal's Eligible / Skipped). Pause / Cancel / Route run 4 days at a time; Resume one day at a time, oldest first (two older days of one product both merge into today's day).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `ids` | uuid[] (1..1000) | **yes** | Schedule ids (duplicates collapse). An id of another account / unknown -> a skipped result "Not found". |
| `action` | enum: pause\|resume\|cancel\|route | **yes** | pause: pending / partial days, no job. cancel: pending / partial / paused, no job (the pending charges are cancelled, the subs paused - Resume restores them). resume: paused / cancelled / error (a day older than yesterday merges into today). route: any day but done / error, no job. Required in synchronous mode or when async actions[] is absent. |
| `route` | { atriId: uuid } \| { midId: uuid } \| null | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `route.atriId` | uuid | no | Inside route: Route through this ATRI of the account (active, with an activated card-capable MID). Not with midId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `route.midId` | uuid | no | Inside route: Pin this activated MID of the account (it must belong to an active ATRI; NMI and Convesio MIDs with a supported card adapter). Not with atriId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `preview` | boolean; default `false` | no | true = nothing written: each day's eligibility and the summary. |

**Request body**

```json
{
  "ids": [
    "11111111-1111-4111-8111-111111111111"
  ],
  "action": "pause",
  "preview": true
}
```

**Response**

```json
{
  "results": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "ok": true,
      "name": "VIP - 2026-09-29",
      "runDay": "2026-09-29",
      "status": "pending",
      "pending": 412,
      "keepOwn": 0,
      "reroute": 0
    }
  ],
  "summary": {
    "done": 0,
    "skipped": 0,
    "failed": 0,
    "eligible": 1,
    "pending": 412,
    "pastDays": 0,
    "keepOwn": 0,
    "reroute": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `results` | array | One per id, in the request's order. |
| `results[].ok` | boolean | Eligible (preview) / written (run). |
| `results[].skipped` | true | Not eligible (the row menu's rules) or not found - `error` says why ("Schedule is done", "A job is running", "Not found"). |
| `results[].error` | string | The skip reason, or the operation's refusal (e.g. "Cancel the running job first"); "Unexpected error" for an internal failure (logged). |
| `results[].detail` | string | Run: "Paused" - "Cancelled - 3 charges - 1 sub paused" - "Resumed - 3 charges back - 2 subs - merged into today (n) - n re-spread - 1 charge takes today's route" - "Route -> ATRI X - 2 charges keep their own route" - "Unchanged" (every count agrees with its noun and verb). |
| `results[].name / runDay / status / pending` | string\|integer | The day (name, New York day, status, pending charges: the scheduled ones - for action resume, plus the cancelled ones the Resume would put back: the open cancel stop's recorded charges, or every "schedule cancelled" one of a day stopped before v3.9.12; an upper bound, the run's detail says the exact count). |
| `results[].keepOwn` | integer | action route: scheduled charges with their own route override (they keep it). |
| `results[].reroute` | integer | action resume of a past day: charges that would take today's day route (no override of theirs or their day's, a split of != 1 ATRI, today's day holding one) - counted over the same charges as pending (the ones the Resume puts back included). 0 on production (every live split has one ATRI). |
| `results[].pastDay` | boolean | action resume: the day is older than yesterday (it merges into today). |
| `summary` | object | { done, skipped, failed, eligible, pending, pastDays, keepOwn, reroute } (preview: done = 0). |

**Errors**

- `400` {"error":"Invalid request",...} - > 1000 ids, a non-uuid, an unknown action, an extra key (strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"route goes with action route only"} - {"error":"Route required: { atriId } | { midId } | null"} - the route's resolution errors (wallet MID, ATRI without a card MID, unknown / disabled / inactive).
- `422` Unknown/inactive ATRI, ATRI without an activated card-capable MID, disabled MID, unsupported card adapter, MID outside active ATRIs, or both atriId and midId supplied.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- No server-side batch row: the Report is the modal's; each day carries the single operation's own audit.
- A per-day refusal is a result, never a 4xx: the call answers 200 with every id.
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.

##### `GET /v1/subscription/schedules/bulk-jobs`

**Scope** `subscriptions.read` - **List schedule bulk jobs**

Lists up to 20 schedule bulk jobs of the caller (same account and same caller scope): the one named by requestId first, then held jobs, then active ones, then newest.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Puts the job created with this requestId first (to recover a job whose 202 was lost). Not a uuid = 400. |

**Response**

```json
{
  "jobs": [
    {
      "id": "11111111-2222-4333-8444-555555555555",
      "request_id": "22222222-3333-4444-8555-666666666666",
      "status": "running",
      "total": 3,
      "processed": 1,
      "succeeded": 1,
      "failed": 0,
      "skipped": 0,
      "units_processed": 1,
      "cancel_requested": false,
      "error": null,
      "created_at": "2026-11-24T09:00:00.000Z",
      "updated_at": "2026-11-24T09:00:02.000Z",
      "finished_at": null,
      "held": false,
      "action": "pause",
      "preview": false,
      "result": {
        "done": 1,
        "skipped": 0
      },
      "errors": []
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | Jobs, at most 20, same fields as job in POST /v1/subscription/schedules/bulk-jobs. |

**Errors**

- `400` {"error":"Invalid request reference"}: requestId is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.read"} when the key's scopes lack subscriptions.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers carry Cache-Control: no-store.
- Only the caller's own jobs are listed: a job created by another key or member of the account is not visible.

##### `POST /v1/subscription/schedules/bulk-jobs`

**Scope** `subscriptions.write` - **Create a schedule bulk job**

Queues one durable job that applies the same action to up to 10000 rebill schedules (schedule days) of the account: pause, resume, cancel, route (set or clear the route override), amount (change the charge amount of the scheduled entries) or run_day (move or merge to another day). With preview:true nothing changes: each schedule's result reports what would happen (pending, keepOwn, reroute counts). Answers 202 once the job is committed; poll GET /v1/subscription/schedules/bulk-jobs/:id and read GET .../results.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key per account. The same requestId with the same input and caller returns the existing job (202); with a different input or another caller, 409 "Request ID already belongs to different input or permissions". |
| `ids` | uuid[] 1..10000 | **yes** | Rebill schedule ids of the account (duplicates are removed). One id that is not a schedule of the account = 404 "One or more schedules are unavailable" and nothing is queued. |
| `action` | "pause" \| "resume" \| "cancel" \| "route" \| "amount" \| "run_day" | **yes** | pause: pause the day's charges. resume: resume a paused or cancelled day (a past day is moved to today, New York time). cancel: cancel the day's scheduled charges (their subscriptions are paused). route: set or clear the route override (role admin only). amount: set a new amount on the day's scheduled charges. run_day: move (or merge into an existing day of the same subscription) the day's charges to another day. |
| `preview` | boolean; default `false` | no | true = compute only, change nothing. A preview does not block or count as an active operation. |
| `route` | {atriId: uuid} \| {midId: uuid} \| null | no | action route only: the new route override, an ATRI or a gateway (MID) of the account, or null to clear the override (the schedule's own routing applies again). Required for route unless preview. An unknown or foreign target fails that schedule (422 in its result). Each object is strict (exactly one key). |
| `route.atriId` | uuid | no | Inside route: Route through this ATRI of the account (active, with an activated card-capable MID). Not with midId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `route.midId` | uuid | no | Inside route: Pin this activated MID of the account (it must belong to an active ATRI; NMI and Convesio MIDs with a supported card adapter). Not with atriId. The object holds exactly one of atriId or midId; send route: null to clear the override. |
| `to` | integer 1..1000000 \| string YYYY-MM-DD | no | amount: the new amount in cents per charge (integer, required). run_day: the target day YYYY-MM-DD (a real calendar day, required); a schedule already on that day, or a day before today (New York time), is skipped. |

**Request body**

```json
{
  "requestId": "22222222-3333-4444-8555-666666666666",
  "ids": [
    "33333333-4444-4555-8666-777777777777",
    "44444444-5555-4666-8777-888888888888"
  ],
  "action": "run_day",
  "to": "2026-12-01",
  "preview": false
}
```

**Response** `202`

```json
{
  "jobId": "11111111-2222-4333-8444-555555555555",
  "job": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "22222222-3333-4444-8555-666666666666",
    "status": "queued",
    "total": 3,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T09:00:00.000Z",
    "updated_at": "2026-11-24T09:00:00.000Z",
    "finished_at": null,
    "held": false,
    "action": "run_day",
    "preview": false,
    "result": {
      "done": 0,
      "skipped": 0
    },
    "errors": []
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | The job id. |
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | The requestId it was created with. |
| `job.status` | "queued" \| "running" \| "success" \| "partial" \| "failed" \| "cancelled" | partial = some schedules failed or a schedule is held mid-way (held true, see resume); failed = every processed schedule failed. |
| `job.total / processed / succeeded / failed / skipped` | integer | Schedule counters (skipped includes cancelled ones). |
| `job.units_processed` | integer | Worker steps done. |
| `job.cancel_requested` | boolean | A cancel was asked. |
| `job.error` | string \| null | Terminal error. |
| `job.created_at / updated_at / finished_at` | string (ISO-8601) \| null | Timestamps. |
| `job.held` | boolean | A schedule of the job is held paused mid-way (resume it with POST .../resume). |
| `job.action / preview` | string / boolean | The action and whether it was a preview. |
| `job.result` | {done, skipped} | succeeded and skipped counts. |
| `job.errors` | array | Always []: per-schedule outcomes are in GET .../results. |

**Errors**

- `400` {"error":"Invalid schedule operation","details":{...}} (zod flatten): a missing or bad field, an unknown key (strict), "Route is required" (route without route, not a preview), "Amount is required" (amount without an integer to), "Valid day is required" (run_day without a real YYYY-MM-DD).
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.write"} when the key's scopes lack subscriptions.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `404` {"error":"One or more schedules are unavailable"}: an id is not a schedule of the account.
- `409` {"error":"Another schedule operation is active"} (a non-preview schedule job of the account is queued, running or holds a schedule), {"error":"Another subscription operation is active"} (a subscription, client, transaction or past-attach bulk job of the account is running), {"error":"Request ID already belongs to different input or permissions"}.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Schedule background operations are disabled"}: background jobs are off on this deployment.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Answers carry Cache-Control: no-store.
- One non-preview schedule job per account at a time, and none while another subscription-type bulk job runs. Previews are not limited.
- Per schedule, a skip is not an error: a schedule already done or dispatching, one with an active dispatch job, or an unchanged / past run_day is reported as skipped in its result.
- A schedule that fails mid-way (for example resume) can stay held paused: the job ends partial with held true; POST .../resume finishes it, POST .../cancel leaves it paused.
- No payment is sent by this job itself; it changes the schedules the rebill engine later charges.

##### `GET /v1/subscription/schedules/bulk-jobs/:id`

**Scope** `subscriptions.read` - **Read a schedule bulk job**

Reads one schedule bulk job of the caller with its counters and status.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. Not a uuid = 400 {"error":"Invalid job ID"}. |

**Response**

```json
{
  "job": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "22222222-3333-4444-8555-666666666666",
    "status": "running",
    "total": 3,
    "processed": 1,
    "succeeded": 1,
    "failed": 0,
    "skipped": 0,
    "units_processed": 1,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T09:00:00.000Z",
    "updated_at": "2026-11-24T09:00:02.000Z",
    "finished_at": null,
    "held": false,
    "action": "pause",
    "preview": false,
    "result": {
      "done": 1,
      "skipped": 0
    },
    "errors": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | The requestId it was created with. |
| `job.status` | "queued" \| "running" \| "success" \| "partial" \| "failed" \| "cancelled" | partial = some schedules failed or a schedule is held mid-way (held true, see resume); failed = every processed schedule failed. |
| `job.total / processed / succeeded / failed / skipped` | integer | Schedule counters (skipped includes cancelled ones). |
| `job.units_processed` | integer | Worker steps done. |
| `job.cancel_requested` | boolean | A cancel was asked. |
| `job.error` | string \| null | Terminal error. |
| `job.created_at / updated_at / finished_at` | string (ISO-8601) \| null | Timestamps. |
| `job.held` | boolean | A schedule of the job is held paused mid-way (resume it with POST .../resume). |
| `job.action / preview` | string / boolean | The action and whether it was a preview. |
| `job.result` | {done, skipped} | succeeded and skipped counts. |
| `job.errors` | array | Always []: per-schedule outcomes are in GET .../results. |

**Errors**

- `400` {"error":"Invalid job ID"}
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.read"} when the key's scopes lack subscriptions.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `404` {"error":"Job not found"}: no such job for this account and caller.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers carry Cache-Control: no-store.

##### `POST /v1/subscription/schedules/bulk-jobs/:id/cancel`

**Scope** `subscriptions.write` - **Cancel a schedule bulk job**

Stops a queued or running job: schedules not started are marked cancelled, a schedule in progress stops after its committed step and stays paused (partial, held). A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. Not a uuid = 400 {"error":"Invalid job ID"}. |

**Response**

```json
{
  "job": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "22222222-3333-4444-8555-666666666666",
    "status": "cancelled",
    "total": 3,
    "processed": 1,
    "succeeded": 1,
    "failed": 0,
    "skipped": 0,
    "units_processed": 1,
    "cancel_requested": true,
    "error": null,
    "created_at": "2026-11-24T09:00:00.000Z",
    "updated_at": "2026-11-24T09:00:02.000Z",
    "finished_at": "2026-11-24T09:00:05.000Z",
    "held": false,
    "action": "pause",
    "preview": false,
    "result": {
      "done": 1,
      "skipped": 0
    },
    "errors": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | The requestId it was created with. |
| `job.status` | "queued" \| "running" \| "success" \| "partial" \| "failed" \| "cancelled" | partial = some schedules failed or a schedule is held mid-way (held true, see resume); failed = every processed schedule failed. |
| `job.total / processed / succeeded / failed / skipped` | integer | Schedule counters (skipped includes cancelled ones). |
| `job.units_processed` | integer | Worker steps done. |
| `job.cancel_requested` | boolean | A cancel was asked. |
| `job.error` | string \| null | Terminal error. |
| `job.created_at / updated_at / finished_at` | string (ISO-8601) \| null | Timestamps. |
| `job.held` | boolean | A schedule of the job is held paused mid-way (resume it with POST .../resume). |
| `job.action / preview` | string / boolean | The action and whether it was a preview. |
| `job.result` | {done, skipped} | succeeded and skipped counts. |
| `job.errors` | array | Always []: per-schedule outcomes are in GET .../results. |

**Errors**

- `400` {"error":"Invalid job ID"}
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.write"} when the key's scopes lack subscriptions.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `404` {"error":"Job not found"}
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers carry Cache-Control: no-store.
- Works even when job creation is disabled. Changes already applied to a schedule are not undone.

##### `GET /v1/subscription/schedules/bulk-jobs/:id/results`

**Scope** `subscriptions.read` - **Read schedule bulk job results**

Pages the per-schedule outcomes of a job, in the job's order.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. Not a uuid = 400 {"error":"Invalid job ID"}. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer >= 0; default `0` | no | Rows to skip. |
| `limit` | integer 1..100; default `100` | no | Page size. |

**Response**

```json
{
  "results": [
    {
      "id": "33333333-4444-4555-8666-777777777777",
      "state": "done",
      "phase": "done",
      "error": null,
      "result": {
        "id": "33333333-4444-4555-8666-777777777777",
        "ok": true,
        "name": "Example subscription",
        "runDay": "2026-11-28",
        "status": "scheduled",
        "moved": 12,
        "mode": "move",
        "detail": "Moved 12 charges"
      }
    }
  ],
  "nextOffset": 1,
  "total": 2,
  "expired": false
}
```

| response field | type | description |
|---|---|---|
| `results[].id` | uuid | Schedule id. |
| `results[].state` | "pending" \| "working" \| "done" \| "skipped" \| "failed" \| "cancelled" \| "partial" | Outcome state of that schedule. |
| `results[].phase` | string | Worker phase (start, restore, finish, done). |
| `results[].error` | string \| null | Failure or cancel reason. |
| `results[].result` | object | id, ok, skipped (reason) when skipped, name, runDay, status, detail (a sentence), plus the action's counts (preview: pending, keepOwn, reroute, pastDay; amount: entries; run_day: moved, mode move \| merge; cancel: cancelled, paused; resume: restored, resumed, refused). |
| `nextOffset` | integer \| null | offset of the next page, null at the end. |
| `total` | integer | Schedules in the job. |
| `expired` | boolean | true when no rows remain for a finished job that had some (the per-schedule rows were purged). |

**Errors**

- `400` {"error":"Invalid pagination"} (offset or limit out of range) or {"error":"Invalid job ID"}
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.read"} when the key's scopes lack subscriptions.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `404` {"error":"Job not found"}
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Answers carry Cache-Control: no-store.

##### `POST /v1/subscription/schedules/bulk-jobs/:id/resume`

**Scope** `subscriptions.write` - **Resume a held schedule bulk job**

Re-queues the held schedules of a partial job (the ones left paused mid-way), so the worker finishes them.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. Not a uuid = 400 {"error":"Invalid job ID"}. |

**Response**

```json
{
  "job": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "22222222-3333-4444-8555-666666666666",
    "status": "queued",
    "total": 3,
    "processed": 1,
    "succeeded": 1,
    "failed": 0,
    "skipped": 0,
    "units_processed": 1,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-24T09:00:00.000Z",
    "updated_at": "2026-11-24T09:00:02.000Z",
    "finished_at": null,
    "held": true,
    "action": "pause",
    "preview": false,
    "result": {
      "done": 1,
      "skipped": 0
    },
    "errors": []
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | The requestId it was created with. |
| `job.status` | "queued" \| "running" \| "success" \| "partial" \| "failed" \| "cancelled" | partial = some schedules failed or a schedule is held mid-way (held true, see resume); failed = every processed schedule failed. |
| `job.total / processed / succeeded / failed / skipped` | integer | Schedule counters (skipped includes cancelled ones). |
| `job.units_processed` | integer | Worker steps done. |
| `job.cancel_requested` | boolean | A cancel was asked. |
| `job.error` | string \| null | Terminal error. |
| `job.created_at / updated_at / finished_at` | string (ISO-8601) \| null | Timestamps. |
| `job.held` | boolean | A schedule of the job is held paused mid-way (resume it with POST .../resume). |
| `job.action / preview` | string / boolean | The action and whether it was a preview. |
| `job.result` | {done, skipped} | succeeded and skipped counts. |
| `job.errors` | array | Always []: per-schedule outcomes are in GET .../results. |

**Errors**

- `400` {"error":"Invalid job ID"}
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.write"} when the key's scopes lack subscriptions.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"Current permissions do not allow this operation"} when the caller's access, account or grants changed since the job was created (or, on create and resume, a route job by a member whose role is not admin).
- `404` {"error":"Job not found"}
- `409` {"error":"No suspended operation to resume"}: the job is not partial with a held schedule.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Schedule background operations are disabled"}
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Answers carry Cache-Control: no-store.
- A held operation started in the dashboard keeps its day reserved, and a key cannot resume it (404): jobs are visible only to the caller that created them.

##### `GET /v1/subscription/schedules/bulk-jobs/capability`

**Scope** `subscriptions.read` - **Schedule bulk jobs: capability**

Says whether durable schedule bulk jobs can be created on this deployment: {enabled:false} when background jobs are off, {enabled:true} when they are on and the job tables exist.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | true = POST /v1/subscription/schedules/bulk-jobs is accepted. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"subscriptions.read"} when the key's scopes lack subscriptions.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan lacks the subscriptions module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Required storage for schedule bulk jobs is unavailable. Complete the current database migrations."} when jobs are on but the tables are missing.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."}: the 10-second control deadline passed (the control transaction is rolled back; re-read the job before retrying).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Answers carry Cache-Control: no-store.
- Reading, cancelling and listing saved jobs keep working when creation is disabled.

##### `GET /v1/subscription/schedules/calendar`

**Scope** `subscriptions.read` - **Calendar of schedules**

Every schedule whose run day is in [from, to] (the /subscriptions/schedules calendar month), with its hover stats. v3.9.15 - every catalog key narrows the days (the schedule grain) and, under filters, each day carries `filtered` (the chips read it, FD23).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (YYYY-MM-DD) | **yes** | First run day of the window (New York), inclusive. Required. |
| `to` | string (YYYY-MM-DD) | **yes** | Last run day of the window (New York), inclusive. Required; >= from. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "name": "VIP Monthly - 2026-09-19",
      "kind": "subscription",
      "run_day": "2026-09-19",
      "status": "partial",
      "total_clients": 412,
      "has_active_job": false,
      "test_mode": false,
      "subscription": "VIP Monthly",
      "stats": {
        "sources": {
          "sale": 380,
          "sweep": 12,
          "ops@example.com": 20
        },
        "decided": 210,
        "success": 176,
        "approved_cents": 1231824,
        "planned_cents": 1413798,
        "first_pending_at": "2026-09-19T13:41:00.000Z",
        "errors": 0,
        "missed": 0,
        "force_ended": false
      },
      "overrides": []
    }
  ],
  "today": "2026-09-19"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Schedules of the window ordered by run_day, kind, name. |
| `rows[].id` | uuid | Schedule id. |
| `rows[].name` | string | Schedule name. |
| `rows[].kind` | enum: success\|declines\|retry\|subscription | Schedule kind. |
| `rows[].run_day` | string (YYYY-MM-DD) | New York day. |
| `rows[].status` | enum: pending\|dispatching\|partial\|done\|cancelled\|error\|paused | Schedule status. |
| `rows[].total_clients` | integer | Distinct customers planned into the day. |
| `rows[].has_active_job` | boolean | A manual job is queued / running / paused. |
| `rows[].test_mode` | boolean | Simulated day. |
| `rows[].subscription` | string\|null | Product name (from source.subscription); null on legacy schedules. |
| `rows[].stats` | object | {sources, decided, success, approved_cents, planned_cents, first_pending_at, errors, missed, force_ended} - errors = UNRESOLVED technical errors (a charge that ended in an ERROR, not a decline, and was not followed by a later attempt of the same charge - a later attempt resolves it, whatever its result); missed = charges never dispatched within a day of their slot; force_ended = a Force bill ran through the day, which makes the day FINISHED before its New York day is over (the chip reads Partial only on a finished day that is incomplete). |
| `rows[].overrides` | array | Recorded overrides (always an array). |
| `today` | string (YYYY-MM-DD) | Today's New York day. |
| `rows[].route_override` | object\|null | The day's route override (the chip's hover): { kind: "atri", atriId, name } \| { kind: "mid", midId, name } (+ via: "merge" when a Resume / Change date merge kept the charge's former day's ATRI) \| null. |
| `rows[].filtered` | object \| absent | Present ONLY when a catalog key narrows (hasFilters: every key but from / to / tz / refundBasis and refundTest=exclude): the figures of the row restricted to its charges matching the filters - total, scheduled, processing, pending (= scheduled + processing), success, failed, declined (= rebill_failed with a transaction row), blocked (refused before any MID or without a row), rejected, cancelled, missed, decided, approved_cents, planned_cents, processed_first / processed_last (the decided span - the /transactions link range). The row's own entry_counts / stats stay the WHOLE day's (they drive its status, progress bar and hover). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - from / to missing or not YYYY-MM-DD, a reversed range, an unknown query key or closed-vocabulary value.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Both bounds are required and inclusive; there is no cap on the span - a multi-year range returns everything.
- No `timezone` field in this response, but the days are still New York days.
- entry_counts are not included here - use the list or the detail endpoint for per-status counts.
- Strict: an unknown key is a 400; an instant `from` / `to` is a 400 (run days only).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/subscription/schedules/ids`

**Scope** `subscriptions.read` - **List the ids of the matching schedules**

The ids of every schedule the Schedules list (GET /v1/subscription/schedules) returns for the same query - its where and its order, without the per-day aggregates (entry_counts, stats, the FD23 filtered block) the list computes. For "Select all N matching" -> POST /v1/subscription/schedules/bulk. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: success\|declines\|retry\|subscription | no | Filter on kind. Note legacy retry children are excluded anyway. |
| `sort` | enum: run_day\|name\|status\|total_clients\|created_at\|kind\|schedule_type; default `run_day` | no | Sort column. Absent -> run_day. Anything else is a 400 {"error":"Invalid sort","allowed":[...]} listing the accepted columns - it no longer falls back silently to run_day (a direction passed as the key, `sort=desc`, used to return the default order). Ties break on created_at desc; nulls last. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |
| `limit` | integer | no | Validated like the list (1..10000, else 400) and then ignored: at most 10 000 ids come back. |
| `offset` | integer | no | Validated like the list (>= 0, else 400) and then ignored. |
| `from` | string (YYYY-MM-DD) | no | Filter catalog (Date): first New York run / charge day of the range, inclusive. An ISO instant is a 400 on this endpoint. |
| `to` | string (YYYY-MM-DD) | no | Filter catalog (Date): last New York run / charge day of the range, inclusive. An ISO instant is a 400 on this endpoint. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "ids": [
    "6f1c2d3e-0000-4000-8000-000000000001",
    "6f1c2d3e-0000-4000-8000-000000000002"
  ],
  "capped": false
}
```

| response field | type | description |
|---|---|---|
| `ids` | string[] | Schedule ids (uuid), in the list's order (sort / dir), at most 10 000. |
| `capped` | boolean | true when the cap (10 000) was reached - more schedules may match. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key (a legacy name included) or closed-vocabulary value, an instant `from` / `to` (days only), a reversed range; an unknown `sort` (the allowed columns listed).
- `400` {"error":"Invalid sort","allowed":[...]}: sort is not one of the list's columns.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Send the list's query unchanged (the same strict catalog, the same kind / sort / dir; limit / offset are ignored): the ids are exactly the list's rows, in its order.
- The static path `ids` ranks above GET /v1/subscription/schedules/:id (find-my-way) - the literal path is part of the contract.
- Legacy retry children never appear (as in the list). No filter at all returns every listed schedule of the account (up to the cap).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

#### Monitoring

The subscription monitoring KPIs, the engine alerts and the subscription dashboard.

##### `GET /v1/subscription/alerts`

**Scope** `subscriptions.read` - **Subscription engine alerts**

v3.9.2 section 3 - the two engine invariants of docs/SUBSCRIPTIONS.md section 6.8 for the caller's account, counted with sample sub ids: `successWithoutNext` (an active sub that paid, on an active product, with no next charge or no pin for over 5 minutes - V2) and `stuckPin` (an active sub pinned to an entry that is no longer live, processed over 10 minutes ago - V3). Both are expected 0; the Subscriptions overview and /health show them, the Telegram alert channel emits them as critical.

*No parameters.*

**Response**

```json
{
  "successWithoutNext": {"count": 0, "sampleIds": []},
  "stuckPin": {"count": 2, "sampleIds": ["06e107f0-1111-4222-8333-444455556666", "962f46ad-1111-4222-8333-444455556666"]},
  "checkedAt": "2026-09-26T16:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `successWithoutNext` | object | {count, sampleIds (<= 5, oldest first)}. |
| `stuckPin` | object | {count, sampleIds (<= 5)}. |
| `checkedAt` | string | ISO instant of the read. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Operational health is temporarily unavailable. Please refresh shortly."}: the bounded health reader is saturated or ran past its budget.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Health reads always use bounded execution. Response fields, existing role/account scope and Telegram configuration remain unchanged.
- The two HTTP reads share two dedicated connections, pending-request coalescing, cancellation and a five-second total SQL budget. Authentication middleware remains outside that budget.

##### `GET /v1/subscription/dashboard`

**Scope** `subscriptions.read` - **Subscription dashboard KPIs**

Returns the operations dashboard of the engine for a [from, to] window of New York days: processed-charge KPIs (gross / net / counts, test charges excluded), a time series (hourly buckets when from = to, daily otherwise), schedule and client counts, pending charges, MRR and active subs, the upcoming volume for 24 h / 7 d / 30 d, and the schedules currently active - plus the kill switch state, today and the caller role.

`gross_cents` is the money that came back (the approved charges). `net_cents` prices the DECIDED charges, approved **and** declined: the processor bills every authorization it took, so a declined charge nets its attempt and 3DS fees below zero. "declined_fees_cents" (over "declined_count" charges) is the slice of that cost the declines carry: it is **already inside** `net_cents` and must never be deducted again.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (YYYY-MM-DD) | **yes** | First New York day (processed_at window). |
| `to` | string (YYYY-MM-DD) | **yes** | Last day, inclusive; must be >= from. |

**Response**

```json
{
  "mrr_cents": 16657620,
  "active_subs": 2380,
  "upcoming": {
    "h24": {
      "schedules": 2,
      "entries": 410,
      "amount_cents": 2869590
    },
    "d7": {
      "schedules": 9,
      "entries": 2210,
      "amount_cents": 15467790
    },
    "d30": {
      "schedules": 31,
      "entries": 7120,
      "amount_cents": 49832880
    }
  },
  "gross_cents": 1231824,
  "net_cents": 1190310,
  "success": 176,
  "failed": 34,
  "rejected": 1,
  "schedules": 3,
  "clients": 1180,
  "active": 2,
  "pending_entries": 6900,
  "series": [
    {
      "label": "09:00",
      "success": 26,
      "failed": 4,
      "revenue_cents": 181974
    },
    {
      "label": "10:00",
      "success": 31,
      "failed": 6,
      "revenue_cents": 216969
    }
  ],
  "activeSchedules": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "name": "VIP Monthly - 2026-09-19",
      "run_day": "2026-09-19",
      "status": "partial",
      "total": 412,
      "sent": 210,
      "auto_dispatch_enabled": false
    }
  ],
  "globalDispatchEnabled": true,
  "today": "2026-09-19",
  "role": "admin"
}
```

| response field | type | description |
|---|---|---|
| `gross_cents` | integer | Approved charge volume processed in the window (non-test). |
| `net_cents` | integer | Net after gateway fees, from the transactions (0 until fees are known). |
| `success` | integer | Approved charges; failed = every rebill_failed; blocked (v3.9.9: refused before any MID or left without a transaction row, inside failed); rejected = BIN-scrubbed. |
| `schedules` | integer | Schedules whose run_day is in the window; clients = sum their total_clients. |
| `active` | integer | Schedules currently dispatching / partial / today / with in-flight charges (length of activeSchedules, max 100). |
| `pending_entries` | integer | 'scheduled' charges of pending / partial schedules, account-wide (not windowed). |
| `mrr_cents` | integer | sum active subs amount x 43200 / interval_minutes; active_subs = live active subs. Account-wide, now. |
| `upcoming` | object | {h24, d7, d30: {schedules, entries, amount_cents}} - pending / partial schedules with run_day within the horizon (today included) and their scheduled charges / amounts. |
| `series` | array | [{label, success, failed, revenue_cents}] - label 'HH:00' (New York hour) when from = to, else 'YYYY-MM-DD'. |
| `activeSchedules` | array | [{id, name, run_day, status, total, sent, auto_dispatch_enabled}] - total = entries, sent = entries no longer pending. |
| `globalDispatchEnabled` | boolean | Account kill switch. |
| `today` | string (YYYY-MM-DD) | Today's New York day. |
| `role` | string | Caller effective role. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - from / to missing, not YYYY-MM-DD, or 'from must be <= to'.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- KPIs are by PROCESSING day (processed_at in New York), not by run_day - a charge planned yesterday but processed today counts today.
- Test-mode charges are excluded from gross / net / counts / series.
- mrr_cents, active_subs, pending_entries and upcoming ignore the window (they describe now).
- A single-day window (from = to) switches the series to hourly buckets.

##### `GET /v1/subscription/monitoring`

**Scope** `subscriptions.read` - **Subscription monitoring KPIs**

The subscription business dashboard, computed over SUBSCRIPTION charges only (the original sale is never counted): active / new / lost subs, monthly churn (lost / sub-months, split payment vs voluntary), approval, MRR (contracted) and expected MRR (x 1 - churn) with its new / lost / net new movements, revenue with refunds (partial included) and chargebacks, expected LTV / lifetime / paid charges per sub derived from monthly ARPU and churn (lifetime capped at 60 months) next to the realised figures of the ended subs, time to first charge, recovery of failed cycles, the next 7 days of charges, a daily series (trailing-30-day rates), end causes with their kind, all-time retention among the subs at risk, approval by cycle, per-product figures, top decline reasons and a block for the legacy engine's charges. `period` drives every series and every over-the-period figure; days are the caller's `tz` days.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `period` | enum: 1m\|3m\|6m\|1y\|2y\|all; default `1m` | no | Window ending today: 30 / 91 / 182 / 365 / 730 days; 'all' = since the account's first sub, capped at 731 days. |
| `tz` | string; default `the account's display timezone` | no | IANA timezone (<= 64 chars) used to cut days, e.g. 'America/New_York'. Validated with Intl - an unknown zone is a 400. v3.9.9 - absent = the account's display timezone (account_settings.timezone; was UTC). |

**Response**

```json
{
  "period": {
    "key": "1m",
    "days": 30,
    "from": "2026-08-21",
    "to": "2026-09-19",
    "tz": "America/New_York"
  },
  "active": 2380,
  "paused": 41,
  "subs": 3933,
  "ended": 1553,
  "new_today": 42,
  "lost_today": 11,
  "kpis": {
    "new_subs": 1210,
    "lost_subs": 388,
    "net_new": 822,
    "churn": {
      "lost": 388,
      "involuntary_lost": 300,
      "sub_months": 1974,
      "monthly": 0.1966,
      "involuntary_monthly": 0.152,
      "rate_period": 0.1966
    },
    "approval": {
      "success": 2034,
      "failed": 388,
      "rate": 0.8398
    },
    "mrr": {
      "raw_cents": 16657620,
      "expected_cents": 13382732,
      "retention": 0.8034,
      "new_cents": 8468790,
      "lost_cents": 2715612,
      "net_new_cents": 5753178
    },
    "revenue": {
      "cents": 14231964,
      "charges": 2034,
      "refund_cents": 209970,
      "refunds": 30,
      "chargeback_cents": 27996,
      "chargebacks": 4,
      "net_cents": 13993998
    },
    "arpu_cents": 7210,
    "avg_active": 1974,
    "ltv": {
      "value_cents": 36673,
      "lifetime_months": 5.09,
      "duration_days": 152.6,
      "realized_ended_value_cents": 9870,
      "realized_ended_duration_days": 61.2,
      "ended_n": 1553
    },
    "charges_per_sub": {
      "expected": 5.24,
      "realized_ended": 1.42
    },
    "time_to_first_charge_days": 3.1,
    "time_to_first_charge_n": 1102,
    "recovery": {
      "failed_cycles": 388,
      "recovered": 96,
      "retry_pending": 40,
      "rate": 0.2474
    },
    "upcoming": {
      "count": 640,
      "amount_cents": 4479360,
      "expected_cents": 3761760,
      "per_day": [
        {
          "day": "2026-09-19",
          "n": 96,
          "amount_cents": 671904,
          "expected_cents": 564300
        }
      ],
      "rate": 0.8398
    }
  },
  "series": [
    {
      "day": "2026-09-18",
      "new_subs": 39,
      "lost_subs": 14,
      "net_new": 25,
      "active_end": 2390,
      "churn_monthly": 0.192,
      "churn_involuntary": 0.149,
      "success": 171,
      "failed": 36,
      "approval_rate": 0.826,
      "revenue_cents": 1196829,
      "refunds": 2,
      "refund_cents": 13998,
      "chargebacks": 1,
      "chargeback_cents": 6999,
      "mrr_raw_cents": 16650602,
      "mrr_expected_cents": 13453686,
      "new_mrr_cents": 272961,
      "lost_mrr_cents": 97986,
      "net_new_mrr_cents": 174975,
      "arpu_cents": 7160,
      "ltv_value_cents": 37292,
      "ltv_duration_days": 156.2,
      "charges_per_sub": 5.3,
      "first_charges": 36,
      "time_to_first_charge_days": 3.2
    },
    {
      "day": "2026-09-19",
      "new_subs": 42,
      "lost_subs": 11,
      "net_new": 31,
      "active_end": 2421,
      "churn_monthly": 0.19,
      "churn_involuntary": 0.15,
      "success": 176,
      "failed": 34,
      "approval_rate": 0.838,
      "revenue_cents": 1231824,
      "refunds": 1,
      "refund_cents": 6999,
      "chargebacks": 0,
      "chargeback_cents": 0,
      "mrr_raw_cents": 16944560,
      "mrr_expected_cents": 13725094,
      "new_mrr_cents": 293958,
      "lost_mrr_cents": 76989,
      "net_new_mrr_cents": 216969,
      "arpu_cents": 7180,
      "ltv_value_cents": 37789,
      "ltv_duration_days": 157.9,
      "charges_per_sub": 5.4,
      "first_charges": 39,
      "time_to_first_charge_days": 3
    }
  ],
  "recovery_series": [
    {
      "day": "2026-09-19",
      "failed_cycles": 34,
      "recovered": 5,
      "retry_pending": 12
    }
  ],
  "lost_by_cause": [
    {
      "cause": "decline",
      "kind": "involuntary",
      "n": 300
    },
    {
      "cause": "user",
      "kind": "voluntary",
      "n": 60
    },
    {
      "cause": "refund",
      "kind": "voluntary",
      "n": 28
    }
  ],
  "retention": [
    {
      "cycle": 1,
      "reached": 3100,
      "decided": 3500,
      "share": 0.886,
      "step": 0.886
    },
    {
      "cycle": 2,
      "reached": 2010,
      "decided": 2900,
      "share": 0.693,
      "step": 0.75
    }
  ],
  "approval_by_cycle": [
    {
      "cycle": 1,
      "success": 1102,
      "failed": 230,
      "rate": 0.827,
      "revenue_cents": 7712898
    }
  ],
  "products": [
    {
      "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "name": "VIP Monthly",
      "amount_cents": 6999,
      "interval_minutes": 43200,
      "active": true,
      "subs": 3933,
      "active_subs": 2380,
      "mrr_raw_cents": 16657620,
      "success": 2034,
      "failed": 388,
      "approval_rate": 0.8398,
      "revenue_cents": 14231964
    }
  ],
  "decline_reasons": [
    {
      "reason": "insufficient_funds",
      "n": 210,
      "share": 0.541,
      "amount_cents": 1469790
    }
  ],
  "legacy": {
    "charges": 1200,
    "success": 800,
    "failed": 300,
    "pending": 100,
    "success_cents": 3999200,
    "converted": 120,
    "today": {
      "success": 20,
      "failed": 6,
      "pending": 10
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `period` | object | {key, days, from, to, tz} the resolved window (tz days). |
| `active` | integer | Active subs now; paused = paused now; subs = every sub the account ever had; ended = ended subs (all time); new_today / lost_today = today's flows. |
| `kpis` | object | Over-the-period figures: new_subs, lost_subs, net_new, churn {lost, involuntary_lost, sub_months (sum daily live stock / 30), monthly (lost / sub_months), involuntary_monthly, rate_period (1 - (1 - monthly)^(days / 30))}, approval {success, failed, rate}, mrr {raw_cents (sum amount x 43200 / interval_minutes of the subs active now), expected_cents (raw x retention), retention (1 - monthly churn, floored at 0, null without exposure), new_cents, lost_cents, net_new_cents}, revenue {cents, charges, refund_cents, refunds (full + partial), chargeback_cents, chargebacks, net_cents}, arpu_cents (revenue / sub_months, monthly), avg_active, ltv {value_cents (arpu x lifetime_months), lifetime_months (min(60, 1 / monthly churn)), duration_days (30 x lifetime), realized_ended_value_cents, realized_ended_duration_days, ended_n}, charges_per_sub {expected ((paid charges / sub_months) x lifetime), realized_ended}, time_to_first_charge_days / _n, recovery {failed_cycles, recovered, retry_pending, rate}, upcoming {count, amount_cents, expected_cents, rate (the approval rate used: period, else last 30 days, else 1), per_day[7]}. |
| `series` | array | One MonitoringPoint per day of the period: new_subs, lost_subs, net_new, active_end (LIVE subs = active + paused, created <= day and not ended <= day), churn_monthly and churn_involuntary (trailing 30 days: lost / sub-months), success, failed, approval_rate, revenue_cents, refunds, refund_cents, chargebacks, chargeback_cents, mrr_raw_cents (live stock), mrr_expected_cents (x 1 - churn_monthly), new_mrr_cents, lost_mrr_cents, net_new_mrr_cents, arpu_cents (trailing 30-day revenue / sub-months), ltv_value_cents, ltv_duration_days, charges_per_sub, first_charges, time_to_first_charge_days. |
| `recovery_series` | array | [{day, failed_cycles, recovered, retry_pending}] - a failed cycle = a (sub, Nth charge) with a decline that day; recovered when a later attempt of that cycle paid. |
| `lost_by_cause` | array | [{cause, kind, n}] why the subs that ended in the period ended (ended_at = coalesce(cancelled_at, updated_at)); kind = involuntary (decline / card_expired / binscrub), voluntary, or completed. |
| `retention` | array | [{cycle, reached, decided, share, step}] all-time survival among the subs AT RISK: reached = subs with >= N paid charges, decided = reached + ended before N (live subs whose Nth charge is still ahead are censored), share = reached / decided, step = reached N / (reached N + ended at cycle N - 1); N <= 60. |
| `approval_by_cycle` | array | [{cycle, success, failed, rate, revenue_cents}] attempts by rebill_number in the period. |
| `products` | array | Per product (soft-deleted included): subs, active_subs, mrr_raw_cents, success, failed, approval_rate, revenue_cents over the period. |
| `decline_reasons` | array | [{reason (normalised or lower-cased text), n, share, amount_cents}] top 10 over the GATEWAY declines only - the attempts refused before any MID (rebill_entries.blocked, v3.9 section 1) are left out (they are the Blocked figure); share = n / (kpis.approval.failed - kpis.approval.blocked). |
| `legacy` | object | The OLD engine's charges (every entry without a sub - the list's engine=legacy) over the days of the period ENDING TODAY (v3.9.9, F12; was today + 1), dated like the list (the transaction's creation, else the decision instant): charges (success + declined = the list's engine=legacy rows), success, declined (with a transaction row: at a MID or a technical error), blocked (before any MID or no transaction row), failed (declined + blocked, kept for older readers), pending (undecided entries whose slot falls in the period), success_cents, converted (customers turned into subs by a paid legacy charge), today {success, declined, failed, blocked, pending}. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - period not in the enum, or tz is not a valid IANA zone ('unknown timezone').
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Every rate (approval_rate, churn.monthly, mrr.retention, share, step...) is a RATIO 0..1 (null when there is nothing to compute it on), not a percentage; churn.monthly can exceed 1 when subs are lost faster than the exposure (retention is then 0).
- The default tz is the account's display timezone (was UTC): the days match the dashboard's other pages and /transactions.
- mrr.raw_cents is the contracted MRR (sum amount x 43200 / interval_minutes of the subs ACTIVE now, paused excluded); mrr.expected_cents = raw x (1 - churn.monthly). Only upcoming.expected_cents is scaled by an approval rate (upcoming.rate).
- 'all' is capped at 731 days of series; older activity is folded into the first day's stock.
- Expensive (11 aggregate queries over every sub / charge of the account) - cache client-side, do not poll.
- series.active_end is the LIVE stock (active + paused) - a pause is not an event - so the last point exceeds `active` by `paused`.
- Resuming a failed sub sets it back to active: its historic loss leaves every lost / churn figure (status-based predicates, no event log).

#### Products

The subscription products (plans), plan simulation, the storefront hosts and attaching a product to past sales.

- `GET /v1/subscription/subscriptions` takes no filter: the page filters and searches the full list in the browser.

##### `GET /v1/subscription/attachment-jobs`

**Scope** `subscriptions.read` - **List historical attachment jobs**

List up to 20 historical attachment jobs of this credential scope: the job with the given requestId first, then active jobs, then the newest.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Puts the job created with this idempotency id first (use it to find a job whose POST answer was lost). |

**Response**

```json
{
  "jobs": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "request_id": "22222222-2222-4222-8222-222222222222",
      "subscription_id": "33333333-3333-4333-8333-333333333333",
      "mode": "preview",
      "preview_id": null,
      "criteria": {
        "from": "2026-10-01",
        "to": "2026-10-31",
        "storefronts": []
      },
      "status": "success",
      "phase": "attach",
      "total": 6200,
      "processed": 0,
      "succeeded": 0,
      "skipped": 0,
      "failed": 0,
      "summary": {
        "candidates": 5400,
        "blacklisted": 300,
        "expired": 250,
        "refunded": 250,
        "remaining": 400,
        "depth": 5810,
        "truncated": false
      },
      "cancel_requested": false,
      "attempts": 0,
      "next_attempt_at": "2026-11-20T10:00:00.000Z",
      "error": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:40.000Z",
      "finished_at": "2026-11-20T10:00:40.000Z",
      "expires_at": "2026-11-21T10:00:00.000Z",
      "errors": [],
      "result": {
        "done": 0,
        "skipped": 0
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | Job objects, same fields as GET /v1/subscription/attachment-jobs/:id. |

**Errors**

- `400` Invalid request reference.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions). Historical attachment permissions changed. (the credential, its owner, role or grants differ from those of the job, or the key owner is a sub-account member)
- `404` Historical attachment jobs are not installed.
- `503` Authentication scope is temporarily unavailable.
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

##### `POST /v1/subscription/attachment-jobs`

**Scope** `subscriptions.write` - **Start a historical attachment preview or apply**

Attach a subscription product to PAST in-house sales that do not have it yet, in two durable steps. mode=preview stages the candidate sales of a date range (New York days) for the product's storefronts and counts blacklisted, expired and refunded ones; mode=apply attaches the product to the first 5000 eligible sales of a successful, unexpired preview. No payment is made. Answers 202 once the job is committed; poll it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `mode` | string (preview\|apply) | **yes** | preview stages candidates; apply runs a finished preview. |
| `requestId` | uuid | **yes** | Idempotency id: the same id with the same input returns the existing job; with another input or scope answers 409. |
| `subscriptionId` | uuid | no | mode=preview only (required there): the subscription product to attach. It must be active, not deleted and not in opt-in attach mode. |
| `criteria` | object | no | mode=preview only (required there). |
| `criteria.from` | string (YYYY-MM-DD) | no | First sale day (New York time), a real calendar date; required with criteria. |
| `criteria.to` | string (YYYY-MM-DD) | no | Last sale day (New York time), on or after from; required with criteria. |
| `criteria.storefronts` | array of string (max 200, each 1..200); default `[]` | no | Storefront hosts to limit the sales to; [] uses the product's own storefronts. |
| `previewId` | uuid | no | mode=apply only (required there): id of a successful, unexpired preview job of this scope that has not been applied yet. |

**Request body**

```json
{
  "mode": "preview",
  "requestId": "22222222-2222-4222-8222-222222222222",
  "subscriptionId": "33333333-3333-4333-8333-333333333333",
  "criteria": {
    "from": "2026-10-01",
    "to": "2026-10-31",
    "storefronts": []
  }
}
```

**Response** `202`

```json
{
  "jobId": "11111111-1111-4111-8111-111111111111",
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "22222222-2222-4222-8222-222222222222",
    "subscription_id": "33333333-3333-4333-8333-333333333333",
    "mode": "preview",
    "preview_id": null,
    "criteria": {
      "from": "2026-10-01",
      "to": "2026-10-31",
      "storefronts": []
    },
    "status": "queued",
    "phase": "discovery",
    "total": 0,
    "processed": 0,
    "succeeded": 0,
    "skipped": 0,
    "failed": 0,
    "summary": {},
    "cancel_requested": false,
    "attempts": 0,
    "next_attempt_at": "2026-11-20T10:00:00.000Z",
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:40.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T10:00:00.000Z",
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | Id of the job (new or the existing one for this requestId). |
| `job.id / request_id / subscription_id` | uuid | Job id, its idempotency id, and the subscription product. |
| `job.mode` | string | preview or apply. |
| `job.preview_id` | uuid \| null | For an apply: the preview it applies. |
| `job.criteria` | object | {from, to, storefronts[]} as given to the preview (copied onto the apply). |
| `job.status` | string | queued \| running \| success \| partial \| failed \| cancelled. |
| `job.phase` | string | Worker phase: discovery (preview), prepare and attach (apply). |
| `job.total / processed / succeeded / skipped / failed` | integer | Item counters: a preview stages candidates (total), an apply processes up to 5000 eligible sales. |
| `job.summary` | object | Preview counts: candidates (eligible), blacklisted, expired, refunded, remaining (eligible beyond the 5000 cap), depth (staged ordinal reached by the cap), truncated (more than 100000 sales matched). |
| `job.cancel_requested / attempts / next_attempt_at / error` | mixed | Cancellation flag, worker attempts, next worker slot, job-level error text. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps; a job expires 24 hours after creation (an expired preview can no longer be applied). |
| `job.errors` | array | Always [] here; read GET /v1/subscription/attachment-jobs/:id/errors. |
| `job.result` | object | {done: succeeded, skipped}. |

**Errors**

- `400` Invalid attachment request. (wrong mode shape, unknown key, bad uuid or date, from after to)
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions). Historical attachment permissions changed. (the credential, its owner, role or grants differ from those of the job, or the key owner is a sub-account member)
- `404` Subscription product not found.
- `409` Request ID belongs to another input or permission scope; Another historical attachment is active; This preview has expired or is incomplete; preview again; Subscription settings changed; preview again; or This preview already has an attachment operation.
- `422` Subscription product is unavailable for manual attachment. (inactive, deleted or opt-in attach mode)
- `503` Authentication scope is temporarily unavailable. Historical attachment jobs are disabled.
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

**Gotchas**

- Apply body is {"mode":"apply","requestId","previewId"}; the body is strict per mode.
- Preview stages at most 100000 sales (summary.truncated tells you more matched); apply attaches at most 5000 eligible sales (summary.remaining are left out).
- A preview expires 24 hours after creation; a product edited after the preview requires a new preview.
- One historical attachment job per account at a time.
- Each attachment is atomic per sale; cancelling keeps the attachments already made.

##### `GET /v1/subscription/attachment-jobs/:id`

**Scope** `subscriptions.read` - **Read a historical attachment job**

Read one preview or apply job: status, phase, counters, preview summary and timestamps.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "22222222-2222-4222-8222-222222222222",
    "subscription_id": "33333333-3333-4333-8333-333333333333",
    "mode": "preview",
    "preview_id": null,
    "criteria": {
      "from": "2026-10-01",
      "to": "2026-10-31",
      "storefronts": []
    },
    "status": "success",
    "phase": "attach",
    "total": 6200,
    "processed": 0,
    "succeeded": 0,
    "skipped": 0,
    "failed": 0,
    "summary": {
      "candidates": 5400,
      "blacklisted": 300,
      "expired": 250,
      "refunded": 250,
      "remaining": 400,
      "depth": 5810,
      "truncated": false
    },
    "cancel_requested": false,
    "attempts": 0,
    "next_attempt_at": "2026-11-20T10:00:00.000Z",
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:40.000Z",
    "finished_at": "2026-11-20T10:00:40.000Z",
    "expires_at": "2026-11-21T10:00:00.000Z",
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id / request_id / subscription_id` | uuid | Job id, its idempotency id, and the subscription product. |
| `job.mode` | string | preview or apply. |
| `job.preview_id` | uuid \| null | For an apply: the preview it applies. |
| `job.criteria` | object | {from, to, storefronts[]} as given to the preview (copied onto the apply). |
| `job.status` | string | queued \| running \| success \| partial \| failed \| cancelled. |
| `job.phase` | string | Worker phase: discovery (preview), prepare and attach (apply). |
| `job.total / processed / succeeded / skipped / failed` | integer | Item counters: a preview stages candidates (total), an apply processes up to 5000 eligible sales. |
| `job.summary` | object | Preview counts: candidates (eligible), blacklisted, expired, refunded, remaining (eligible beyond the 5000 cap), depth (staged ordinal reached by the cap), truncated (more than 100000 sales matched). |
| `job.cancel_requested / attempts / next_attempt_at / error` | mixed | Cancellation flag, worker attempts, next worker slot, job-level error text. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps; a job expires 24 hours after creation (an expired preview can no longer be applied). |
| `job.errors` | array | Always [] here; read GET /v1/subscription/attachment-jobs/:id/errors. |
| `job.result` | object | {done: succeeded, skipped}. |

**Errors**

- `400` Invalid operation ID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions). Historical attachment permissions changed. (the credential, its owner, role or grants differ from those of the job, or the key owner is a sub-account member)
- `404` Job not found.
- `503` Authentication scope is temporarily unavailable.
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

##### `POST /v1/subscription/attachment-jobs/:id/cancel`

**Scope** `subscriptions.write` - **Cancel a historical attachment job**

Stop the remaining work of a queued or running job. A queued job (or one whose worker lease expired) is cancelled at once; a running one stops at the next item. Attachments already made stay. On a finished job the job is returned unchanged. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "22222222-2222-4222-8222-222222222222",
    "subscription_id": "33333333-3333-4333-8333-333333333333",
    "mode": "apply",
    "preview_id": "44444444-4444-4444-8444-444444444444",
    "criteria": {
      "from": "2026-10-01",
      "to": "2026-10-31",
      "storefronts": []
    },
    "status": "cancelled",
    "phase": "attach",
    "total": 6200,
    "processed": 0,
    "succeeded": 100,
    "skipped": 0,
    "failed": 0,
    "summary": {
      "candidates": 5400,
      "blacklisted": 300,
      "expired": 250,
      "refunded": 250,
      "remaining": 400,
      "depth": 5810,
      "truncated": false
    },
    "cancel_requested": true,
    "attempts": 0,
    "next_attempt_at": "2026-11-20T10:00:00.000Z",
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:40.000Z",
    "finished_at": "2026-11-20T10:00:40.000Z",
    "expires_at": "2026-11-21T10:00:00.000Z",
    "errors": [],
    "result": {
      "done": 100,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id / request_id / subscription_id` | uuid | Job id, its idempotency id, and the subscription product. |
| `job.mode` | string | preview or apply. |
| `job.preview_id` | uuid \| null | For an apply: the preview it applies. |
| `job.criteria` | object | {from, to, storefronts[]} as given to the preview (copied onto the apply). |
| `job.status` | string | queued \| running \| success \| partial \| failed \| cancelled. |
| `job.phase` | string | Worker phase: discovery (preview), prepare and attach (apply). |
| `job.total / processed / succeeded / skipped / failed` | integer | Item counters: a preview stages candidates (total), an apply processes up to 5000 eligible sales. |
| `job.summary` | object | Preview counts: candidates (eligible), blacklisted, expired, refunded, remaining (eligible beyond the 5000 cap), depth (staged ordinal reached by the cap), truncated (more than 100000 sales matched). |
| `job.cancel_requested / attempts / next_attempt_at / error` | mixed | Cancellation flag, worker attempts, next worker slot, job-level error text. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps; a job expires 24 hours after creation (an expired preview can no longer be applied). |
| `job.errors` | array | Always [] here; read GET /v1/subscription/attachment-jobs/:id/errors. |
| `job.result` | object | {done: succeeded, skipped}. |

**Errors**

- `400` Invalid operation ID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions). Historical attachment permissions changed. (the credential, its owner, role or grants differ from those of the job, or the key owner is a sub-account member)
- `404` Job not found.
- `503` Authentication scope is temporarily unavailable.
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

##### `GET /v1/subscription/attachment-jobs/:id/errors`

**Scope** `subscriptions.read` - **Read historical attachment failures and skips**

Page through the failed and skipped sales of a job, in staged order.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (0..100000); default `0` | no | Rows to skip. |
| `limit` | integer (1..100); default `100` | no | Rows to return. |

**Response**

```json
{
  "errors": [
    {
      "itemId": "44444444-4444-4444-8444-444444444444",
      "reason": "Already subscribed on this order"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `errors[]` | object[] | {itemId (transaction id of the sale), reason}. |

**Errors**

- `400` Invalid operation ID; or Invalid error pagination.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions). Historical attachment permissions changed. (the credential, its owner, role or grants differ from those of the job, or the key owner is a sub-account member)
- `404` Job not found.
- `503` Authentication scope is temporarily unavailable.
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

##### `GET /v1/subscription/attachment-jobs/capability`

**Scope** `subscriptions.read` - **Read historical attachment capability**

Say whether historical attachment jobs can run on this deployment: background jobs enabled and the job storage installed.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | false when background jobs are disabled on this deployment. |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions).
- `503` Authentication scope is temporarily unavailable. Required storage for historical attachment jobs is unavailable. Complete the current database migrations. (background jobs enabled but tables missing; body {"error","requestId"}, Retry-After: 1)
- `504` The request took too long and was cancelled (the 10 s control budget expired); retry the same request.

##### `POST /v1/subscription/plan/preview`

**Scope** `subscriptions.read` - **Simulate a subscription plan**

The Advanced plan builder's Simulation: the engine's own maths (rebill/plan.ts simulate - the same functions that plan the charges) on a DRAFT plan: the first N charges from a sample sale instant, with their date, amount, rule and running total. Pure: nothing is read or written.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `planSteps` | array | **yes** | 0..24 intro steps [{amount_cents, after_value, after_unit, anchor, repeat?}] (snake_case, unknown keys 400). Ranges / ordering are validatePlan's: an invalid plan answers 200 {valid:false, errors}. |
| `amountCents` | integer | **yes** | The tail (recurring) amount, 1..1000000. |
| `interval` | object | **yes** | {value >= 1, unit: minutes\|hours\|days\|weeks\|months} - the tail interval (<= 49710 months / 100000 other units). |
| `maxCycles` | integer\|null; default `null` | no | Total paid charges, intro included (1..1000; null = forever). The simulation stops there. |
| `saleAt` | string (ISO datetime); default `now` | no | The sample sale instant (minute-floored). Default: now. |
| `cycles` | integer; default `12` | no | How many charges to simulate, 1..60. |
| `retries` | array | no | [{k (1..60), afterHours: [1..720, <= 10]}] - charge k declined and retried after each delay (the slots shift; the next cycles count from the paid retry). |
| `interval.value` | integer | **yes** | 1..100000 (months at most 49710: longer answers 400 "the duration is too long (at most 49710 months)"). |
| `interval.unit` | enum: minutes\|hours\|days\|weeks\|months | **yes** | Unit of the duration. |
| `planSteps[].amount_cents` | integer | no | Amount of this intro cycle in cents (validated 1..1000000 by the plan rules). |
| `planSteps[].after_value` | integer | no | Delay value before this cycle. |
| `planSteps[].after_unit` | enum: minutes\|hours\|days\|weeks\|months | no | Delay unit. |
| `planSteps[].anchor` | enum: sale\|previous | no | The delay counts from the sale or from the previous cycle. |
| `planSteps[].repeat` | integer; default `1` | no | How many times this step repeats (at most 24). |
| `retries[].k` | integer | no | Charge number that declines, 1..60 (at most 60 entries). |
| `retries[].afterHours` | integer[] | no | 1..10 retry delays in hours, each 1..720. |

**Request body**

```json
{
  "planSteps": [
    {
      "amount_cents": 1900,
      "after_value": 2,
      "after_unit": "days",
      "anchor": "sale"
    },
    {
      "amount_cents": 2900,
      "after_value": 6,
      "after_unit": "days",
      "anchor": "sale"
    }
  ],
  "amountCents": 4900,
  "interval": {
    "value": 30,
    "unit": "days"
  },
  "saleAt": "2026-09-29T14:37:00Z",
  "cycles": 3
}
```

**Response**

```json
{
  "valid": true,
  "errors": [],
  "saleAt": "2026-09-29T14:37:00.000Z",
  "timezone": "America/New_York",
  "summary": "$19.00 -> $29.00 -> $49.00 every 30 days",
  "rows": [
    {
      "k": 1,
      "at": "2026-10-01T14:37:00.000Z",
      "nominal_at": "2026-10-01T14:37:00.000Z",
      "offset_minutes": 2880,
      "amount_cents": 1900,
      "total_cents": 1900,
      "kind": "intro",
      "anchor": "sale",
      "step": 1,
      "occurrence": 1,
      "anchor_text": "after 2 days of the sale",
      "pushed": false,
      "attempts": 1,
      "processed_at": "2026-10-01T14:37:00.000Z"
    },
    {
      "k": 2,
      "at": "2026-10-05T14:37:00.000Z",
      "nominal_at": "2026-10-05T14:37:00.000Z",
      "offset_minutes": 8640,
      "amount_cents": 2900,
      "total_cents": 4800,
      "kind": "intro",
      "anchor": "sale",
      "step": 2,
      "occurrence": 1,
      "anchor_text": "after 6 days of the sale",
      "pushed": false,
      "attempts": 1,
      "processed_at": "2026-10-05T14:37:00.000Z"
    },
    {
      "k": 3,
      "at": "2026-11-04T15:37:00.000Z",
      "nominal_at": "2026-11-04T15:37:00.000Z",
      "offset_minutes": 52620,
      "amount_cents": 4900,
      "total_cents": 9700,
      "kind": "tail",
      "anchor": "tail",
      "step": null,
      "occurrence": null,
      "anchor_text": "every 30 days",
      "pushed": false,
      "attempts": 1,
      "processed_at": "2026-11-04T15:37:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `valid` | boolean | false = the plan breaks a rule; errors says which (rows is then empty). |
| `errors[]` | array | {step (the cycle number, null = the plan), field (steps\|amount_cents\|after_value\|after_unit\|anchor\|repeat\|timeline\|max_cycles), message} - messages name the cycle. |
| `saleAt` | string | The sample sale instant used. |
| `timezone` | string | America/New_York - day / week / month delays keep the sale's New York wall clock. |
| `summary` | string | The plan label ("$19.00 -> $29.00 -> $49.00 every 30 days"). |
| `rows[].k` | integer | The charge number (the steps expanded by their repeat, then the tail). |
| `rows[].at` | string | The charge instant (after retries / pushes). |
| `rows[].nominal_at` | string | The slot before the min-gap guard. |
| `rows[].offset_minutes` | integer | Minutes after the sale. |
| `rows[].amount_cents / total_cents` | integer | The charge amount and the running total. |
| `rows[].kind / anchor / step / occurrence` | string / string / integer\|null / integer\|null | intro \| tail; sale \| previous \| tail; the builder's cycle and the repeat occurrence. |
| `rows[].anchor_text` | string | "after 6 days of the sale" - "after 7 days of the previous cycle (2/3)" - "every 30 days" - "... - pushed to 24 hours after cycle 1". |
| `rows[].pushed` | boolean | The min-gap guard moved a sale-anchored charge: never closer than min(24 h, the nominal gap) after the previous paid charge. |
| `rows[].attempts` | integer | 1 + the simulated retries of that charge. |
| `rows[].processed_at` | string | When the charge is processed (= at in a preview). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a malformed body (an unknown key, a step key other than amount_cents / after_value / after_unit / anchor / repeat, amountCents out of range, cycles > 60, a duration too long).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- An invalid plan is DATA (200 {valid:false, errors}) - the builder calls this on every keystroke.
- The UI never re-implements the maths: what the simulation shows is what the engine plans (retries shift slots; a sale-anchored cycle is pushed when a retry / force bill brought the previous charge too close).

##### `GET /v1/subscription/storefronts`

**Scope** `subscriptions.read` - **List storefront hosts**

Returns the canonical storefront hosts (scheme, www./pay. prefix and path stripped, lower-cased) seen on the account's NMI card sales of the last 180 days, with their sale counts - the vocabulary for `storefronts` on products and attach calls. Top 200 by count.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "site": "shop.example.com",
      "n": 18422
    },
    {
      "site": "store.example.org",
      "n": 2310
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | [{site, n}] most frequent first. |
| `rows[].site` | string | Canonical host - use exactly this value in product / attach `storefronts`. |
| `rows[].n` | integer | Card sales in the last 180 days. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only the last 180 days: an old shop with no recent sale disappears from the list although its subs still exist.
- GET /v1/subscription/subs/facets is removed: the filter bar's store options come from GET /v1/filters/facets `storefronts` (the account's charges of the last 90 days).

##### `GET /v1/subscription/subscriptions`

**Scope** `subscriptions.read` - **List subscription products**

Returns the account's subscription products (soft-deleted ones excluded) with live counters (active / paused / failed / cancelled subs, MRR, 30-day revenue and approval), the account's retry profiles (for the product form), the engine timezone and the caller role.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "owner_email": "ops@example.com",
      "name": "VIP Monthly",
      "amount_cents": 6999,
      "first_after_days": 3,
      "interval_days": 30,
      "attach_pct": 100,
      "first_after_value": 3,
      "first_after_unit": "days",
      "interval_value": 1,
      "interval_unit": "months",
      "first_after_minutes": 4320,
      "interval_minutes": 43200,
      "max_cycles": null,
      "active": true,
      "auto_attach": true,
      "attach_on": "approved",
      "storefronts": [
        "shop.example.com"
      ],
      "atri_split": null,
      "routing_mode": "atri",
      "routing_gateway_id": null,
      "rebill_flow_id": null,
      "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
      "created_at": "2026-06-01T10:05:00.000Z",
      "updated_at": "2026-09-01T08:00:00.000Z",
      "deleted_at": null,
      "active_subs": 2380,
      "paused_subs": 41,
      "failed_subs": 610,
      "cancelled_subs": 902,
      "mrr_cents": 16657620,
      "revenue_30d_cents": 14231964,
      "success_30d": 2034,
      "failed_30d": 388
    }
  ],
  "profiles": [
    {
      "id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
      "owner_email": "ops@example.com",
      "name": "NSF +72h at $39.99",
      "scope": "insufficient",
      "amount_cents": 3999,
      "delay_hours": 72,
      "atri_split": null,
      "created_at": "2026-06-01T10:00:00.000Z",
      "updated_at": "2026-09-19T14:12:00.000Z"
    }
  ],
  "timezone": "America/New_York",
  "role": "admin",
  "routingTargets": {
    "gateways": [],
    "flows": []
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Products ordered by created_at, with stats. |
| `rows[].id` | uuid | Product id. |
| `rows[].name` | string | Unique per account. |
| `rows[].amount_cents` | integer | Price new attaches pay, in cents. |
| `rows[].first_after_value` | integer | Delay sale -> first charge, with first_after_unit (minutes\|hours\|days\|weeks\|months); first_after_minutes = the exact minutes, first_after_days = legacy rounded days. |
| `rows[].interval_value` | integer | Cycle length with interval_unit; interval_minutes exact, interval_days legacy rounded. |
| `rows[].attach_pct` | integer | Share (0-100) of matching sales that get the product (deterministic per order x product). |
| `rows[].max_cycles` | integer\|null | Sub completes after this many paid charges; null = until it fails / is cancelled. |
| `rows[].active` | boolean | Inactive: nothing attaches, nothing is planned (subs stay active with no pending charge). |
| `rows[].auto_attach` | boolean | Attach to every matching new sale of the account. |
| `rows[].attach_on` | enum: approved\|declined | Which sales the product attaches to. |
| `rows[].storefronts` | string[] | Canonical storefront hosts the product attaches to (empty = all). |
| `rows[].atri_split` | array\|null | [{id, name, pct}] or null = account default ATRI. |
| `rows[].retry_profile_id` | uuid\|null | Retry profile that shapes the dunning retry after a decline. |
| `rows[].deleted_at` | string\|null | Soft-deleted products are never returned by these routes. |
| `rows[].active_subs` | integer | Live counters: active_subs, paused_subs, failed_subs, cancelled_subs. |
| `rows[].mrr_cents` | integer | sum active subs amount x 43200 / interval_minutes (30-day month). |
| `rows[].revenue_30d_cents` | integer | Paid subscription charges of the last 30 days; success_30d / failed_30d the counts. |
| `profiles` | array | The account's retry profiles (same shape as GET /v1/subscription/profiles rows). |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `role` | string | Caller effective role. |
| `rows[].plan_mode` | string | 'simple' \| 'advanced'. |
| `rows[].plan_steps` | array\|null | The intro steps of an advanced product; null in simple. |
| `rows[].amount_mode` | string | fixed or dispatch. |
| `rows[].amount_options_cents` | array | Dispatch price points in integer cents; empty for Fixed. amount_cents mirrors the first choice for compatible product reads. |
| `rows[].routing_mode` | string | atri, gateway or rebill_flow. |
| `rows[].routing_gateway_id` | uuid\|null | The gateway of the gateway mode (kept in the other modes). |
| `rows[].rebill_flow_id` | uuid\|null | The Rebill Flow of the rebill_flow mode (kept in the other modes). |
| `routingTargets` | object | The gateways and the Rebill Flows the returned products name, by id, so a page can show names without another call. An id that is missing from both lists no longer exists. |
| `routingTargets.gateways` | array | [{ id, name, activated, archived }]. |
| `routingTargets.flows` | array | [{ id, name, published_version, archived }]. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Soft-deleted products (deleted_at set) never appear, although their subs / schedules / charges remain visible elsewhere.
- mrr_cents counts ACTIVE subs only; paused subs contribute nothing.
- Dispatch pricing assigns one of 1-50 distinct price points to each new subscription, with equal allocation probability. The product/order allocation is stable for 3DS and enrollment; the assigned customer amount is then snapshotted. Product edits and renewals do not reroll existing subscriptions. Advanced intro steps keep their explicit amounts; dispatch applies to the recurring tail.

##### `POST /v1/subscription/subscriptions`

**Scope** `subscriptions.write` - **Create a subscription product**

Creates a subscription product for the account: price, delay to the first charge, cycle interval, attach rules (auto-attach, approved/declined sales, storefronts, attach share), optional cap on cycles, ATRI split and retry profile. An active auto-attach product starts attaching to the account's NEW settled sales immediately; past sales are attached separately with POST .../:id/attach. Returns 201 with the row (no stats). v3.9.15 - the Plan: Simple (as before) or Advanced (planMode + planSteps: intro cycles, then the recurring price; the product's subs snapshot it at attach).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed 1..120 chars, unique within the account. |
| `amountCents` | integer | **yes** | 1..1000000 cents. Fixed amount; for Dispatch the server canonicalizes this legacy scalar to the first price point. Actual customer amounts are allocated separately. |
| `firstAfter` | object | **yes** | {value: int 0..100000, unit: minutes\|hours\|days\|weeks\|months} delay between the sale and the first charge. minutes/hours exact; days/weeks keep the sale's New York wall-clock; months = same day-of-month (clamped). 0 = charge in the remaining part of today. |
| `interval` | object | **yes** | {value: int >= 1 (<= 100000), unit} cycle length after each paid charge. |
| `attachPct` | integer; default `100` | no | 0..100 - share of matching sales that get the product (deterministic per order x product). |
| `maxCycles` | integer\|null; default `null` | no | 1..1000 paid charges after which a sub completes; null / omitted = unlimited. |
| `active` | boolean; default `true` | no | Inactive: attaches nothing and plans nothing. |
| `autoAttach` | boolean; default `true` | no | Attach to every matching new sale of the account. |
| `attachOn` | enum: approved\|declined; default `approved` | no | Attach to approved sales, or to declined ones (recovery products). |
| `storefronts` | string[]; default `[]` | no | Up to 200 canonical hosts (each trimmed 1..200 chars, see GET /v1/subscription/storefronts); empty = every storefront. |
| `atriSplit` | array\|null; default `null` | no | [{id: uuid, name, pct 0..100}] <= 20 - ATRI routing split for the charges; null = account default ATRI. Percentages not validated to sum to 100. |
| `retryProfileId` | uuid\|null; default `null` | no | A retry profile OF THIS ACCOUNT (else 422 Unknown retry profile). |
| `planMode` | string | no | 'simple' (one price every interval - every product before v3.9.15) or 'advanced' (planSteps = the intro cycles, then amountCents every interval). Absent on a PUT = the plan is left untouched. Sent together with planSteps (the DB CHECK: simple <=> planSteps null). |
| `planSteps` | array\|null | no | Advanced only (null / absent in simple; a simple body with steps is 422): 1..24 ordered intro steps [{amount_cents (1..1000000), after_value (>= 1; <= 49710 months / 100000 other units), after_unit (minutes\|hours\|days\|weeks\|months), anchor ('sale' \| 'previous' - step 1 is always the sale), repeat? (1..24, default 1)}] (snake_case, unknown keys 400), expanding to <= 60 charges. firstAfter is WRITTEN from step 1 whatever the body says (the mirror). Validated by rebill/plan.ts validatePlan: the nominal timeline must increase for every sale instant. |
| `attachMode` | auto \| optin; default `auto` | no | Optin = NEVER auto-attached (the auto rules, the sweep, the bulk / manual attaches all refuse it): only a checkout subscription opt-in attaches it, source optin. |
| `amountMode` | string; default `fixed` | no | fixed or dispatch. Omitted on create: fixed; omitted on update: preserve current mode. |
| `amountOptionsCents` | array | no | Dispatch: 1-50 distinct integer-cent amounts, each 1..1000000. Fixed: empty array. Send with amountMode and amountCents when editing pricing. |
| `firstAfter.value` | integer | **yes** | 0..100000 (months at most 49710: longer answers 400 "the duration is too long (at most 49710 months)"). |
| `firstAfter.unit` | enum: minutes\|hours\|days\|weeks\|months | **yes** | Unit of the duration. |
| `interval.value` | integer | **yes** | 1..100000 (months at most 49710: longer answers 400 "the duration is too long (at most 49710 months)"). |
| `interval.unit` | enum: minutes\|hours\|days\|weeks\|months | **yes** | Unit of the duration. |
| `storefronts[]` | string | no | One canonical store host, trimmed 1..200 characters (at most 200 entries). |
| `atriSplit[].id` | uuid | no | ATRI id of the account. |
| `atriSplit[].name` | string | no | ATRI name (display snapshot), up to 200 characters. |
| `atriSplit[].pct` | number | no | Share of the charges, 0..100 (at most 20 entries; the shares are not re-validated to sum 100). |
| `amountOptionsCents[]` | integer | no | One dispatch price point in cents, 1..1000000 (at most 50, distinct). |
| `planSteps[].amount_cents` | integer | no | Amount of this intro cycle in cents (validated 1..1000000 by the plan rules). |
| `planSteps[].after_value` | integer | no | Delay value before this cycle. |
| `planSteps[].after_unit` | enum: minutes\|hours\|days\|weeks\|months | no | Delay unit. |
| `planSteps[].anchor` | enum: sale\|previous | no | The delay counts from the sale or from the previous cycle. |
| `planSteps[].repeat` | integer; default `1` | no | How many times this step repeats (at most 24). |
| `routingMode` | enum: atri\|gateway\|rebill_flow | no | Where the charges of the product's subs go. atri: the ATRI split (atriSplit), else the account default ATRI. gateway: the gateway of routingGatewayId, as the only attempt. rebill_flow: the Rebill Flow of rebillFlowId decides each charge. Omitted on create: atri. Omitted on update: unchanged. |
| `routingGatewayId` | uuid\|null | no | The gateway of the gateway mode. Required (stored or sent) when the mode is gateway: it must be a gateway of the account that is switched on, can charge a card on file and is an active member of an active ATRI. Kept when the mode changes. |
| `rebillFlowId` | uuid\|null | no | The Rebill Flow of the rebill_flow mode. Required (stored or sent) when the mode is rebill_flow: it must be a flow of the account, not archived, with a published version. Kept when the mode changes. |

**Request body**

```json
{
  "name": "VIP Monthly",
  "amountCents": 4900,
  "firstAfter": {
    "value": 3,
    "unit": "days"
  },
  "interval": {
    "value": 30,
    "unit": "days"
  },
  "attachPct": 100,
  "maxCycles": null,
  "active": true,
  "autoAttach": true,
  "attachOn": "approved",
  "storefronts": [
    "shop.example.com"
  ],
  "atriSplit": null,
  "retryProfileId": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
  "planMode": "advanced",
  "planSteps": [
    {
      "amount_cents": 1900,
      "after_value": 2,
      "after_unit": "days",
      "anchor": "sale",
      "repeat": 1
    },
    {
      "amount_cents": 2900,
      "after_value": 6,
      "after_unit": "days",
      "anchor": "sale",
      "repeat": 1
    }
  ]
}
```

**Response**

```json
{
  "subscription": {
    "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "owner_email": "ops@example.com",
    "name": "VIP Monthly",
    "amount_cents": 6999,
    "first_after_days": 3,
    "interval_days": 30,
    "attach_pct": 100,
    "first_after_value": 3,
    "first_after_unit": "days",
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_minutes": 4320,
    "interval_minutes": 43200,
    "max_cycles": null,
    "active": true,
    "auto_attach": true,
    "attach_on": "approved",
    "storefronts": [
      "shop.example.com"
    ],
    "atri_split": null,
    "routing_mode": "atri",
    "routing_gateway_id": null,
    "rebill_flow_id": null,
    "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "created_at": "2026-09-19T14:20:00.000Z",
    "updated_at": "2026-09-19T14:20:00.000Z",
    "deleted_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `subscription` | object | The inserted product row (snake_case; NO stats fields here - GET the product for them). |
| `subscription.id` | uuid | Product id. |
| `subscription.name` | string | Unique per account. |
| `subscription.amount_cents` | integer | Price new attaches pay, in cents. |
| `subscription.first_after_value` | integer | Delay sale -> first charge, with first_after_unit (minutes\|hours\|days\|weeks\|months); first_after_minutes = the exact minutes, first_after_days = legacy rounded days. |
| `subscription.interval_value` | integer | Cycle length with interval_unit; interval_minutes exact, interval_days legacy rounded. |
| `subscription.attach_pct` | integer | Share (0-100) of matching sales that get the product (deterministic per order x product). |
| `subscription.max_cycles` | integer\|null | Sub completes after this many paid charges; null = until it fails / is cancelled. |
| `subscription.active` | boolean | Inactive: nothing attaches, nothing is planned (subs stay active with no pending charge). |
| `subscription.auto_attach` | boolean | Attach to every matching new sale of the account. |
| `subscription.attach_on` | enum: approved\|declined | Which sales the product attaches to. |
| `subscription.storefronts` | string[] | Canonical storefront hosts the product attaches to (empty = all). |
| `subscription.atri_split` | array\|null | [{id, name, pct}] or null = account default ATRI. |
| `subscription.retry_profile_id` | uuid\|null | Retry profile that shapes the dunning retry after a decline. |
| `subscription.deleted_at` | string\|null | Soft-deleted products are never returned by these routes. |
| `subscription.plan_mode` | string | 'simple' \| 'advanced'. |
| `subscription.plan_steps` | array\|null | The intro steps of an advanced product ([{amount_cents, after_value, after_unit, anchor, repeat}]); null in simple. |
| `subscription.amount_mode` | string | fixed or dispatch. |
| `subscription.amount_options_cents` | array | Dispatch price points in integer cents; empty for Fixed. amount_cents mirrors the first choice for compatible product reads. |
| `subscription.routing_mode` | string | atri, gateway or rebill_flow. |
| `subscription.routing_gateway_id` | uuid\|null | The gateway of the gateway mode (kept in the other modes). |
| `subscription.rebill_flow_id` | uuid\|null | The Rebill Flow of the rebill_flow mode (kept in the other modes). |
| `warnings` | string[] | Present only when the save has something to say that refuses nothing: a list of sentences. One sentence exists today, "This account has no default ATRI. A charge that cannot use its target will fail.": the body carried a routing key (routingMode, routingGatewayId or rebillFlowId), the product is now in the gateway or rebill_flow mode, and the account has no active default ATRI. The product is saved all the same. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - missing firstAfter / interval, interval.value < 1, amountCents out of 1..1000000, unknown unit, > 200 storefronts... v3.9.15 - also a duration too long for the minute columns ('the duration is too long (at most 49710 months)', was a 500) and an unknown planSteps key.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `409` {"error":"A subscription with this name already exists"} - unique (owner_email, name); a soft-deleted product still holds its name.
- `422` {"error":"Unknown retry profile"} - retryProfileId not found in this account.
- `422` v3.9.15 - {"error": <the first message>, "errors": [{step, field, message}]} - a refused plan; the messages name the cycle: 'Cycle 2 lands before cycle 1', 'Cycle 2 can land on or before cycle 1 - leave more time between them', 'Cycle 1: the delay is too long (at most 49710 months)', 'Max cycles (1) ends the plan before its intro is over (2 charges)', 'A simple plan has no intro cycles - send planSteps: null', 'An advanced plan needs at least one cycle'.
- `422` {"error":"Fixed amount cannot contain dispatch price points"}, {"error":"Dispatch requires 1 to 50 price points between $0.01 and $10,000.00"} or {"error":"Dispatch price points must be distinct"}.
- `422` Routing: {"error":"Choose a gateway for the Gateway routing."} or {"error":"Choose a Rebill Flow for the Rebill Flow routing."} when the mode has no target; {"error":"This gateway does not exist in this account."}, {"error":"This gateway is switched off. Switch it on or choose another gateway."}, {"error":"This gateway cannot charge a card on file. Choose another gateway."}, {"error":"This gateway is not in any active ATRI. Add it to an active ATRI first."}; {"error":"This Rebill Flow does not exist in this account."}, {"error":"This Rebill Flow is archived. Choose another flow."}, {"error":"This Rebill Flow has no published version. Publish it first."}. {"error":"This Rebill Flow is archived. Choose another flow."} is also the answer when the flow is archived while the save runs. Nothing is written (a product being created is not kept).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 201 on success; the response row has no stats (active_subs, mrr_cents...) unlike the list / get.
- firstAfter and interval have NO defaults - both objects are required.
- Auto-attach starts with the next settled sale; nothing is attached retroactively - call POST /v1/subscription/subscriptions/:id/attach for past sales.
- The stored first_after_days / interval_days are rounded legacy mirrors of first_after_minutes / interval_minutes - read the *_value / *_unit pairs.
- storefronts must be canonical hosts (lower-case, no scheme / www. / pay. / path); a full URL never matches.
- A soft-deleted product keeps its name reserved: recreate under another name or expect 409.
- Exify-exclusive orders (per-account Exify split) are never attached even when everything else matches.
- An advanced product's first_after_* is written from planSteps[0] (the mirror), whatever firstAfter says.
- Simulate a draft first: POST /v1/subscription/plan/preview answers the engine's own dates and amounts.
- Dispatch pricing assigns one of 1-50 distinct price points to each new subscription, with equal allocation probability. The product/order allocation is stable for 3DS and enrollment; the assigned customer amount is then snapshotted. Product edits and renewals do not reroll existing subscriptions. Advanced intro steps keep their explicit amounts; dispatch applies to the recurring tail.
- Switching to Fixed requires amountMode: fixed and an explicit amountCents; amountOptionsCents must be empty. Unrelated sparse updates preserve pricing. A legacy scalar-only update to a Dispatch product does not change its configured price points.
- Routing: a switch of routingMode applies to the next charge that is dispatched. Planned charges, schedule days and route overrides are not rewritten, and a Force bill route, a charge override or a day override still wins over the product. atriSplit is never cleared by a switch: it comes back untouched when the product returns to atri. It is stored whatever the mode, and it is read in the two other modes too: a gateway pinned by the product or by a flow is charged under an active ATRI of the split that holds it (else under the account default ATRI when it holds it, else under the oldest active ATRI that does), and the Rebill Flow action charge_product_atri draws its ATRI from it.
- Routing: the three keys are independent. Only the keys sent are written; the gateway and the flow of the modes that are not selected stay stored.
- Routing: routingGatewayId and rebillFlowId are compared and stored in lower case, whatever the case they are sent in: sending the product's own flow in upper case is not a move away from it.
- Routing: in the gateway and rebill_flow modes a charge that cannot use its target (a gateway that is full or switched off, an archived flow, a block that is unavailable with nothing after it) is sent to the account default routing. An account with no active default ATRI has no such last resort: that charge fails. A save that carries a routing key and leaves the product in one of these two modes then answers warnings; a save in the atri mode, or one that carries no routing key, never does and reads nothing for it.

##### `GET /v1/subscription/subscriptions/:id`

**Scope** `subscriptions.read` - **Get a subscription product**

Returns one product of the account with its live counters (subs by status, MRR, 30-day revenue / approval).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Product id (account-scoped, not soft-deleted). |

**Response**

```json
{
  "subscription": {
    "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "owner_email": "ops@example.com",
    "name": "VIP Monthly",
    "amount_cents": 6999,
    "first_after_days": 3,
    "interval_days": 30,
    "attach_pct": 100,
    "first_after_value": 3,
    "first_after_unit": "days",
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_minutes": 4320,
    "interval_minutes": 43200,
    "max_cycles": null,
    "active": true,
    "auto_attach": true,
    "attach_on": "approved",
    "storefronts": [
      "shop.example.com"
    ],
    "atri_split": null,
    "routing_mode": "atri",
    "routing_gateway_id": null,
    "rebill_flow_id": null,
    "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "created_at": "2026-06-01T10:05:00.000Z",
    "updated_at": "2026-09-01T08:00:00.000Z",
    "deleted_at": null,
    "active_subs": 2380,
    "paused_subs": 41,
    "failed_subs": 610,
    "cancelled_subs": 902,
    "mrr_cents": 16657620,
    "revenue_30d_cents": 14231964,
    "success_30d": 2034,
    "failed_30d": 388
  },
  "routingTargets": {
    "gateways": [],
    "flows": []
  }
}
```

| response field | type | description |
|---|---|---|
| `subscription` | object | Product row + stats. |
| `subscription.id` | uuid | Product id. |
| `subscription.name` | string | Unique per account. |
| `subscription.amount_cents` | integer | Price new attaches pay, in cents. |
| `subscription.first_after_value` | integer | Delay sale -> first charge, with first_after_unit (minutes\|hours\|days\|weeks\|months); first_after_minutes = the exact minutes, first_after_days = legacy rounded days. |
| `subscription.interval_value` | integer | Cycle length with interval_unit; interval_minutes exact, interval_days legacy rounded. |
| `subscription.attach_pct` | integer | Share (0-100) of matching sales that get the product (deterministic per order x product). |
| `subscription.max_cycles` | integer\|null | Sub completes after this many paid charges; null = until it fails / is cancelled. |
| `subscription.active` | boolean | Inactive: nothing attaches, nothing is planned (subs stay active with no pending charge). |
| `subscription.auto_attach` | boolean | Attach to every matching new sale of the account. |
| `subscription.attach_on` | enum: approved\|declined | Which sales the product attaches to. |
| `subscription.storefronts` | string[] | Canonical storefront hosts the product attaches to (empty = all). |
| `subscription.atri_split` | array\|null | [{id, name, pct}] or null = account default ATRI. |
| `subscription.retry_profile_id` | uuid\|null | Retry profile that shapes the dunning retry after a decline. |
| `subscription.deleted_at` | string\|null | Soft-deleted products are never returned by these routes. |
| `subscription.active_subs` | integer | Live counters: active_subs, paused_subs, failed_subs, cancelled_subs. |
| `subscription.mrr_cents` | integer | sum active subs amount x 43200 / interval_minutes (30-day month). |
| `subscription.revenue_30d_cents` | integer | Paid subscription charges of the last 30 days; success_30d / failed_30d the counts. |
| `subscription.amount_mode` | string | fixed or dispatch. |
| `subscription.amount_options_cents` | array | Dispatch price points in integer cents; empty for Fixed. amount_cents mirrors the first choice for compatible product reads. |
| `subscription.routing_mode` | string | atri, gateway or rebill_flow. |
| `subscription.routing_gateway_id` | uuid\|null | The gateway of the gateway mode (kept in the other modes). |
| `subscription.rebill_flow_id` | uuid\|null | The Rebill Flow of the rebill_flow mode (kept in the other modes). |
| `routingTargets` | object | The gateways and the Rebill Flows the returned products name, by id, so a page can show names without another call. An id that is missing from both lists no longer exists. |
| `routingTargets.gateways` | array | [{ id, name, activated, archived }]. |
| `routingTargets.flows` | array | [{ id, name, published_version, archived }]. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown, another account's, or soft-deleted product.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A soft-deleted product is a 404 here although its id still appears on subs (subscription_id) and schedules.
- Dispatch pricing assigns one of 1-50 distinct price points to each new subscription, with equal allocation probability. The product/order allocation is stable for 3DS and enrollment; the assigned customer amount is then snapshotted. Product edits and renewals do not reroll existing subscriptions. Advanced intro steps keep their explicit amounts; dispatch applies to the recurring tail.

##### `PUT /v1/subscription/subscriptions/:id`

**Scope** `subscriptions.write` - **Update a subscription product**

Partially updates a product (every field of the create schema is optional here). The product's pending / in-progress days are synced at once with its name, ATRI split and retry profile; interval / maxCycles apply at the next paid charge; amount, firstAfter and the attach rules only concern NEW attaches. active=false cancels and unpins the pending charges of its subs (the subs stay active, nothing is planned while inactive); active=true lets the minute sweep re-plan them. Returns the row (no stats).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Product id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | no | Trimmed 1..120, unique per account. Renames the pending days too ("<name> - <run_day>"). |
| `amountCents` | integer | no | 1..1000000 cents. Fixed amount; for Dispatch the server canonicalizes this legacy scalar to the first price point. Actual customer amounts are allocated separately. |
| `firstAfter` | object | no | {value, unit} - new sales only. |
| `interval` | object | no | {value >= 1, unit} - read at each success: the cycle after the next paid charge follows it; a charge already planned keeps its slot. |
| `attachPct` | integer | no | 0..100, new sales only. |
| `maxCycles` | integer\|null | no | 1..1000 or null (unlimited); checked at each success. |
| `active` | boolean | no | false: pending charges of the subs are cancelled (reason "subscription deactivated"); true: re-planned by the sweep. |
| `autoAttach` | boolean | no | New sales only. |
| `attachOn` | enum: approved\|declined | no | New sales only. |
| `storefronts` | string[] | no | Canonical hosts, <= 200; new sales only. |
| `atriSplit` | array\|null | no | Copied onto the pending days at once (the dispatcher reads the day's split at charge time). null = default ATRI. |
| `retryProfileId` | uuid\|null | no | Must belong to the account (422 otherwise); null clears. Read at decline time - live for the very next decline. |
| `planMode` | string | no | 'simple' (one price every interval - every product before v3.9.15) or 'advanced' (planSteps = the intro cycles, then amountCents every interval). Absent on a PUT = the plan is left untouched. Sent together with planSteps (the DB CHECK: simple <=> planSteps null). |
| `planSteps` | array\|null | no | Advanced only (null / absent in simple; a simple body with steps is 422): 1..24 ordered intro steps [{amount_cents (1..1000000), after_value (>= 1; <= 49710 months / 100000 other units), after_unit (minutes\|hours\|days\|weeks\|months), anchor ('sale' \| 'previous' - step 1 is always the sale), repeat? (1..24, default 1)}] (snake_case, unknown keys 400), expanding to <= 60 charges. firstAfter is WRITTEN from step 1 whatever the body says (the mirror). Validated by rebill/plan.ts validatePlan: the nominal timeline must increase for every sale instant. |
| `attachMode` | auto \| optin; default `auto` | no | Optin = NEVER auto-attached (the auto rules, the sweep, the bulk / manual attaches all refuse it): only a checkout subscription opt-in attaches it, source optin. |
| `amountMode` | string | no | fixed or dispatch. Omitted on create: fixed; omitted on update: preserve current mode. |
| `amountOptionsCents` | array | no | Dispatch: 1-50 distinct integer-cent amounts, each 1..1000000. Fixed: empty array. Send with amountMode and amountCents when editing pricing. |
| `firstAfter.value` | integer | no | 0..100000 (months at most 49710: longer answers 400 "the duration is too long (at most 49710 months)"). |
| `firstAfter.unit` | enum: minutes\|hours\|days\|weeks\|months | no | Unit of the duration. |
| `interval.value` | integer | no | 1..100000 (months at most 49710: longer answers 400 "the duration is too long (at most 49710 months)"). |
| `interval.unit` | enum: minutes\|hours\|days\|weeks\|months | no | Unit of the duration. |
| `storefronts[]` | string | no | One canonical store host, trimmed 1..200 characters (at most 200 entries). |
| `atriSplit[].id` | uuid | no | ATRI id of the account. |
| `atriSplit[].name` | string | no | ATRI name (display snapshot), up to 200 characters. |
| `atriSplit[].pct` | number | no | Share of the charges, 0..100 (at most 20 entries; the shares are not re-validated to sum 100). |
| `amountOptionsCents[]` | integer | no | One dispatch price point in cents, 1..1000000 (at most 50, distinct). |
| `planSteps[].amount_cents` | integer | no | Amount of this intro cycle in cents (validated 1..1000000 by the plan rules). |
| `planSteps[].after_value` | integer | no | Delay value before this cycle. |
| `planSteps[].after_unit` | enum: minutes\|hours\|days\|weeks\|months | no | Delay unit. |
| `planSteps[].anchor` | enum: sale\|previous | no | The delay counts from the sale or from the previous cycle. |
| `planSteps[].repeat` | integer; default `1` | no | How many times this step repeats (at most 24). |
| `routingMode` | enum: atri\|gateway\|rebill_flow | no | Where the charges of the product's subs go. atri: the ATRI split (atriSplit), else the account default ATRI. gateway: the gateway of routingGatewayId, as the only attempt. rebill_flow: the Rebill Flow of rebillFlowId decides each charge. Omitted on create: atri. Omitted on update: unchanged. |
| `routingGatewayId` | uuid\|null | no | The gateway of the gateway mode. Required (stored or sent) when the mode is gateway: it must be a gateway of the account that is switched on, can charge a card on file and is an active member of an active ATRI. Kept when the mode changes. |
| `rebillFlowId` | uuid\|null | no | The Rebill Flow of the rebill_flow mode. Required (stored or sent) when the mode is rebill_flow: it must be a flow of the account, not archived, with a published version. Kept when the mode changes. |
| `resumeFlowPaused` | boolean; default `true` | no | Only read when this save moves the product away from its Rebill Flow (another mode, or another flow): true resumes the subs that flow paused, false leaves them paused. |

**Request body**

```json
{
  "amountCents": 7999,
  "interval": {
    "value": 30,
    "unit": "days"
  },
  "storefronts": [
    "shop.example.com",
    "store.example.org"
  ]
}
```

**Response**

```json
{
  "subscription": {
    "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "owner_email": "ops@example.com",
    "name": "VIP Monthly",
    "amount_cents": 7999,
    "first_after_days": 3,
    "interval_days": 30,
    "attach_pct": 100,
    "first_after_value": 3,
    "first_after_unit": "days",
    "interval_value": 30,
    "interval_unit": "days",
    "first_after_minutes": 4320,
    "interval_minutes": 43200,
    "max_cycles": null,
    "active": true,
    "auto_attach": true,
    "attach_on": "approved",
    "storefronts": [
      "shop.example.com",
      "store.example.org"
    ],
    "atri_split": null,
    "routing_mode": "atri",
    "routing_gateway_id": null,
    "rebill_flow_id": null,
    "retry_profile_id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "created_at": "2026-06-01T10:05:00.000Z",
    "updated_at": "2026-09-19T14:25:00.000Z",
    "deleted_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `subscription` | object | The updated row (no stats). |
| `subscription.id` | uuid | Product id. |
| `subscription.name` | string | Unique per account. |
| `subscription.amount_cents` | integer | Price new attaches pay, in cents. |
| `subscription.first_after_value` | integer | Delay sale -> first charge, with first_after_unit (minutes\|hours\|days\|weeks\|months); first_after_minutes = the exact minutes, first_after_days = legacy rounded days. |
| `subscription.interval_value` | integer | Cycle length with interval_unit; interval_minutes exact, interval_days legacy rounded. |
| `subscription.attach_pct` | integer | Share (0-100) of matching sales that get the product (deterministic per order x product). |
| `subscription.max_cycles` | integer\|null | Sub completes after this many paid charges; null = until it fails / is cancelled. |
| `subscription.active` | boolean | Inactive: nothing attaches, nothing is planned (subs stay active with no pending charge). |
| `subscription.auto_attach` | boolean | Attach to every matching new sale of the account. |
| `subscription.attach_on` | enum: approved\|declined | Which sales the product attaches to. |
| `subscription.storefronts` | string[] | Canonical storefront hosts the product attaches to (empty = all). |
| `subscription.atri_split` | array\|null | [{id, name, pct}] or null = account default ATRI. |
| `subscription.retry_profile_id` | uuid\|null | Retry profile that shapes the dunning retry after a decline. |
| `subscription.deleted_at` | string\|null | Soft-deleted products are never returned by these routes. |
| `subscription.plan_mode` | string | 'simple' \| 'advanced'. |
| `subscription.plan_steps` | array\|null | The intro steps of an advanced product ([{amount_cents, after_value, after_unit, anchor, repeat}]); null in simple. |
| `subscription.amount_mode` | string | fixed or dispatch. |
| `subscription.amount_options_cents` | array | Dispatch price points in integer cents; empty for Fixed. amount_cents mirrors the first choice for compatible product reads. |
| `subscription.routing_mode` | string | atri, gateway or rebill_flow. |
| `subscription.routing_gateway_id` | uuid\|null | The gateway of the gateway mode (kept in the other modes). |
| `subscription.rebill_flow_id` | uuid\|null | The Rebill Flow of the rebill_flow mode (kept in the other modes). |
| `flowPaused` | object | Present only when this save moved the product away from its Rebill Flow: what happened to the subs that flow had paused. |
| `flowPaused.flowId` | uuid | The flow the product left. |
| `flowPaused.attempted` | boolean | False when resumeFlowPaused was false: nothing was resumed. |
| `flowPaused.resumed` | integer | Subs resumed (100 at most per save). The next charge of each one is planned in the same call, or by the planner (it tries again every minute) when another operation is working on its schedule day. |
| `flowPaused.refused` | integer | Subs tried and left paused; flowPaused.reasons counts them by reason (customer_has_live_sub, order_has_live_sub, not_resumable, error). |
| `flowPaused.remaining` | integer\|null | Subs still paused by that flow that this save did not try. Continue with POST /v1/subscription/flows/:id/resume-paused { subscriptionId, after: flowPaused.next }. |
| `flowPaused.next` | uuid\|null | The cursor for that call; null when nothing is left to try. |
| `warnings` | string[] | Present only when the save has something to say that refuses nothing: a list of sentences. One sentence exists today, "This account has no default ATRI. A charge that cannot use its target will fail.": the body carried a routing key (routingMode, routingGatewayId or rebillFlowId), the product is now in the gateway or rebill_flow mode, and the account has no active default ATRI. The product is saved all the same. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a field of the wrong type / range.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown / other account's / soft-deleted product (when at least one field is sent).
- `409` {"error":"A subscription with this name already exists"}.
- `422` {"error":"Unknown retry profile"}.
- `422` v3.9.15 - {"error": <the first message>, "errors": [{step, field, message}]} - a refused plan; the messages name the cycle: 'Cycle 2 lands before cycle 1', 'Cycle 2 can land on or before cycle 1 - leave more time between them', 'Cycle 1: the delay is too long (at most 49710 months)', 'Max cycles (1) ends the plan before its intro is over (2 charges)', 'A simple plan has no intro cycles - send planSteps: null', 'An advanced plan needs at least one cycle'.
- `422` v3.9.15 - {"error":"Max cycles (3) would end 12 live subs inside their intro (up to 5 charges)", errors:[{field:'max_cycles'}]} - a body carrying maxCycles / planMode / planSteps whose effective max_cycles is below the intro a live (active / paused) sub snapshotted (max_cycles is read live, the steps are not) - whatever the product's mode now.
- `422` {"error":"Fixed amount cannot contain dispatch price points"}, {"error":"Dispatch requires 1 to 50 price points between $0.01 and $10,000.00"} or {"error":"Dispatch price points must be distinct"}.
- `422` Routing: {"error":"Choose a gateway for the Gateway routing."} or {"error":"Choose a Rebill Flow for the Rebill Flow routing."} when the mode has no target; {"error":"This gateway does not exist in this account."}, {"error":"This gateway is switched off. Switch it on or choose another gateway."}, {"error":"This gateway cannot charge a card on file. Choose another gateway."}, {"error":"This gateway is not in any active ATRI. Add it to an active ATRI first."}; {"error":"This Rebill Flow does not exist in this account."}, {"error":"This Rebill Flow is archived. Choose another flow."}, {"error":"This Rebill Flow has no published version. Publish it first."}. {"error":"This Rebill Flow is archived. Choose another flow."} is also the answer when the flow is archived while the save runs. Nothing is written (a product being created is not kept).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Changing amountCents does NOT re-price existing subs or their planned charges - only new attaches. Use PATCH /v1/subscription/subs/:id, POST /subs/bulk {action:"amount"}, or a schedule amount override.
- active=false does not pause or end the subs: they stay 'active' with no pending charge; re-activation plans today's slots for those already due.
- A done day keeps its historical name / split; only pending / partial / dispatching days are synced.
- An empty body {} performs no update and returns the row as-is (this no-op path reads by id without the account filter).
- Sending `maxCycles: null` or `retryProfileId: null` clears the field; omitting them leaves them unchanged.
- A plan edit reaches NEW subs only: every live sub keeps the steps it snapshotted (like its amount); the tail interval and max_cycles stay read live.
- The plan is re-validated only when the body carries planMode / planSteps / maxCycles; a rename, {active:false}, a split, an amount or an interval edit never re-validates a stored plan. A PUT with firstAfter alone on an advanced product re-writes first_after_* from the stored step 1.
- The diff events (sub.product.edited) gain "plan mode (new subs only)" and "intro cycles (new subs only)".
- Dispatch pricing assigns one of 1-50 distinct price points to each new subscription, with equal allocation probability. The product/order allocation is stable for 3DS and enrollment; the assigned customer amount is then snapshotted. Product edits and renewals do not reroll existing subscriptions. Advanced intro steps keep their explicit amounts; dispatch applies to the recurring tail.
- Switching to Fixed requires amountMode: fixed and an explicit amountCents; amountOptionsCents must be empty. Unrelated sparse updates preserve pricing. A legacy scalar-only update to a Dispatch product does not change its configured price points.
- Routing: a switch of routingMode applies to the next charge that is dispatched. Planned charges, schedule days and route overrides are not rewritten, and a Force bill route, a charge override or a day override still wins over the product. atriSplit is never cleared by a switch: it comes back untouched when the product returns to atri. It is stored whatever the mode, and it is read in the two other modes too: a gateway pinned by the product or by a flow is charged under an active ATRI of the split that holds it (else under the account default ATRI when it holds it, else under the oldest active ATRI that does), and the Rebill Flow action charge_product_atri draws its ATRI from it.
- Routing: the three keys are independent. Only the keys sent are written; the gateway and the flow of the modes that are not selected stay stored.
- Routing: routingGatewayId and rebillFlowId are compared and stored in lower case, whatever the case they are sent in: sending the product's own flow in upper case is not a move away from it.
- Routing: in the gateway and rebill_flow modes a charge that cannot use its target (a gateway that is full or switched off, an archived flow, a block that is unavailable with nothing after it) is sent to the account default routing. An account with no active default ATRI has no such last resort: that charge fails. A save that carries a routing key and leaves the product in one of these two modes then answers warnings; a save in the atri mode, or one that carries no routing key, never does and reads nothing for it.
- Routing: moving a product away from its Rebill Flow resumes the subs that flow paused (resumeFlowPaused, default true), after the product is saved. A resumed sub is planned again and its next charge follows the new routing; an overdue one is charged soon after.
- Routing: the checks of a target run when the body carries routingMode or that mode's own key. A save that touches no routing key never looks at the stored targets.

##### `DELETE /v1/subscription/subscriptions/:id`

**Scope** `subscriptions.write` - **Delete a subscription product**

Deletes a product: its live subs (active / paused) are cancelled first (end_cause 'product_deleted', pending charges cancelled), then the product is SOFT-deleted (deleted_at, active=false, auto_attach=false, hidden from the lists) if it was ever referenced by a sub or a schedule, or hard-deleted if never used. History is never erased.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Product id (account-scoped). |

**Response**

```json
{
  "ok": true,
  "cancelledSubs": 2421
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `cancelledSubs` | integer | Live subs cancelled by the deletion. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown, other account's, or already deleted.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- IRREVERSIBLE for the customers: every active / paused sub is cancelled (cause product_deleted) and they are not re-attached automatically.
- 'failed' subs are left as they are (already terminal-ish, no pending charge).
- The name stays reserved by the soft-deleted row (409 on re-create with the same name).
- Past days, charges and the transactions stay visible under the old subscription_id.

##### `POST /v1/subscription/subscriptions/:id/attach`

**Scope** `subscriptions.write` - **Attach a product to past sales**

Bulk-attaches a product to the account's past card-on-file sales of a date range (the manual replacement of the old daily import): every sale matching the product's attach_on / storefronts / attach share that has no sub on the product yet gets a sub, and its first charge is materialised at once. Blacklisted customers, expired cards, refunded / charged-back orders and Exify-exclusive orders are skipped. dryRun=true only counts.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Product id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (YYYY-MM-DD) | **yes** | First sale day (YYYY-MM-DD, a New York day). The window is [from 00:00, to + 1 day 00:00) in America/New_York. |
| `to` | string (YYYY-MM-DD) | **yes** | Last sale day inclusive (YYYY-MM-DD, New York); must be >= from. |
| `storefronts` | string[] | no | Override of the product's storefront filter for this run (canonical hosts, <= 200). Omitted / empty = the product's own list. |
| `dryRun` | boolean; default `false` | no | true = count candidates only, attach nothing. |

**Request body**

```json
{
  "from": "2026-09-01",
  "to": "2026-09-15",
  "dryRun": true
}
```

**Response**

```json
{
  "dryRun": true,
  "candidates": 1830,
  "blacklisted": 12,
  "expired": 40,
  "refunded": 27
}
```

| response field | type | description |
|---|---|---|
| `dryRun` | boolean | Present (true) only on a dry run. |
| `candidates` | integer | Dry run: sales that WOULD get a sub. |
| `blacklisted` | integer | Dry run: skipped because the customer is blacklisted; expired = card expired; refunded = order refunded / charged back. |
| `attached` | integer | Real run: subs created (max 5000 per call). |
| `skipped` | object | Real run: {blacklisted, expired, refunded, exify, exists, share} - exify = order belongs to the Exify split (filtered in SQL, usually 0), exists = a live sub already exists / race lost, share = 0 here (attach share filtered in SQL). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - from / to not YYYY-MM-DD or 'from must be <= to'; storefronts > 200 items.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - product not in the account.
- `422` v3.9.17 - "This subscription product is opt-in only: it is attached only to sales whose customer opted into it at checkout" (attach_mode optin).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- CHARGES TODAY: a sale whose first charge (sale + first_after) is already in the past is planned in the remaining part of today's New York day - attaching a month of old sales bills them all today. Always dry-run first.
- The real run's response has no dryRun key: {attached, skipped:{...}}.
- Works on an INACTIVE product too: subs are created but no charge is planned until the product is active (then re-planned in today's window).
- The product's attach_pct applies: with attachPct 50 only the deterministic half of the matching orders is attached.
- Sales without a card on file (wallets, imports without ccnumber) and rebill charges themselves are never candidates.
- Days are New York days (both the preview and the run read the same candidate list). One call attaches at most 5 000 eligible sales; remaining tells how many eligible sales of the range are left for another call.

#### Rebill flows

The Rebill Flows: the graphs of conditions and actions that decide where each subscription charge goes. List, build, publish and test a flow, read what it decided, resume the subscriptions it paused.

- The builder checks a graph in the browser before it enables Publish. The server checks it again at publish and adds what only it can know: the gateways, the ATRIs and the products the graph names must belong to the account, and a gateway or an ATRI must not be archived.
- The Test window of the builder is `POST /v1/subscription/flows/:id/preview`: it reads, it never charges.
- The figures of the flow page come from `GET /v1/subscription/flows/:id/activity`. It answers one row per block and output; the total of a block is summed in the browser.

##### `GET /v1/subscription/flows`

**Scope** `subscriptions.read` - **List Rebill Flows**

Lists the live Rebill Flows of the account, last changed first. A Rebill Flow is a graph of conditions and actions that decides, for each charge of a subscription, where the charge goes (a gateway, an ATRI) or that it is not sent (pause, cancel, retry later, skip the cycle). A subscription product uses one through routingMode rebill_flow (PUT /v1/subscription/subscriptions/:id). Archived flows are not listed.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `q` | string | no | Search in the name (contains, without case), 200 characters at most. |
| `status` | enum: draft\|published | no | published: at least one version is published. draft: never published. |
| `limit` | integer; default `100` | no | 1 to 500. |
| `offset` | integer; default `0` | no | Rows to skip. |

**Response** `200`

```json
{
  "items": [
    {
      "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
      "name": "Winback routing",
      "draft_revision": 4,
      "published_version": 2,
      "published_at": "2026-11-27T10:15:00.000Z",
      "updated_at": "2026-11-27T10:15:00.000Z",
      "created_at": "2026-11-26T09:00:00.000Z",
      "draft_changed": false,
      "products_count": 1
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `items` | array | The page. |
| `items[].id` | string (uuid) | Rebill Flow id. |
| `items[].name` | string | Name. |
| `items[].draft_revision` | integer | Revision of the draft. |
| `items[].published_version` | integer | The version the engine runs; 0 = never published. |
| `items[].published_at` | string (ISO 8601) \| null | When that version was published. |
| `items[].draft_changed` | boolean | True while the draft is not what is published. |
| `items[].products_count` | integer | Subscription products whose charges this flow decides (routingMode rebill_flow). |
| `items[].updated_at` | string (ISO 8601) | Last change. |
| `items[].created_at` | string (ISO 8601) | Creation time. |
| `total` | integer | Rows matching q and status, whatever the page. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The list does not carry the graphs: read one flow with GET /v1/subscription/flows/:id.
- An unknown query key is refused (400): the query is strict.

##### `POST /v1/subscription/flows`

**Scope** `subscriptions.write` - **Create a Rebill Flow**

Creates a Rebill Flow with the default draft (the Entry point and one action). Nothing is published and no charge reads it until it is published and a subscription product selects it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters, unique among the live flows of the account (compared without case). |

**Request body**

```json
{
  "name": "Winback routing"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "default-routing",
          "kind": "action",
          "name": "Send to an ATRI",
          "action": {
            "type": "charge_atri",
            "atriId": null
          },
          "position": {
            "x": 400,
            "y": 80
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "default-routing"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "published_at": null,
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-27T10:15:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": true
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `400` {"error":"Enter a name of 1 to 120 characters."}: the trimmed name is empty, too long, or holds the character U+0000.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `409` {"error":"A Rebill Flow with this name already exists."}: the name is taken by a live flow of the account (compared without case). An archived flow frees its name.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Next steps: PUT /v1/subscription/flows/:id/draft to save the graph, POST /v1/subscription/flows/:id/publish to publish it, then PUT /v1/subscription/subscriptions/:id { "routingMode": "rebill_flow", "rebillFlowId": "<id>" } to route a product through it.

##### `GET /v1/subscription/flows/:id`

**Scope** `subscriptions.read` - **Get a Rebill Flow**

Returns one live Rebill Flow with its draft graph and the subscription products that route through it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Response** `200`

```json
{
  "item": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "three-ds",
          "kind": "condition",
          "name": "3DS available",
          "position": {
            "x": 400,
            "y": 80
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "three_ds_ready",
                "operator": "is",
                "value": true
              }
            ]
          }
        },
        {
          "id": "same-mid",
          "kind": "action",
          "name": "Charge on the original MID",
          "position": {
            "x": 720,
            "y": 80
          },
          "action": {
            "type": "charge_original_gateway"
          }
        },
        {
          "id": "cycle-check",
          "kind": "condition",
          "name": "Cycle above 3",
          "position": {
            "x": 720,
            "y": 320
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "cycle",
                "operator": "gt",
                "value": 3
              }
            ]
          }
        },
        {
          "id": "send-atri",
          "kind": "action",
          "name": "Send to an ATRI",
          "position": {
            "x": 1040,
            "y": 320
          },
          "action": {
            "type": "charge_atri",
            "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
          }
        },
        {
          "id": "pause",
          "kind": "action",
          "name": "Pause the subscription",
          "position": {
            "x": 1040,
            "y": 560
          },
          "action": {
            "type": "pause"
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "three-ds"
        },
        {
          "from": "three-ds",
          "output": "matched",
          "to": "same-mid"
        },
        {
          "from": "three-ds",
          "output": "unmatched",
          "to": "cycle-check"
        },
        {
          "from": "cycle-check",
          "output": "matched",
          "to": "send-atri"
        },
        {
          "from": "cycle-check",
          "output": "unmatched",
          "to": "pause"
        }
      ]
    },
    "draft_revision": 4,
    "published_version": 2,
    "published_at": "2026-11-27T10:15:00.000Z",
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-26T09:00:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": false,
    "products": [
      {
        "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
        "name": "VIP Monthly"
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |
| `item.products` | array | The subscription products in routingMode rebill_flow that select this flow, [{ id, name }] (50 at most). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The answer holds the DRAFT. The published graph is not returned by any endpoint: POST /v1/subscription/flows/:id/versions/:version/restore copies a version into the draft, POST /v1/subscription/flows/:id/preview with source published walks it.

##### `PATCH /v1/subscription/flows/:id`

**Scope** `subscriptions.write` - **Rename a Rebill Flow**

Renames a live Rebill Flow. Neither the draft nor the published version changes.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1 to 120 characters, unique among the live flows of the account. |

**Request body**

```json
{
  "name": "Winback routing v2"
}
```

**Response** `200`

```json
{
  "item": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing v2",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "three-ds",
          "kind": "condition",
          "name": "3DS available",
          "position": {
            "x": 400,
            "y": 80
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "three_ds_ready",
                "operator": "is",
                "value": true
              }
            ]
          }
        },
        {
          "id": "same-mid",
          "kind": "action",
          "name": "Charge on the original MID",
          "position": {
            "x": 720,
            "y": 80
          },
          "action": {
            "type": "charge_original_gateway"
          }
        },
        {
          "id": "cycle-check",
          "kind": "condition",
          "name": "Cycle above 3",
          "position": {
            "x": 720,
            "y": 320
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "cycle",
                "operator": "gt",
                "value": 3
              }
            ]
          }
        },
        {
          "id": "send-atri",
          "kind": "action",
          "name": "Send to an ATRI",
          "position": {
            "x": 1040,
            "y": 320
          },
          "action": {
            "type": "charge_atri",
            "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
          }
        },
        {
          "id": "pause",
          "kind": "action",
          "name": "Pause the subscription",
          "position": {
            "x": 1040,
            "y": 560
          },
          "action": {
            "type": "pause"
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "three-ds"
        },
        {
          "from": "three-ds",
          "output": "matched",
          "to": "same-mid"
        },
        {
          "from": "three-ds",
          "output": "unmatched",
          "to": "cycle-check"
        },
        {
          "from": "cycle-check",
          "output": "matched",
          "to": "send-atri"
        },
        {
          "from": "cycle-check",
          "output": "unmatched",
          "to": "pause"
        }
      ]
    },
    "draft_revision": 4,
    "published_version": 2,
    "published_at": "2026-11-27T10:15:00.000Z",
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-26T09:00:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": false,
    "products": []
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |
| `item.products` | array | The products that route through the flow, [{ id, name }]. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `400` {"error":"Enter a name of 1 to 120 characters."}: the trimmed name is empty, too long, or holds the character U+0000.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `409` {"error":"A Rebill Flow with this name already exists."}: the name is taken by a live flow of the account (compared without case). An archived flow frees its name.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

##### `DELETE /v1/subscription/flows/:id`

**Scope** `subscriptions.write` - **Archive a Rebill Flow**

Archives a Rebill Flow: it leaves the list and the pickers and frees its name. Refused while a subscription product in routingMode rebill_flow selects it. A flow is never deleted: its versions and its decision history stay.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Response** `200`

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `409` {"error":"This Rebill Flow routes 2 products: VIP Monthly, Trial. Choose another routing for them first.","products":[{"id":"<uuid>","name":"VIP Monthly"}]}: a product still routes through the flow. Nothing is archived.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- There is no way back in this version: an archived flow cannot be restored. Duplicate it first if in doubt.
- Subscriptions the flow paused stay paused: GET /v1/subscription/flows/:id/paused and POST /v1/subscription/flows/:id/resume-paused still answer for an archived flow, and so does GET /v1/subscription/flows/:id/activity.

##### `GET /v1/subscription/flows/:id/activity`

**Scope** `subscriptions.read` - **Get Rebill Flow activity**

What a Rebill Flow decided: how many evaluations went through each block and each output over the last 7 and 30 days, the same by outcome, the latest decisions one by one, and how many subscriptions the flow holds paused. One decision is recorded per evaluation, that is per charge attempt of a subscription whose product routes through the flow. Decisions are kept 90 days.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `outcome` | enum: charged\|paused\|cancelled\|postponed\|skipped\|fallback\|no_effect\|retry_planned\|ended\|continued\|profile | no | Keep the latest decisions of this outcome only. The counts are not filtered. |
| `stage` | enum: charge\|approved\|declined | no | Keep the latest decisions of this stage only: charge (the decision before the send), approved or declined (the walk after the bank answered). The counts are not filtered. |
| `subId` | string (uuid) | no | Keep the latest decisions of this sub only. |
| `entryId` | string (uuid) | no | Keep the decisions of this planned charge only. |
| `limit` | integer; default `50` | no | 1 to 200 latest decisions. |
| `offset` | integer; default `0` | no | Decisions to skip. |

**Response** `200`

```json
{
  "flow": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing",
    "published_version": 2,
    "archived": false
  },
  "totals": {
    "d7": 212,
    "d30": 840
  },
  "outcomes": [
    {
      "outcome": "charged",
      "d7": 150,
      "d30": 610
    },
    {
      "outcome": "paused",
      "d7": 58,
      "d30": 215
    },
    {
      "outcome": "cancelled",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "postponed",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "skipped",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "fallback",
      "d7": 4,
      "d30": 15
    },
    {
      "outcome": "no_effect",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "retry_planned",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "ended",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "continued",
      "d7": 0,
      "d30": 0
    },
    {
      "outcome": "profile",
      "d7": 0,
      "d30": 0
    }
  ],
  "stages": {
    "approved": {
      "totals": {
        "d7": 0,
        "d30": 0
      },
      "outcomes": [
        {
          "outcome": "charged",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "paused",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "cancelled",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "postponed",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "skipped",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "fallback",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "no_effect",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "retry_planned",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "ended",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "continued",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "profile",
          "d7": 0,
          "d30": 0
        }
      ]
    },
    "declined": {
      "totals": {
        "d7": 0,
        "d30": 0
      },
      "outcomes": [
        {
          "outcome": "charged",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "paused",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "cancelled",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "postponed",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "skipped",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "fallback",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "no_effect",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "retry_planned",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "ended",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "continued",
          "d7": 0,
          "d30": 0
        },
        {
          "outcome": "profile",
          "d7": 0,
          "d30": 0
        }
      ]
    }
  },
  "nodes": [
    {
      "nodeId": "entry-point",
      "name": "Entry point",
      "kind": "entry",
      "output": "next",
      "stage": "charge",
      "d7": 212,
      "d30": 840
    },
    {
      "nodeId": "three-ds",
      "name": "3DS available",
      "kind": "condition",
      "output": "unmatched",
      "stage": "charge",
      "d7": 190,
      "d30": 760
    }
  ],
  "latest": {
    "items": [
      {
        "id": "c7b6a5f4-e3d2-41c0-b9a8-7f6e5d4c3b2a",
        "created_at": "2026-11-27T14:02:11.000Z",
        "version_id": "8a6f2f0c-9a0e-4a43-8f43-0f3b5d8c2a10",
        "version": 2,
        "sub_id": "3f2a9b7c-1d4e-4f6a-8b0c-5e6d7f8a9b0c",
        "entry_id": "6e5d4c3b-2a19-4087-9f6e-5d4c3b2a1908",
        "order_id": "ORD-10482",
        "cycle": 4,
        "attempt": 1,
        "path": [
          {
            "nodeId": "entry-point",
            "kind": "entry",
            "output": "next"
          },
          {
            "nodeId": "three-ds",
            "kind": "condition",
            "output": "unmatched"
          },
          {
            "nodeId": "cycle-check",
            "kind": "condition",
            "output": "matched"
          },
          {
            "nodeId": "send-atri",
            "kind": "action",
            "output": null
          }
        ],
        "action": "charge_atri",
        "target_kind": "atri",
        "target_id": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b",
        "target_name": "Main Rebill",
        "outcome": "charged",
        "note": "Rebill Flow Winback routing v2: Send to ATRI Main Rebill",
        "facts": {
          "cycle": 4,
          "threeDsReady": false
        },
        "stage": "charge",
        "start_node": null,
        "changes": []
      }
    ],
    "total": 840
  },
  "paused": {
    "count": 215
  }
}
```

| response field | type | description |
|---|---|---|
| `flow` | object | { id, name, published_version, archived }. |
| `totals` | object | Evaluations over the last 7 days (d7) and 30 days (d30), of stage charge only (one charge, one count). |
| `outcomes` | array | The decisions of stage charge by outcome, always the eleven outcomes in this order: charged (the charge ran under a route action of the flow: it says where the charge was sent, not what the bank answered), paused, cancelled, postponed (retry later, or change the bill date), skipped (skip this cycle), fallback (the flow or its targets could not be used, or a target could not be read: the charge ran on the account default routing), no_effect (the action changed nothing: the sub had already stopped, or the order is pinned for verification), retry_planned (after a decline, the flow planned the next attempt), ended (end as declined, or the limit of 15 failed attempts in a cycle), continued (after an approval, the subscription goes on with what the flow saved), profile (after a decline, the retry profile plans the next attempt). |
| `stages` | object | The two other stages, each { totals, outcomes } as above: stages.approved (the walks after an approval) and stages.declined (the walks after a decline). A charge whose result was handled by its flow has a second row in one of them. |
| `nodes` | array | One row per stage, block and output taken: [{ nodeId, name, kind, output, stage, d7, d30 }], most used first. output is null for the action that decided; in stage declined, a charge block with output null is the block the next attempt starts at. name is null for a block that no longer exists in the draft nor in the versions involved. |
| `latest.items` | array | The latest decisions, newest first. |
| `latest.items[].id` | string (uuid) | Decision id. |
| `latest.items[].created_at` | string (ISO 8601) | When the flow was evaluated. |
| `latest.items[].version` | integer \| null | The version evaluated (version_id is its row id); null when the flow had none to run. |
| `latest.items[].sub_id` | string (uuid) | The sub. entry_id is the planned charge, order_id the order. |
| `latest.items[].cycle` | integer | The cycle being charged (1 = the first renewal). |
| `latest.items[].attempt` | integer \| null | The attempt inside the cycle (1 = the first try). |
| `latest.items[].path` | array | The blocks in walk order, [{ nodeId, kind, output }]. The last one whose output is null is the action that decided; unavailable marks a charge action that could not be used. |
| `latest.items[].action` | string \| null | The type of the action that decided; null when the charge fell back to the account default routing. |
| `latest.items[].target_kind` | string \| null | gateway, atri or default, with target_id and target_name, for a charge. |
| `latest.items[].outcome` | string | One of the eleven outcomes. |
| `latest.items[].stage` | string | charge, approved or declined: the decision before the send, or the walk after the bank answered (a second row for the same entry_id). |
| `latest.items[].start_node` | string \| null | The block a cursor started the walk at; null = the Entry point. |
| `latest.items[].changes` | array | The changes of the walk (a price, a frequency, a bill date, a note). A note holds its block id and its length, never its text. |
| `latest.items[].note` | string | The sentence of the decision, 300 characters at most, on every row, a charged one included: what was decided and, for a fallback, what could not be used. For example "Rebill Flow Winback routing v2: Send to ATRI Main Rebill", or "Rebill Flow unavailable: evaluation failed -> account default routing". |
| `latest.items[].facts` | object | The facts the rules read, by fact name, as the walk left them: after a block that changes the price, amountCents and amountVsPricePercent are those of the new amount of the charge, subscriptionPriceCents and priceVsProductPercent those of the new price of the next charges, and changes holds the amount before each price (fromCents). Never a card number, a security code, an e-mail or a name: ids, the BIN, the brand and the country only. |
| `latest.total` | integer | Decisions matching outcome, stage, subId and entryId, over the 90 days kept. |
| `paused.count` | integer | Subscriptions the flow paused that nobody resumed or paused again since. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id or a flow of another account. An archived flow still answers.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The counts cover every version of the flow together; a block keeps its figures across publishes as long as it keeps its id.
- A decision says where the charge was SENT, not what the bank answered: read the transaction for the verdict.
- A decision of the action charge_product_atri names the ATRI that was drawn from the product split (target_kind atri, target_id, target_name); when the product has no split it holds target_kind default, no target_id, and the outcome is charged, not fallback.
- Still answers for an archived flow.

##### `PUT /v1/subscription/flows/:id/draft`

**Scope** `subscriptions.write` - **Save a Rebill Flow draft**

Replaces the draft graph of a Rebill Flow. An incomplete graph saves: the answer lists what still prevents publishing. No charge reads a draft.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | The draft_revision the graph was loaded with. A different stored revision answers 409. |
| `graph` | object | **yes** | The whole graph: { format: 1, entry, nodes, edges }, these four keys only. At most 128 KB of JSON, 64 blocks besides the Entry point, 577 links. |
| `graph.format` | integer | **yes** | Always 1. |
| `graph.entry` | string | **yes** | Id of the Entry point block. |
| `graph.nodes` | array | **yes** | The blocks. |
| `graph.nodes[].id` | string | **yes** | Block id, unique in the graph (letters, digits, _ and -, 80 characters at most). |
| `graph.nodes[].kind` | enum: entry\|condition\|switch\|split\|action | **yes** | entry: the fixed starting block. condition: outputs matched and unmatched. switch: one output per case (case:<id>) and otherwise; the first case that matches is followed. split: one output per weighted branch. action: a charge block (outputs unavailable, approved, declined), a change block or a wait (output next, "Then"), or a block that ends the path. |
| `graph.nodes[].name` | string | **yes** | The label shown on the canvas. |
| `graph.nodes[].position` | object | **yes** | { x, y } on the canvas. |
| `graph.nodes[].condition` | object | no | A Condition block: { mode: all\|any, rules }, 1 to 16 rules. A rule on a list field is { field, operator: in\|not_in, values: [...] }; on a number or money field { field, operator: eq\|gt\|gte\|lt\|lte\|between, value, upper? } (upper only with between; money is in USD cents; sale_amount may carry currency, ISO 4217, absent = USD); on a yes or no field { field, operator: is, value: true\|false }; on a date field (date, sale_date) { field, operator: before\|after\|between, value: YYYY-MM-DD, upper? }; on sale_products { field, operator: has_any\|has_none, values: [...] }; on the two gateway fields (gateway_cap_used in whole percents, gateway_cap_room in USD cents) { field, gatewayId, operator: eq\|gt\|gte\|lt\|lte\|between, value, upper? }, at most 16 gateways in one flow. The 69 fields: cycle, attempt, amount, product, subscription_age_days, days_since_last_approved, store, sale_approved, last_result, last_decline_category, last_decline_severity, declines_in_a_row, last_attempt_gateway, postponed_in_cycle (how many times a flow answered retry_later, skip_cycle or set_bill_date for this cycle number), card_brand, card_funding, card_country, card_bin, card_issuer, card_expired, card_expires_in_months, three_ds_ready, sale_three_ds, sale_gateway, sale_gateway_usable, customer_country, customer_state, day_of_week, day_of_month, hour, subscription_price, cycle_price, amount_vs_price, product_price, price_vs_product, advanced_plan, plan_step, plan_occurrence, approved_charges, paid_total, days_since_first_due, hours_since_first_due, days_since_resumed, attach_source, forced_credential_mode, sale_amount, sale_currency, sale_age_days, sale_date, sale_items, sale_products, sale_checkout, sale_imported, sale_traffic, sale_utm_source, sale_utm_campaign, last_decline_code, failed_total, retry_step, last_credential_mode, hours_since_last_attempt, card_level, card_country_mismatch, gateway_cap_used, gateway_cap_room, email_domain, customer_other_subs, month, date. GET /v1/subscription/flows/options serves the values of the list fields: valueSets for the closed lists, gateways, products, stores, issuers and checkouts for the others. An id (a gateway, a product, a checkout) is written in lower case, as the API answers it: an id in upper or mixed case is refused at save (400, code node_shape). |
| `graph.nodes[].cases` | array | no | A Switch block: 2 to 8 cases [{ id, name?, condition }], checked in order; condition as for a Condition block. The block leaves by case:<id> of the first case that matches, else by otherwise. name is optional, 80 characters at most: without it the canvas shows the rules of the case. |
| `graph.nodes[].branches` | array | no | A Split block: 2 to 8 branches [{ id, name, weight }], weight a whole number from 1 to 10000. Weights are relative: 70 and 30, or 7 and 3, split the same way. |
| `graph.nodes[].drawAgain` | enum: never\|cycle\|attempt; default `never` | no | A Split block: when a subscription draws a new branch. never: once, the subscription keeps its branch. cycle: at every cycle. attempt: at every attempt. |
| `graph.nodes[].action` | object | no | An Action block: { type, ... }. type is one of, in the order of the catalog: charge_original_gateway (requireThreeDs optional), charge_last_approved_gateway (requireThreeDs optional), charge_last_attempt_gateway (the gateway of the previous attempt; requireThreeDs optional), charge_gateway (gatewayId; requireThreeDs optional), charge_atri (atriId, null = the account default routing), charge_product_atri (no setting: at each charge attempt an ATRI is drawn from the ATRI split of the product being charged, by its weights; the split is the atriSplit of PUT /v1/subscription/subscriptions/:id, and a product with no split uses the account default routing), set_price ({ mode: set\|lower_percent\|raise_percent\|lower_amount\|raise_amount, value, scope: this\|this_and_next\|next, floorCents? with the two lower modes, ceilingCents? with the two raise modes } or { mode: product, scope }: the price of this charge, of the next charges, or both), set_frequency ({ value, unit: days\|weeks\|months } or { reset: true }: the frequency of the next charges of this subscription), add_note (text, 300 characters at most: a note on the original sale), retry_later (hours, 1 to 720), skip_cycle, set_bill_date (date: { mode: in, value, unit: hours\|days\|weeks\|months } or { mode: day_of_month, day } or { mode: weekday, weekday: mon\|tue\|wed\|thu\|fri\|sat\|sun }, each with hour? 0 to 23 except with hours, in the account timezone), use_retry_profile (after "If declined" only: the retry profile plans the next attempt), pause, cancel, end_declined (each with reason? 120 characters at most). The six charge blocks have the outputs unavailable, approved and declined; set_price, set_frequency, add_note, retry_later and set_bill_date have next ("Then"); the others end the path. After "If approved" only conditions, switches, splits, set_price, set_frequency, set_bill_date, add_note, pause and cancel may follow. retry_later and skip_cycle change nothing a rule reads but the clock and postponed_in_cycle: put a rule on one of them before such a block, or the same path is taken at every evaluation and the subscription is never charged. gatewayId and atriId are written in lower case: an id in upper or mixed case is refused at save (400, code node_shape). |
| `graph.edges` | array | **yes** | The links between blocks. |
| `graph.edges[].from` | string | **yes** | Id of the block the link leaves. |
| `graph.edges[].output` | string | **yes** | The output it leaves by: next (the Entry point, and "Then" of a change block or a wait), matched or unmatched (condition), case:<id> or otherwise (switch), branch:<id> (split), unavailable (a charge block whose target cannot be used), approved and declined (a charge block, followed after the bank answered the charge it sent). |
| `graph.edges[].to` | string | **yes** | Id of the block it reaches. |

**Request body**

```json
{
  "baseRevision": 3,
  "graph": {
    "format": 1,
    "entry": "entry-point",
    "nodes": [
      {
        "id": "entry-point",
        "kind": "entry",
        "name": "Entry point",
        "position": {
          "x": 80,
          "y": 80
        }
      },
      {
        "id": "three-ds",
        "kind": "condition",
        "name": "3DS available",
        "position": {
          "x": 400,
          "y": 80
        },
        "condition": {
          "mode": "all",
          "rules": [
            {
              "field": "three_ds_ready",
              "operator": "is",
              "value": true
            }
          ]
        }
      },
      {
        "id": "same-mid",
        "kind": "action",
        "name": "Charge on the original MID",
        "position": {
          "x": 720,
          "y": 80
        },
        "action": {
          "type": "charge_original_gateway"
        }
      },
      {
        "id": "cycle-check",
        "kind": "condition",
        "name": "Cycle above 3",
        "position": {
          "x": 720,
          "y": 320
        },
        "condition": {
          "mode": "all",
          "rules": [
            {
              "field": "cycle",
              "operator": "gt",
              "value": 3
            }
          ]
        }
      },
      {
        "id": "send-atri",
        "kind": "action",
        "name": "Send to an ATRI",
        "position": {
          "x": 1040,
          "y": 320
        },
        "action": {
          "type": "charge_atri",
          "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
        }
      },
      {
        "id": "pause",
        "kind": "action",
        "name": "Pause the subscription",
        "position": {
          "x": 1040,
          "y": 560
        },
        "action": {
          "type": "pause"
        }
      }
    ],
    "edges": [
      {
        "from": "entry-point",
        "output": "next",
        "to": "three-ds"
      },
      {
        "from": "three-ds",
        "output": "matched",
        "to": "same-mid"
      },
      {
        "from": "three-ds",
        "output": "unmatched",
        "to": "cycle-check"
      },
      {
        "from": "cycle-check",
        "output": "matched",
        "to": "send-atri"
      },
      {
        "from": "cycle-check",
        "output": "unmatched",
        "to": "pause"
      }
    ]
  }
}
```

**Response** `200`

```json
{
  "item": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "three-ds",
          "kind": "condition",
          "name": "3DS available",
          "position": {
            "x": 400,
            "y": 80
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "three_ds_ready",
                "operator": "is",
                "value": true
              }
            ]
          }
        },
        {
          "id": "same-mid",
          "kind": "action",
          "name": "Charge on the original MID",
          "position": {
            "x": 720,
            "y": 80
          },
          "action": {
            "type": "charge_original_gateway"
          }
        },
        {
          "id": "cycle-check",
          "kind": "condition",
          "name": "Cycle above 3",
          "position": {
            "x": 720,
            "y": 320
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "cycle",
                "operator": "gt",
                "value": 3
              }
            ]
          }
        },
        {
          "id": "send-atri",
          "kind": "action",
          "name": "Send to an ATRI",
          "position": {
            "x": 1040,
            "y": 320
          },
          "action": {
            "type": "charge_atri",
            "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
          }
        },
        {
          "id": "pause",
          "kind": "action",
          "name": "Pause the subscription",
          "position": {
            "x": 1040,
            "y": 560
          },
          "action": {
            "type": "pause"
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "three-ds"
        },
        {
          "from": "three-ds",
          "output": "matched",
          "to": "same-mid"
        },
        {
          "from": "three-ds",
          "output": "unmatched",
          "to": "cycle-check"
        },
        {
          "from": "cycle-check",
          "output": "matched",
          "to": "send-atri"
        },
        {
          "from": "cycle-check",
          "output": "unmatched",
          "to": "pause"
        }
      ]
    },
    "draft_revision": 4,
    "published_version": 2,
    "published_at": "2026-11-27T10:15:00.000Z",
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-26T09:00:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": true,
    "issues": [],
    "warnings": []
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |
| `item.issues` | array | What prevents publishing this draft, [{ code, message, nodeId? }]; empty when it can be published. |
| `item.warnings` | array | Advice that refuses nothing, [{ code, message, nodeId? }]: an "If unavailable" output that can never be used, a rule that can never match (a rule on the credential mode of the last attempt in a block reached only after "If approved" or "If declined" is one: that fact is not known right after a result). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `400` {"error":"A Condition block needs 1 to 16 valid rules.","issues":[{"code","message","nodeId"}]}: the graph is malformed. error is the sentence of the first issue and issues lists them all (codes shape, node_shape, edge_shape, duplicate_node, entry, entry_incoming). Among them: a gateway, ATRI or product id written in upper or mixed case ({"error":"A Condition block needs 1 to 16 valid rules."} or {"error":"An Action block needs one valid action."}, code node_shape); a graph nested too deep to be written back as JSON (code shape); a block or branch name that holds the character U+0000 ({"error":"A block has invalid fields."}, code node_shape). {"error":"The Entry point cannot be changed or removed."}: the Entry point was removed, replaced or moved.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `409` {"error":"This draft changed in another tab. Reload before saving.","draftRevision":<current>}: baseRevision is not the stored revision.
- `413` {"error":"This flow is too large. Remove blocks or values."}: more than 128 KB of JSON.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Send the whole graph every time, the Entry point included and untouched.
- An unfinished graph saves: a Condition block whose list rule has no value yet, a "Charge on a gateway" block without a gateway, an output not connected. issues says what is left to do.
- A save never changes what the engine runs: only POST /v1/subscription/flows/:id/publish does.
- Gateways, ATRIs and products named by the graph are checked at publish, not at save.

##### `POST /v1/subscription/flows/:id/duplicate`

**Scope** `subscriptions.write` - **Duplicate a Rebill Flow**

Creates a new Rebill Flow whose draft is a copy of the DRAFT of this one. Nothing is published on the copy.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Name of the copy: trimmed, 1 to 120 characters, unique among the live flows of the account. |

**Request body**

```json
{
  "name": "Winback routing (copy)"
}
```

**Response** `201`

```json
{
  "item": {
    "id": "0f1e2d3c-4b5a-4978-8695-a4b3c2d1e0f9",
    "name": "Winback routing (copy)",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "three-ds",
          "kind": "condition",
          "name": "3DS available",
          "position": {
            "x": 400,
            "y": 80
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "three_ds_ready",
                "operator": "is",
                "value": true
              }
            ]
          }
        },
        {
          "id": "same-mid",
          "kind": "action",
          "name": "Charge on the original MID",
          "position": {
            "x": 720,
            "y": 80
          },
          "action": {
            "type": "charge_original_gateway"
          }
        },
        {
          "id": "cycle-check",
          "kind": "condition",
          "name": "Cycle above 3",
          "position": {
            "x": 720,
            "y": 320
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "cycle",
                "operator": "gt",
                "value": 3
              }
            ]
          }
        },
        {
          "id": "send-atri",
          "kind": "action",
          "name": "Send to an ATRI",
          "position": {
            "x": 1040,
            "y": 320
          },
          "action": {
            "type": "charge_atri",
            "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
          }
        },
        {
          "id": "pause",
          "kind": "action",
          "name": "Pause the subscription",
          "position": {
            "x": 1040,
            "y": 560
          },
          "action": {
            "type": "pause"
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "three-ds"
        },
        {
          "from": "three-ds",
          "output": "matched",
          "to": "same-mid"
        },
        {
          "from": "three-ds",
          "output": "unmatched",
          "to": "cycle-check"
        },
        {
          "from": "cycle-check",
          "output": "matched",
          "to": "send-atri"
        },
        {
          "from": "cycle-check",
          "output": "unmatched",
          "to": "pause"
        }
      ]
    },
    "draft_revision": 0,
    "published_version": 0,
    "published_at": null,
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-26T09:00:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": true
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `400` {"error":"Enter a name of 1 to 120 characters."}: the trimmed name is empty, too long, or holds the character U+0000.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `409` {"error":"A Rebill Flow with this name already exists."}: the name is taken by a live flow of the account (compared without case). An archived flow frees its name.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

##### `GET /v1/subscription/flows/:id/paused`

**Scope** `subscriptions.read` - **Count subscriptions paused by a Rebill Flow**

How many subscriptions this Rebill Flow paused and nobody resumed or paused again since, for the whole account or for one subscription product. The product modal reads it before a product leaves its flow.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `subscriptionId` | string (uuid) | no | Count the subs of this subscription product only. |

**Response** `200`

```json
{
  "count": 215
}
```

| response field | type | description |
|---|---|---|
| `count` | integer | Subscriptions still paused by the flow. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id or a flow of another account. An archived flow still answers.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A sub the flow paused and that an operator resumed is no longer counted, even if it was paused again by hand.
- Still answers for an archived flow.

##### `POST /v1/subscription/flows/:id/preview`

**Scope** `subscriptions.read` - **Test a Rebill Flow**

A dry run: walks a graph on facts and answers the path taken, the action that decides and the target the charge would be sent to. Nothing is written, nothing is charged, no stored 3DS proof is consumed. The graph is the published version (the default: what the engine runs), the stored draft (source draft) or the graph posted in the body. The facts are the ones posted, the real facts of one sub (subId), or both (the posted ones then replace the sub's, key by key). This is a read: a key with subscriptions.read can call it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `source` | enum: draft\|published; default `published` | no | Which stored graph to walk. Ignored when graph is sent. |
| `graph` | object | no | A graph to walk instead of a stored one (an unsaved canvas): { format: 1, entry, nodes, edges }, 128 KB at most. It must be a graph that could be published. |
| `subId` | string (uuid) | no | Read the real facts of this sub: its pending charge, or its next cycle when it has none. |
| `facts` | object | no | Facts to walk on, keyed by fact name (68): cycle, attempt, amountCents, productId, subscriptionAgeDays, daysSinceLastApproved, store, saleApproved, lastResult, lastDeclineCategory, lastDeclineSeverity, declinesInARow, lastAttemptGatewayId, postponedInCycle, cardBrand, cardFunding, cardCountry, cardBin, cardIssuer, cardExpired, cardExpiresInMonths, threeDsReady, saleThreeDs, saleGatewayId, saleGatewayUsable, customerCountry, customerState, dayOfWeek, dayOfMonth, hour, subscriptionPriceCents, cyclePriceCents, amountVsPricePercent, productPriceCents, priceVsProductPercent, advancedPlan, planStep, planOccurrence, approvedCharges, paidTotalCents, daysSinceFirstDue, hoursSinceFirstDue, daysSinceResumed, forcedCredentialMode, attachSource, saleAmountCents, saleCurrency, saleItems, saleProducts, saleDate, saleCheckoutId, saleImported, saleTraffic, saleUtmSource, saleUtmCampaign, lastDeclineCode, lastCredentialMode, failedTotal, retryStep, hoursSinceLastAttempt, cardLevel, cardCountryMismatch, emailDomain, customerOtherSubs, month, localDate, gatewayCapUsed, gatewayCapRoom. gatewayCapUsed and gatewayCapRoom are objects keyed by gateway id. A fact that is not given and not read from a sub is unknown, and a rule on an unknown fact does not match. Without subId the gateway actions read their target from these facts: "Charge on the original MID" charges saleGatewayId, and "Charge on the last approved MID" charges the same saleGatewayId unless saleApproved is false. An id (productId, saleGatewayId, lastAttemptGatewayId) is written in lower case. |
| `at` | string (ISO 8601 with offset) | no | Only with subId: the instant the real facts of the sub are read at (the time conditions dayOfWeek, dayOfMonth and hour in the account timezone, the ages, the card expiry, the month of the monthly cap behind saleGatewayUsable). Default: now. Without subId nothing is derived from it: post dayOfWeek, dayOfMonth and hour, or a rule on them reads an unknown fact and does not match. |
| `startAt` | string | no | Start the walk AT this block, as the next attempt of a cycle does at its cursor: a block reached before a charge (not the Entry point), or a charge block reached after "If declined". Letters, digits, _ and -, 80 characters at most. Absent: the Entry point. |
| `pending` | object | no | What the cycle keeps, as an earlier answer gave it in after.next.pending: { thisCents?, nextCents?, frequency?, notes?, priced? }. With startAt or alone. thisCents is then the amount of this charge for the walk: the facts of a sub are read at it, the rules on the amount and the cap test of a gateway read it, and a posted amountCents is the planned amount of the charge. |
| `result` | enum: approved\|declined | no | And then the bank answers: the walk goes on from the charge block the decision is attributed to, through its "If approved" or "If declined" output, and the answer says what the engine would do (after). |
| `resultFacts` | object | no | The verdict of that answer: { declineCategory?, declineSeverity?, declineCode?, gatewayId? }, these keys only. |
| `resultFacts.declineCategory` | string | no | The decline category (a value of valueSets.last_decline_category), 40 characters at most. |
| `resultFacts.declineSeverity` | enum: soft\|hard | no | The decline severity. |
| `resultFacts.declineCode` | string | no | The NMI response code, 3 digits. |
| `resultFacts.gatewayId` | string (uuid) | no | The gateway that took the charge. Default: the gateway the decision pinned (an ATRI target names none). |

**Request body**

```json
{
  "facts": {
    "cycle": 4,
    "attempt": 1,
    "threeDsReady": false
  }
}
```

**Response** `200`

```json
{
  "source": "published",
  "version": 2,
  "warnings": [],
  "steps": [
    {
      "nodeId": "entry-point",
      "kind": "entry",
      "output": "next"
    },
    {
      "nodeId": "three-ds",
      "kind": "condition",
      "output": "unmatched",
      "mode": "all",
      "rules": [
        {
          "field": "three_ds_ready",
          "matched": false,
          "known": true
        }
      ]
    },
    {
      "nodeId": "cycle-check",
      "kind": "condition",
      "output": "matched",
      "mode": "all",
      "rules": [
        {
          "field": "cycle",
          "matched": true,
          "known": true
        }
      ]
    },
    {
      "nodeId": "send-atri",
      "kind": "action",
      "output": null,
      "action": "charge_atri"
    }
  ],
  "action": {
    "type": "charge_atri",
    "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
  },
  "result": "route",
  "target": {
    "kind": "atri",
    "id": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b",
    "name": "Main Rebill",
    "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b",
    "atriName": "Main Rebill",
    "requireThreeDs": false
  },
  "note": "Rebill Flow Winback routing v2: Send to ATRI Main Rebill",
  "facts": {
    "cycle": 4,
    "attempt": 1,
    "threeDsReady": false,
    "cardBrand": null
  },
  "threeDsReason": "posted"
}
```

| response field | type | description |
|---|---|---|
| `source` | string | published, draft, or inline (the graph of the body). |
| `version` | integer \| null | The version walked when source is published. |
| `warnings` | array | The advice of the validator on the graph walked, [{ code, message, nodeId? }]. |
| `steps` | array | Every block crossed since the Entry point, in order: { nodeId, kind, output }. A condition step adds mode and rules [{ field, matched, known }], known false meaning the fact was unknown. A split step adds bucket, total and draw. An action step adds action (its type). output is null on the action that decides and unavailable on a charge action the walk left through "If unavailable". |
| `action` | object \| null | The action that decides, with its settings (for example { "type": "retry_later", "hours": 48 }); null when the charge would use the account default routing as the last resort. |
| `result` | string | route: a charge would be sent to target. lifecycle: no charge (pause, cancel, retry later, skip the cycle, change the bill date, end as declined). fallback: the account default routing. |
| `target` | object \| null | Where the charge would be sent: { kind: gateway\|atri\|default, id, name, atriId, atriName, requireThreeDs }; null when no charge is sent. |
| `note` | string | One sentence that says what was decided and why (a fallback names what could not be used). |
| `facts` | object | The facts the walk ran on, every one of the 68 by fact name; null = unknown (the example shows four of them). |
| `threeDsReason` | string \| null | Why 3DS is or is not available, when the graph reads it. |
| `startNode` | string | Present when startAt was sent: the block the walk started at. |
| `changes` | array | Present when the walk crossed a change block: [{ kind: price\|price_refused\|frequency\|bill_date\|note, nodeId, ... }], in walk order. price_refused says why a price was not changed (bounds, at_limit, once, force_bill, three_ds, unknown). |
| `amountCents` | integer | Present when the flow gives this charge another amount than the planned one (a price block of this walk, or the price the cycle keeps in pending.thisCents): the amount the charge would be sent at. |
| `plannedAmountCents` | integer | With amountCents: the planned amount of this charge, before any price of the flow. It is the posted amountCents, else the amount of the pending charge of the sub (of its next cycle when it has none); with neither, the two keys are absent. |
| `nextAt` | string (ISO 8601) | Present when the flow postponed the charge before sending it (retry_later, set_bill_date): the new date. |
| `after` | object \| null | Present only when result was sent. null when the walk decided no charge, or when the output of that answer is not connected (afterNote says who then decides). One exception: with result approved and nothing connected to "If approved", after is still an object when the cycle keeps changes an approval saves (a price of the next charges, a frequency, a note): steps [], end { kind: end }, plan.kind continue, and a note that ends "-> the changes kept for this cycle were saved". |
| `after.steps` | array | The walk after the answer: the charge block with output approved or declined, then the blocks crossed. |
| `after.changes` | array | The changes of that walk, as changes above. |
| `after.end` | object | { kind: resume, nodeId } (a retry that starts at a charge block), { kind: action, nodeId, action } (the block that ended the walk), or { kind: end }. |
| `after.plan` | object | What the engine would do: { kind: retry\|bill_date\|retry_later\|skip\|profile\|pause\|cancel\|end_declined\|continue, at, resumeAt, nextPrice, frequency }. at is the instant of the next attempt or of the next charge (null when it is not known: a retry the profile plans, a skip or an approval without subId and frequency); resumeAt the block the next attempt starts at; nextPrice and frequency what the cycle keeps for the next charges. With resultFacts.declineCode, a retry date is never earlier than the bank's own wait of that code (an NMI 264 asks 72 hours). |
| `after.next` | object \| null | What the next attempt of the cycle starts with: { startAt, pending, facts }, facts holding only what differs at that attempt (the attempt, the previous attempt, the clock at plan.at). The price the cycle keeps is in pending.thisCents, never in facts: an amountCents posted with the first call stays the planned amount. Post it back (startAt, pending, facts) to test that attempt. null when the cycle ends. |
| `after.capReached` | boolean | True when this decline is the 15th failed attempt of the cycle or more: the subscription then ends as declined before the flow is asked. |
| `after.note` | string | One sentence: "Rebill Flow <name> v<version>: If declined -> <blocks>". |
| `afterNote` | string | Present when the output of the answer is not connected: "Nothing is connected to "If declined": the retry profile decides." or "Nothing is connected to "If approved": the subscription goes on as usual." |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `400` {"error":"A block has invalid fields.","issues":[...]}: the posted graph is malformed (error is the first issue), as for PUT /v1/subscription/flows/:id/draft: an id in upper or mixed case, a graph nested too deep, a name that holds U+0000.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `404` {"error":"Subscription not found"}: subId is not a sub of the account.
- `409` {"error":"This flow has no published version yet."}: the published version was asked of a flow that was never published. Send source draft or a graph.
- `413` {"error":"This flow is too large. Remove blocks or values."}: a posted graph over 128 KB of JSON.
- `422` {"error":"Fix the flow before testing it.","issues":[...],"warnings":[...]}: the graph could not be published as it is (an unfinished draft); the issues say what is left. {"error":"These facts cannot be read: cardBrand.","invalidFacts":["cardBrand"]}: a posted key that is not a fact, or a value of the wrong type or spelling (Visa, not visa), or an id in upper or mixed case. {"error":"This flow could not be evaluated.","reason":"..."}: the walk failed; reason is "lookup failed" when a gateway or an ATRI the walk reached could not be read (the database did not answer). A charge in that case is sent to the account default routing, never through "If unavailable". {"error":"This block cannot start a walk."}: startAt is not a block that can start a walk. {"error":"The pending changes are not valid."}: pending is not what a cycle can keep.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The answer is never cached (cache-control: no-store): the facts of a sub change with every charge.
- A real charge can differ from a dry run made earlier: the facts are read again at charge time, and a target that was usable can stop being so.
- A walk that ends on charge_product_atri draws an ATRI from the ATRI split of the product the facts name: the product of the sub (subId), or the posted productId. The draw is random, as at a charge: two dry runs can name two ATRIs of one split. target is then { kind: atri } with the ATRI drawn. With no product, or a product with no split, target.kind is default (the account default routing) and result is still route.
- The test after an answer assumes a decline the flow is asked about: a final decline, a technical error or a charge refused before any gateway never reach "If declined" at a real charge.
- With subId, a cycle that already has 15 failed attempts is not walked: the engine ends the subscription as declined before any block, and the dry run answers that ending. result is lifecycle, action { "type": "end_declined" }, steps [], note "Rebill Flow <name> v<version>: attempt limit reached (15 failed attempts in this cycle)", and after is null when result was sent.
- With subId, a pending charge that must use its stored 3DS proof keeps its amount, as at charge time: pending.thisCents is not applied to it, and a price block for this charge answers price_refused with the reason three_ds.

##### `POST /v1/subscription/flows/:id/publish`

**Scope** `subscriptions.write` - **Publish a Rebill Flow**

Publishes the draft as the next version. The engine reads the published version at each charge: the very next charge of every product that routes through the flow is decided by the new version, a charge already being processed keeps what it was sent with.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | The draft_revision to publish. A different stored revision answers 409. |
| `note` | string | no | A note kept with the version, 500 characters at most. A note that holds the character U+0000 answers 400 {"error":"Invalid request"}, whose details say "The note holds a character that cannot be stored." |

**Request body**

```json
{
  "baseRevision": 4,
  "note": "Pause below cycle 4 when 3DS is not available"
}
```

**Response** `200`

```json
{
  "version": 3,
  "unchanged": false,
  "warnings": []
}
```

| response field | type | description |
|---|---|---|
| `version` | integer | The version now published. |
| `unchanged` | boolean | True when the draft was already what is published: no version was added. |
| `warnings` | array | Things that do not refuse the publication, [{ code, message, nodeId? }]: inactive_target (a gateway or an ATRI that exists but cannot take a charge right now), default_atri_missing (the account has no active default ATRI: given for ANY flow, with the nodeId of each block that uses the account default routing, else once for the flow, without nodeId), and the advice of the draft save (unused_output, never_matches, can_repeat, and since round two bill_date_every_cycle, next_charge_soon, change_dropped, price_drops_3ds, price_before_cap_test, price_repeats, decline_never_seen, end_without_decline). A never_matches message words the gateway of a rule as "a gateway": the check reads no name. A rule on the credential mode of the last attempt, in a block reached only after "If approved" or "If declined", gets never_matches too: that fact is not known right after a result. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `409` {"error":"This draft changed. Reload before publishing.","draftRevision":<current>}: baseRevision is not the stored revision.
- `422` {"error":"Fix the flow before publishing.","issues":[{"code","message","nodeId"}],"warnings":[...]}: the graph is not finished (codes missing_node, duplicate_output, invalid_output, missing_output, no_action, cycle, incomplete_rule, incomplete_action, orphan, and since round two after_approved: a block that cannot follow "If approved" (only conditions, "Change the price", "Change the frequency", "Change the bill date", "Add a note", Pause and Cancel can); price_after_approved: "Change the price" with a scope that holds this charge, after "If approved"; profile_only_after_declined: "Use the retry profile" reached before a charge; too_many_gateways: a flow reads the monthly cap of at most 16 gateways). The message of missing_output names a Switch case that has no name by its position ("case 2") when its rules name a gateway, an ATRI, a product or a checkout. {"error":"The block \"Charge on Acme\" uses the archived gateway Acme 3. Restore it or choose another gateway.","issues":[...],"warnings":[...]}: a block names a gateway, an ATRI or a product that is not the account's, or charges an archived gateway or ATRI; error is the first issue, issues holds them all (codes unknown_target, archived_target, unknown_condition_value), each with the id of its block.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Nothing is pinned on a subscription, a planned charge or a schedule day: a publish applies from the next charge that is dispatched.
- A target that exists but is switched off does not refuse the publication (warning inactive_target): at charge time the block is unavailable and the charge follows its "If unavailable" output, else the account default routing.
- Versions are never rewritten nor deleted. To go back, restore a version into the draft and publish again.
- The account default routing is the last resort of every flow: a block whose target cannot be used and that has nothing connected to "If unavailable", or a flow that cannot be evaluated, sends the charge there. On an account with no active default ATRI that charge fails, so every publication answers the warning default_atri_missing: {"code":"default_atri_missing","message":"This account has no default ATRI. A charge that cannot use its target will fail."}, or one entry per block that uses the account default routing ({"code":"default_atri_missing","nodeId":"<block>","message":"The block \"<name>\" uses the account default routing, and this account has no active default ATRI."}). GET /v1/subscription/flows/options answers account.defaultAtriId, null in that case.

##### `POST /v1/subscription/flows/:id/resume-paused`

**Scope** `subscriptions.write` - **Resume subscriptions paused by a Rebill Flow**

Resumes the subscriptions this Rebill Flow paused, 100 per call by default, through the same resume as POST /v1/subscription/subs/:id/resume: each sub is planned again at its next slot when that slot is still ahead, else now, and its next charge is decided by whatever its product routes through at that moment (the same flow can pause it again). Call it again with after = the next of the answer until next is null.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `subscriptionId` | string (uuid) | no | Resume the subs of this subscription product only. |
| `after` | string (uuid) | no | The cursor: the next of the previous answer. Subs up to it are not tried again. |
| `limit` | integer; default `100` | no | 1 to 200 subs for this call. |

**Request body**

```json
{
  "limit": 100
}
```

**Response** `200`

```json
{
  "resumed": 97,
  "refused": 3,
  "reasons": {
    "customer_has_live_sub": 2,
    "not_resumable": 1
  },
  "remaining": 115,
  "next": "3f2a9b7c-1d4e-4f6a-8b0c-5e6d7f8a9b0c"
}
```

| response field | type | description |
|---|---|---|
| `resumed` | integer | Subs resumed by this call. The next charge of each one is planned in the same call, or by the planner (it tries again every minute) when another operation is working on its schedule day. |
| `refused` | integer | Subs this call tried and left paused. |
| `reasons` | object | The refusals by reason: customer_has_live_sub (the customer already holds another live subscription), order_has_live_sub, not_resumable (no longer paused, or one of its charges awaits a processor confirmation), error. |
| `remaining` | integer \| null | Subs still paused by the flow that this call did not try. |
| `next` | string (uuid) \| null | Send it as after to continue; null when nothing is left to try. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id or a flow of another account. An archived flow still answers.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A refused sub stays paused. A call without after tries the refused ones again.
- An overdue sub is charged soon after it is resumed.
- Moving a subscription product away from its flow resumes its paused subs by itself (PUT /v1/subscription/subscriptions/:id, resumeFlowPaused).
- Still answers for an archived flow.

##### `GET /v1/subscription/flows/:id/versions`

**Scope** `subscriptions.read` - **List Rebill Flow versions**

Lists the published versions of a live Rebill Flow, newest first, and which one the engine runs.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |

**Response** `200`

```json
{
  "versions": [
    {
      "id": "8a6f2f0c-9a0e-4a43-8f43-0f3b5d8c2a10",
      "version": 2,
      "created_at": "2026-11-27T10:15:00.000Z",
      "created_by": "ops@example.com",
      "note": "Pause below cycle 4 when 3DS is not available"
    }
  ],
  "publishedVersion": 2
}
```

| response field | type | description |
|---|---|---|
| `versions` | array | Newest first. |
| `versions[].id` | string (uuid) | Id of the version row: the id a decision names. |
| `versions[].version` | integer | Version number, from 1. |
| `versions[].created_at` | string (ISO 8601) | When it was published. |
| `versions[].created_by` | string \| null | Who published it. |
| `versions[].note` | string \| null | The note given at publish. |
| `publishedVersion` | integer | The version the engine runs; 0 = none. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The graph of a version is not returned: restore it into the draft to read it.

##### `POST /v1/subscription/flows/:id/versions/:version/restore`

**Scope** `subscriptions.write` - **Restore a Rebill Flow version as the draft**

Copies a published version into the draft. The published version does not change: publish the draft to run it again.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Rebill Flow id. A value that is not a uuid answers 400 {"error":"Invalid request"}. |
| `version` | integer | **yes** | Version number to copy, from 1. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `baseRevision` | integer | **yes** | The current draft_revision. A different stored revision answers 409. |

**Request body**

```json
{
  "baseRevision": 4
}
```

**Response** `200`

```json
{
  "item": {
    "id": "5d0a8a2e-3a41-4a55-9d0f-6f0c3a7b1e21",
    "name": "Winback routing",
    "draft_graph": {
      "format": 1,
      "entry": "entry-point",
      "nodes": [
        {
          "id": "entry-point",
          "kind": "entry",
          "name": "Entry point",
          "position": {
            "x": 80,
            "y": 80
          }
        },
        {
          "id": "three-ds",
          "kind": "condition",
          "name": "3DS available",
          "position": {
            "x": 400,
            "y": 80
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "three_ds_ready",
                "operator": "is",
                "value": true
              }
            ]
          }
        },
        {
          "id": "same-mid",
          "kind": "action",
          "name": "Charge on the original MID",
          "position": {
            "x": 720,
            "y": 80
          },
          "action": {
            "type": "charge_original_gateway"
          }
        },
        {
          "id": "cycle-check",
          "kind": "condition",
          "name": "Cycle above 3",
          "position": {
            "x": 720,
            "y": 320
          },
          "condition": {
            "mode": "all",
            "rules": [
              {
                "field": "cycle",
                "operator": "gt",
                "value": 3
              }
            ]
          }
        },
        {
          "id": "send-atri",
          "kind": "action",
          "name": "Send to an ATRI",
          "position": {
            "x": 1040,
            "y": 320
          },
          "action": {
            "type": "charge_atri",
            "atriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
          }
        },
        {
          "id": "pause",
          "kind": "action",
          "name": "Pause the subscription",
          "position": {
            "x": 1040,
            "y": 560
          },
          "action": {
            "type": "pause"
          }
        }
      ],
      "edges": [
        {
          "from": "entry-point",
          "output": "next",
          "to": "three-ds"
        },
        {
          "from": "three-ds",
          "output": "matched",
          "to": "same-mid"
        },
        {
          "from": "three-ds",
          "output": "unmatched",
          "to": "cycle-check"
        },
        {
          "from": "cycle-check",
          "output": "matched",
          "to": "send-atri"
        },
        {
          "from": "cycle-check",
          "output": "unmatched",
          "to": "pause"
        }
      ]
    },
    "draft_revision": 5,
    "published_version": 2,
    "published_at": "2026-11-27T10:15:00.000Z",
    "archived_at": null,
    "created_by": "ops@example.com",
    "updated_by": "ops@example.com",
    "created_at": "2026-11-26T09:00:00.000Z",
    "updated_at": "2026-11-27T10:15:00.000Z",
    "draft_changed": true
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The flow. |
| `item.id` | string (uuid) | Rebill Flow id. |
| `item.name` | string | Name, unique among the live flows of the account. |
| `item.draft_graph` | object | The draft the builder edits: { format: 1, entry, nodes, edges }. |
| `item.draft_revision` | integer | Revision of the draft. Send it back as baseRevision; every accepted save or restore adds 1. |
| `item.published_version` | integer | The version the engine runs; 0 = never published. |
| `item.published_at` | string (ISO 8601) \| null | When that version was published. |
| `item.draft_changed` | boolean | True while the draft is not what is published (never published, or saved since). |
| `item.archived_at` | null | Always null here: an archived flow is not returned. |
| `item.created_by` | string \| null | Who created the flow. |
| `item.updated_by` | string \| null | Who changed it last. |
| `item.created_at` | string (ISO 8601) | Creation time. |
| `item.updated_at` | string (ISO 8601) | Last change. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a path id that is not a uuid, a key of the wrong type or range, or an unknown key (bodies and queries are strict).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Admin role required"}: a dashboard session of role user. An API key acts with the admin role.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}: unknown id, a flow of another account, or an archived flow.
- `404` {"error":"Version not found"}: the flow has no such version.
- `409` {"error":"The draft changed. Reload before restoring a version.","draftRevision":<current>}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The draft that was there is replaced.

##### `GET /v1/subscription/flows/options`

**Scope** `subscriptions.read` - **Get Rebill Flow options**

Everything the Rebill Flow builder offers in its pickers, in one answer: the gateways and the ATRIs with the reason one cannot take a card-on-file charge right now, the subscription products, the store hosts, the card issuers the account sees most, the closed value lists of the condition fields, and the account facts a flow depends on.

*No parameters.*

**Response** `200`

```json
{
  "stores": [
    {
      "id": "shop.example.com",
      "name": "shop.example.com"
    }
  ],
  "products": [
    {
      "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "name": "VIP Monthly"
    }
  ],
  "gateways": [
    {
      "id": "9c1f2b6e-7a41-4b0d-8f3a-2d5e6c7b8a90",
      "name": "Acme Processing MID 1",
      "gatewayType": "nmi",
      "activated": true,
      "archived": false,
      "disabledReason": null
    }
  ],
  "atris": [
    {
      "id": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b",
      "name": "Main Rebill",
      "isDefault": true,
      "active": true,
      "archived": false,
      "tripType": "classic",
      "disabledReason": null
    }
  ],
  "issuers": [
    {
      "id": "JPMORGAN CHASE",
      "name": "JPMorgan Chase"
    }
  ],
  "checkouts": [
    {
      "id": "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f",
      "name": "Summer checkout"
    }
  ],
  "valueSets": {
    "last_decline_severity": [
      {
        "id": "soft",
        "name": "Soft"
      },
      {
        "id": "hard",
        "name": "Hard"
      }
    ]
  },
  "account": {
    "timezone": "America/New_York",
    "retryEnabled": true,
    "defaultAtriId": "2b7e1c55-6d0a-4f0e-9a3b-7c8d9e0f1a2b"
  }
}
```

| response field | type | description |
|---|---|---|
| `gateways` | array | Every gateway of the account, archived ones included (a block must still be able to name a gateway the pickers no longer offer). |
| `gateways[].id` | string (uuid) | Gateway id. |
| `gateways[].name` | string | Gateway name. |
| `gateways[].gatewayType` | string | Gateway type. |
| `gateways[].activated` | boolean | Switched on. |
| `gateways[].archived` | boolean | Archived. |
| `gateways[].disabledReason` | string \| null | null: a charge can be pinned to it. Else why not: "Archived", "Switched off", "Cannot charge a card on file", "Not in any active ATRI". |
| `atris` | array | Every ATRI of the account, the default first, archived ones included. |
| `atris[].id` | string (uuid) | ATRI id. |
| `atris[].name` | string | ATRI name. |
| `atris[].isDefault` | boolean | The account default ATRI. |
| `atris[].active` | boolean | Switched on. |
| `atris[].archived` | boolean | Archived. |
| `atris[].tripType` | string | classic or cascade. |
| `atris[].disabledReason` | string \| null | null: a charge can be sent to it. Else why not: "Archived", "Switched off", "No active gateway that can charge a card on file". |
| `products` | array | The subscription products of the account, [{ id, name }]: the values of the condition on the product. |
| `stores` | array | The store hosts seen on the card sales of the last 180 days, [{ id, name }] (both are the host): the values of the condition on the store. |
| `issuers` | array | The card issuers of the account's own sales, most orders first, 200 at most, [{ id, name }]: id is the issuer key a rule on card_issuer stores, name its display name. |
| `valueSets` | object | The closed lists of the condition fields, [{ id, name }] by field key: last_result, last_decline_category, last_decline_severity, card_brand, card_funding, day_of_week, attach_source, forced_credential_mode, last_credential_mode, month. id is the value a rule stores, name its label. |
| `checkouts` | array | The checkouts of the account, by name, 500 at most, [{ id, name }]: the values of the condition on sale_checkout. A failed read answers an empty list. A checkout a rule names is not checked at publish: a deleted checkout still names the sales it made. |
| `account.timezone` | string | The account timezone: the time conditions (day of week, day of month, hour) are read in it. |
| `account.retryEnabled` | boolean | The Retry setting of the account. When false no retry is ever planned, so a condition on the attempt number or on the previous decline never matches a second attempt. |
| `account.defaultAtriId` | string (uuid) \| null | The active default ATRI, what "the account default routing" means; null when the account has none. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A gateway or an ATRI with a disabledReason can still be named by a flow: at charge time the block is then unavailable and the charge follows its "If unavailable" output, else the account default routing.
- issuers holds the issuers the account sees most. Find another one with GET /v1/bin-catalog?kind=issuer&q=<text> (scope routing.read): rows[].value is the key to store.
- Countries (card_country, customer_country) are ISO 3166-1 alpha-2 codes; card_bin takes 6 digits; customer_state is written US-CA.

#### Subscribers

The subscribers (subs): list, one sub, edit, pause, resume, cancel, force bill, bulk edits.

- The Total row of the page is summed in the browser.

##### `GET /v1/subscription/bulk-jobs`

**Scope** `subscriptions.read` - **List subscription bulk-edit jobs (subs and schedule charges)**

Lists subscription bulk-edit jobs (bulk edits of subscriptions or of a schedule's charges sent with async: true); schedule billing jobs (Force bill / Sample) are read with GET /v1/subscription/jobs/:jobId and schedule bulk jobs with GET /v1/subscription/schedules/bulk-jobs. List up to 20 subscription bulk-edit jobs of the account: running or queued jobs first (whatever their schedule), then the most recent ones for the requested schedule (or, without scheduleId, for subscription selections). Jobs are created by POST /v1/subscription/subs/bulk or POST /v1/subscription/schedules/:id/entries/bulk with async: true. Finished jobs are kept 30 days.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `scheduleId` | uuid | no | Schedule whose job history to list; omitted lists the jobs on subscription selections (schedule_id null). Active jobs are always included. |

**Response**

```json
{
  "jobs": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "request_id": "22222222-2222-4222-8222-222222222222",
      "schedule_id": null,
      "status": "running",
      "total": 15000,
      "processed": 100,
      "succeeded": 98,
      "failed": 1,
      "skipped": 1,
      "cancel_requested": false,
      "error": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:05.000Z",
      "finished_at": null,
      "errors": [],
      "result": {
        "done": 98,
        "skipped": 1
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | Job rows: id, request_id, schedule_id, status, total, processed, succeeded, failed, skipped, cancel_requested, error, created_at, updated_at, finished_at, errors ([] here), result {done, skipped}. |

**Errors**

- `400` Invalid schedule.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Work runs in the background and survives the caller leaving; poll GET /v1/subscription/bulk-jobs/:jobId.
- One bulk job (subscription, customer or transaction bulk) runs per account at a time.

##### `GET /v1/subscription/bulk-jobs/:jobId`

**Scope** `subscriptions.read` - **Read a subscription bulk-edit job**

Reads one subscription bulk-edit job; schedule billing jobs are read with GET /v1/subscription/jobs/:jobId. Read one bulk-edit job: status, counters, cancellation flag, timestamps and its first 20 failed or skipped items.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Bulk edit job id (jobId returned at creation). |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "22222222-2222-4222-8222-222222222222",
    "request_hash": "9b1f0c3e8a",
    "schedule_id": null,
    "status": "running",
    "total": 15000,
    "processed": 100,
    "succeeded": 98,
    "failed": 1,
    "skipped": 1,
    "cancel_requested": false,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:05.000Z",
    "finished_at": null,
    "errors": [
      {
        "itemId": "33333333-3333-4333-8333-333333333333",
        "reason": "Subscription is cancelled"
      }
    ],
    "result": {
      "done": 98,
      "skipped": 1
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | Idempotency id given (or generated) at creation. |
| `job.request_hash` | string | Fingerprint of the selection and actions, used to refuse a reused request id with different input. |
| `job.schedule_id` | uuid \| null | Schedule whose charges were edited; null for a selection of subscriptions. |
| `job.status` | string | queued \| running \| success \| partial \| failed \| cancelled. |
| `job.total` | integer | Items to process (one per subscription, or per charge without a subscription). |
| `job.processed / succeeded / failed / skipped` | integer | Progress counters. |
| `job.cancel_requested` | boolean | A cancel was requested; work stops between atomic items. |
| `job.error` | string \| null | Job-level failure text. |
| `job.created_at / updated_at / finished_at` | string (ISO 8601) \| null | Timestamps; finished_at null until the job ends. |
| `job.errors[]` | object[] | First 20 failed or skipped items {itemId, reason} (always [] in the list). |
| `job.result` | object | {done: succeeded, skipped}. |

**Errors**

- `400` Invalid job.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- errors holds at most 20 items; page the rest with GET /v1/subscription/bulk-jobs/:jobId/errors.

##### `POST /v1/subscription/bulk-jobs/:jobId/cancel`

**Scope** `subscriptions.write` - **Cancel a subscription bulk-edit job**

Cancels a subscription bulk-edit job; a schedule billing job is cancelled with POST /v1/subscription/jobs/:jobId/cancel. Request cancellation of a queued or running bulk-edit job; work stops between atomic items and changes already committed stay saved. On a finished job nothing changes and the job is returned as is. Safe to repeat. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Bulk edit job id. |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "22222222-2222-4222-8222-222222222222",
    "request_hash": "9b1f0c3e8a",
    "schedule_id": null,
    "status": "running",
    "total": 15000,
    "processed": 100,
    "succeeded": 98,
    "failed": 1,
    "skipped": 1,
    "cancel_requested": true,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:05.000Z",
    "finished_at": null,
    "errors": [
      {
        "itemId": "33333333-3333-4333-8333-333333333333",
        "reason": "Subscription is cancelled"
      }
    ],
    "result": {
      "done": 98,
      "skipped": 1
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Job id. |
| `job.request_id` | uuid | Idempotency id given (or generated) at creation. |
| `job.request_hash` | string | Fingerprint of the selection and actions, used to refuse a reused request id with different input. |
| `job.schedule_id` | uuid \| null | Schedule whose charges were edited; null for a selection of subscriptions. |
| `job.status` | string | queued \| running \| success \| partial \| failed \| cancelled. |
| `job.total` | integer | Items to process (one per subscription, or per charge without a subscription). |
| `job.processed / succeeded / failed / skipped` | integer | Progress counters. |
| `job.cancel_requested` | boolean | A cancel was requested; work stops between atomic items. |
| `job.error` | string \| null | Job-level failure text. |
| `job.created_at / updated_at / finished_at` | string (ISO 8601) \| null | Timestamps; finished_at null until the job ends. |
| `job.errors[]` | object[] | First 20 failed or skipped items {itemId, reason} (always [] in the list). |
| `job.result` | object | {done: succeeded, skipped}. |

**Errors**

- `400` Invalid job.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- status turns cancelled only when the worker reaches the next item; poll the job.

##### `GET /v1/subscription/bulk-jobs/:jobId/errors`

**Scope** `subscriptions.read` - **Read a subscription bulk-edit job's failures**

Pages through the failed and skipped items of a subscription bulk-edit job. Page through the failed and skipped items of a bulk-edit job, in item order.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Bulk edit job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer (1..500); default `100` | no | Rows to return. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |

**Response**

```json
{
  "errors": [
    {
      "itemId": "33333333-3333-4333-8333-333333333333",
      "reason": "Subscription is cancelled"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `errors[]` | object[] | {itemId (subscription id, or charge id for a charge without subscription), reason}. |

**Errors**

- `400` Invalid request. (jobId not a uuid, or limit/offset out of range)
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module subscriptions).
- `404` Not found.
- `503` Authentication scope is temporarily unavailable.

##### `GET /v1/subscription/subs`

**Scope** `subscriptions.read` - **List subs (customer subscriptions)**

Pages through the account's customer subscriptions (subs) with their product, original sale, pinned charge and last paid charge. v3.9.15 - filtered by THE unified catalog (the same keys as /transactions and every report), strictly; `summary` counts the LISTED subs whenever a key (or the range) narrows the list. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `sort` | enum: next_charge_at\|created_at\|amount\|cycle\|status\|email\|customer\|subscription\|last_charge_at\|sale_at\|sale_amount\|product; default `next_charge_at` | no | Sort key (the Subs table's column keys). Absent -> next_charge_at. An UNKNOWN key is a 400 {"error":"Invalid sort","allowed":[...]} listing the accepted keys - no silent fallback any more (a direction passed as the key, `sort=asc`, used to return the default order twice). Ties on created_at desc; nulls last. |
| `dir` | enum: asc\|desc; default `asc` | no | Direction. |
| `limit` | integer; default `25` | no | 1..10000. |
| `offset` | integer; default `0` | no | >= 0. |
| `from` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): Start of the page range (inclusive): the grain's own date. A bare day is read in tz. |
| `to` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): End of the page range (inclusive). A bare day is read in tz. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "owner_email": "ops@example.com",
      "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
      "email": "jane@example.com",
      "amount_cents": 6999,
      "status": "active",
      "cycle": 2,
      "retry_step": 0,
      "next_charge_at": "2026-10-19T15:07:00.000Z",
      "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
      "last_charge_at": "2026-09-19T15:07:05.210Z",
      "last_status": "rebill_success",
      "last_decline_reason": null,
      "source": "auto",
      "attached_by": "sale",
      "cancel_reason": null,
      "cancelled_at": null,
      "end_cause": null,
      "created_at": "2026-08-19T15:07:44.000Z",
      "updated_at": "2026-09-19T15:07:05.400Z",
      "flow_paused_at": null,
      "flow_paused_by": null,
      "subscription_name": "VIP Monthly",
      "product_atri_split": [
        {
          "id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
          "name": "Main Rebill",
          "pct": 100
        }
      ],
      "product_routing": {
        "mode": "atri",
        "gateway_id": null,
        "flow_id": null
      },
      "interval_days": 30,
      "first_after_days": 3,
      "interval_value": 1,
      "interval_unit": "months",
      "first_after_value": 3,
      "first_after_unit": "days",
      "first_name": "Jane",
      "last_name": "Doe",
      "masked_card": "411111******1111",
      "storefront_url": "https://shop.example.com/checkout",
      "country": "US",
      "sale_at": "2026-08-19T15:07:44.000Z",
      "sale_amount_cents": 4999,
      "sale_mid": "MID US 01",
      "card_brand": "VISA",
      "entry_status": "scheduled",
      "entry_scheduled_at": "2026-10-19T15:07:00.000Z",
      "entry_amount_cents": 6999,
      "product_slug": "vip-bundle",
      "product_name": "VIP Bundle",
      "last_charge_amount_cents": 6999,
      "total": 2380
    }
  ],
  "total": 2380,
  "summary": {
    "active": 2380,
    "paused": 41,
    "failed": 610,
    "cancelled": 902,
    "due_24h": 96,
    "mrr_cents": 16657620
  },
  "today": "2026-09-19"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The page of SubDetailRow (snake_case). |
| `rows[].id` | uuid | Sub id. |
| `rows[].subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `rows[].product_atri_split` | array\|null | The product's ATRI split [{id, name, pct}]: the route a Force bill's "Use original" takes (null = the account's default ATRI). |
| `rows[].order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `rows[].email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `rows[].amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `rows[].status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `rows[].cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `rows[].next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `rows[].current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `rows[].last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `rows[].source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `rows[].end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `rows[].sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `rows[].product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `rows[].created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |
| `rows[].total` | integer | Copy of the total on each row. |
| `total` | integer | Subs matching the filters. |
| `summary` | object | Status counts (active, paused, failed, cancelled), due_24h (active subs charging in the next 24 h) and mrr_cents (active subs' amount normalised to 30 days) - v3.9.15: of the LISTED subs when the filters narrow the list, else the whole account. |
| `today` | string (YYYY-MM-DD) | Today's New York day. |
| `rows[].product_routing` | object | The routing of the sub's product: { mode: atri\|gateway\|rebill_flow, gateway_id, flow_id }. What "Use original" means for a Force bill. |
| `rows[].flow_paused_at` | string\|null | When a Rebill Flow last paused this sub. The sub is paused by that flow while status is paused and paused_at equals this instant. |
| `rows[].flow_paused_by` | uuid\|null | The Rebill Flow that did. |
| `rows[].interval_override_value` | integer\|null | The frequency of this sub, set by a Rebill Flow ("Change the frequency", saved by an approved charge), with interval_override_unit (days, weeks or months); null = the product's frequency. Kept after the product leaves the flow; PATCH /v1/subscription/subs/:id { resetFrequency: true } clears it. |
| `rows[].interval_override_unit` | string\|null | days, weeks or months; null with interval_override_value. |
| `rows[].flow_cursor` | object\|null | Where the next attempt of the current cycle starts in the flow, and what the cycle keeps: { v, flowId, versionId, nodeId, cycle, pending?, thisFrom?, nextFrom?, at }. thisFrom and nextFrom are the amounts the two kept prices of pending belong to (the planned amount of the charge, the price of the sub): a kept price is used only while that amount is still in force, so an amount you set meanwhile is charged and stays. Read only while its flow is the product's and its cycle the charge's. |
| `rows[].flow_skipped_cycle` | integer\|null | The charge number (rebill_number, one more than cycle) of the last "Skip this cycle" a Rebill Flow decided after a declined charge (its "If declined" output), with flow_skipped_at; null when it never did. The attempts of that charge number made up to flow_skipped_at belong to the skipped period: the charge of the next billing date is a first try again. |
| `rows[].flow_skipped_at` | string (ISO-8601)\|null | The instant the declined charge of that skip was created; null with flow_skipped_cycle. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key (a legacy name included), an unknown value of a closed vocabulary (subStatus, attachedBy, due, entryStatus...), a non-uuid id, a bad date, hour without tz, a reversed pair, limit out of 1..10 000.
- `400` {"error":"Invalid sort","allowed":[...]} - `sort` is not one of the allowed keys (the body lists them). Absent `sort` is fine (default order).
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- BREAKING: the legacy params are 400s (strict): status -> subStatus, source ("Attached by") -> attachedBy, subscriptionId -> subscription, createdFrom/To -> subCreatedFrom/To, endedFrom/To -> subEndedFrom/To (both bounds now INCLUSIVE), dueFrom/dueTo -> due (overdue | 24h | 7d), email -> customerEmail (exact), orderId / search -> q; `status` / `source` now mean the CHARGE status / source (through the charge link).
- The card / customer keys read the sub's CHARGES (its sale  union  its entries' transactions): a wallet sale now matches brand=Apple Pay; brand / cardType take the catalog words (Visa, Mastercard...), not the old bin_info UPPER case; storefront is the catalog's host bucket.
- cycleMin / cycleMax are the charge's cycle number through the link (0 = the straight sale): the old "paid N cycles" (x.cycle >= N) is cycleMin=N&status=approved.
- summary (active / paused / failed / cancelled / due_24h / mrr_cents) follows the filters whenever they narrow the list (the range included); with none it is the account's snapshot, as before.
- Default sort next_charge_at ASC puts the soonest charges first and terminal subs (null) last. An unknown `sort` is a 400 that lists the allowed keys.
- GET /v1/subscription/subs/facets is removed - the options come from GET /v1/filters/facets.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `POST /v1/subscription/subs`

**Scope** `subscriptions.write` - **Attach a product to one sale (manual sub)**

Creates a sub by hand for one card-on-file sale of the account: the product's amount (or a custom one) and a first charge at the sale instant + the product's first delay (or a given instant; a past instant lands in today's remaining window). The first charge is materialised at once in the product's day. Refuses blacklisted customers and refunded / charged-back orders; one live sub per product x order. v3.9.17 - an opt-in product (attach_mode optin) attaches here too: one order is the operator's explicit decision (source manual); the mass attaches refuse it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `subscriptionId` | uuid | **yes** | Product of the account (404 Unknown subscription otherwise). |
| `transactionId` | uuid | **yes** | The SALE transaction id (transactions.id) - an NMI card sale with a card on file, not a rebill charge, owned by the account. NOT the order id. |
| `amountCents` | integer; default `(product amount)` | no | > 0. Price of this sub; defaults to the product's amount. |
| `nextChargeAt` | ISO-8601; default `(sale + first_after)` | no | First charge instant with a timezone offset ('Z' or +/-hh:mm required). Default: sale time + product first_after; a past instant is placed in today's remaining New York day. |

**Request body**

```json
{
  "subscriptionId": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
  "transactionId": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
  "nextChargeAt": "2026-09-22T15:00:00Z"
}
```

**Response**

```json
{
  "sub": {
    "id": "4f506172-8c9d-4eaf-b012-3c4d5e6f7081",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "active",
    "cycle": 0,
    "retry_step": 0,
    "next_charge_at": "2026-09-22T15:00:00.000Z",
    "current_entry_id": "1a2b3c4d-5e6f-4708-9a0b-1c2d3e4f5061",
    "last_charge_at": null,
    "last_status": null,
    "last_decline_reason": null,
    "source": "manual",
    "attached_by": "ops@example.com",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-09-19T14:30:00.000Z",
    "updated_at": "2026-09-19T14:30:00.000Z",
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-09-22T15:00:00.000Z",
    "entry_amount_cents": 6999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": null,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `sub` | object | The new sub as SubDetailRow (with product / sale / pinned charge joins). |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |
| `multiAllowed` | boolean | v3.9.2 section 3 - the sub was allowed as a second live sub of the customer (the flag is now on). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - non-uuid ids, amountCents <= 0, nextChargeAt without offset / not ISO-8601.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Unknown subscription"} - product not in the account.
- `404` {"error":"Sale not found for this account (subscriptions need a card-on-file sale)"} - not an NMI card sale with ccnumber, a rebill charge, or another account's sale.
- `409` {"error":"This order already has a live sub on this subscription"} - an active / paused sub exists (rebill_subs_live_uq).
- `422` {"error":"This customer is blacklisted"}.
- `422` {"error":"This order was refunded or charged back"}.
- `422` {"error":"The card on file is expired"} or {"error":"This order belongs to Exify"}: the attach skipped the sale.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 201 on success.
- transactionId is the transaction (sale) uuid, not the order id - look it up first (e.g. GET /v1/subscription/customer?orderId=...).
- No card-expiry check and no attach_on / storefront / attach share check here - a declined sale or an out-of-scope storefront can be attached by hand.
- nextChargeAt in the past (or omitted for an old sale) means a charge TODAY in the remaining New York window.
- On an inactive product the sub is created but no charge is planned until the product is active.
- A previously cancelled / failed sub on the same product does not block a new one (only active / paused conflict) - the new sub starts at cycle 0.
- v3.9.2 section 3: goes through attachSubToSale (docs/SUBSCRIPTIONS.md section 2.4 R2.4.4): a customer who already holds a live sub gets the Law (a) flag set implicitly (multi_allowed on the sub and the customer flag row - the response says `multiAllowed: true`); an expired card is 422, an Exify order 422; amountCents / nextChargeAt re-plan the entry once attached and log sub.edited.

##### `GET /v1/subscription/subs/:id`

**Scope** `subscriptions.read` - **Get a sub**

Returns one sub (SubDetailRow with product / sale / pinned charge joins) and its full charge history (every rebill_entries row of the sub, newest slot first).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped). |

**Response**

```json
{
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "active",
    "cycle": 2,
    "retry_step": 0,
    "next_charge_at": "2026-10-19T15:07:00.000Z",
    "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
    "last_charge_at": "2026-09-19T15:07:05.210Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-19T15:07:05.400Z",
    "flow_paused_at": null,
    "flow_paused_by": null,
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-10-19T15:07:00.000Z",
    "entry_amount_cents": 6999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1,
    "product_routing": {
      "mode": "atri",
      "gateway_id": null,
      "flow_id": null
    }
  },
  "entries": [
    {
      "id": "0f1e2d3c-4b5a-4968-8776-655443322110",
      "schedule_id": "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
      "scheduled_at": "2026-10-19T15:07:00.000Z",
      "amount_cents": 6999,
      "status": "scheduled",
      "decline_reason": null,
      "mid_name": null,
      "transaction_id": null,
      "processed_at": null,
      "rebill_number": 3,
      "rebill_type": "recurring"
    },
    {
      "id": "9b7e6d5c-1111-4f22-a333-444455556666",
      "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "scheduled_at": "2026-09-19T15:07:00.000Z",
      "amount_cents": 6999,
      "status": "rebill_success",
      "decline_reason": null,
      "mid_name": "MID US 02",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "processed_at": "2026-09-19T15:07:05.210Z",
      "rebill_number": 2,
      "rebill_type": "recurring"
    }
  ],
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `sub` | object | SubDetailRow. |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.product_atri_split` | array\|null | The product's ATRI split [{id, name, pct}]: the route a Force bill's "Use original" takes (null = the account's default ATRI). |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |
| `entries` | array | [{id, schedule_id, scheduled_at, amount_cents, status, decline_reason, mid_name, transaction_id, processed_at, rebill_number, rebill_type}] every charge of the sub incl. cancelled / re-planned ones, newest slot first. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `sub.product_routing` | object | The routing of the sub's product: { mode: atri\|gateway\|rebill_flow, gateway_id, flow_id }. What "Use original" means for a Force bill. |
| `sub.flow_paused_at` | string\|null | When a Rebill Flow last paused this sub. The sub is paused by that flow while status is paused and paused_at equals this instant. |
| `sub.flow_paused_by` | uuid\|null | The Rebill Flow that did. |
| `sub.interval_override_value` | integer\|null | The frequency of this sub, set by a Rebill Flow ("Change the frequency", saved by an approved charge), with interval_override_unit (days, weeks or months); null = the product's frequency. Kept after the product leaves the flow; PATCH /v1/subscription/subs/:id { resetFrequency: true } clears it. |
| `sub.interval_override_unit` | string\|null | days, weeks or months; null with interval_override_value. |
| `sub.flow_cursor` | object\|null | Where the next attempt of the current cycle starts in the flow, and what the cycle keeps: { v, flowId, versionId, nodeId, cycle, pending?, thisFrom?, nextFrom?, at }. thisFrom and nextFrom are the amounts the two kept prices of pending belong to (the planned amount of the charge, the price of the sub): a kept price is used only while that amount is still in force, so an amount you set meanwhile is charged and stays. Read only while its flow is the product's and its cycle the charge's. |
| `sub.flow_skipped_cycle` | integer\|null | The charge number (rebill_number, one more than cycle) of the last "Skip this cycle" a Rebill Flow decided after a declined charge (its "If declined" output), with flow_skipped_at; null when it never did. The attempts of that charge number made up to flow_skipped_at belong to the skipped period: the charge of the next billing date is a first try again. |
| `sub.flow_skipped_at` | string (ISO-8601)\|null | The instant the declined charge of that skip was created; null with flow_skipped_cycle. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - no sub of the account with this id, or an id that is not a uuid (v3.9.15 - e.g. the removed GET .../subs/facets).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- entries include cancelled duplicates left by edits / re-plans - filter on status.
- The pinned pending charge is the one whose id equals sub.current_entry_id.
- A path id that is not a uuid is a 404 (it was a 400 "A value has an invalid format"); the removed GET /v1/subscription/subs/facets answers this 404.

##### `PATCH /v1/subscription/subs/:id`

**Scope** `subscriptions.write` - **Edit a sub**

Edits a live (active / paused) sub: its amount, its next charge instant, and/or moves it to another product (amount replaced by the new product's unless keepAmount or amountCents is given). The pending charge is dropped and re-materialised with the new amount / slot (a charge already in flight keeps its pin - the edit applies from the following charge). Returns the sub.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped), status active or paused. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `amountCents` | integer | no | > 0 - the new per-sub price (this sub only). A price a Rebill Flow keeps for the current cycle was computed from the earlier amount: it is not applied over the new one. |
| `nextChargeAt` | ISO-8601 | no | New next charge instant (offset required). Past -> today's remaining window. |
| `subscriptionId` | uuid | no | Move the sub to this product of the account (422 if unknown / conflict). Same id as the current product = no move. |
| `keepAmount` | boolean; default `false` | no | With subscriptionId: keep the sub's amount instead of the new product's (implied when amountCents is sent). |
| `resetFrequency` | boolean (true only) | no | true: the frequency a Rebill Flow gave this sub goes, the product's frequency applies again (interval_override_value and interval_override_unit are written null). The planned next charge is not moved: the next approval uses the product's frequency, and a frequency the current cycle of a Rebill Flow still keeps for that approval is removed with it. A sub with no frequency of its own changes nothing else. false is refused (400). |

**Request body**

```json
{
  "amountCents": 4999,
  "nextChargeAt": "2026-10-01T14:00:00Z"
}
```

**Response**

```json
{
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 4999,
    "status": "active",
    "cycle": 2,
    "retry_step": 0,
    "next_charge_at": "2026-10-01T14:00:00.000Z",
    "current_entry_id": "5061728e-9fa0-4b1c-8d2e-3f405162738f",
    "last_charge_at": "2026-09-19T15:07:05.210Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-19T14:35:00.000Z",
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-10-01T14:00:00.000Z",
    "entry_amount_cents": 4999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `sub` | object | The sub after the edit (SubDetailRow), re-read. |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - amountCents <= 0, nextChargeAt without offset, non-uuid subscriptionId.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}.
- `422` {"error":"Sub is <status>"} - only active / paused subs can be edited.
- `422` {"error":"Unknown subscription"} - subscriptionId not in the account.
- `422` {"error":"Could not change the subscription (the order already has a live sub on it, or this sub is not live)"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- An empty body is accepted: nothing changes and the sub is returned.
- On a PAUSED sub the new amount / slot are stored but no charge is planned until it is resumed.
- A charge currently 'processing' is not dropped: its result still lands on the sub (the paid cycle advances) and the edit shapes the NEXT charge.
- The cycle count and retry_step are kept across a product change.
- The re-materialised charge gets a NEW entry id (current_entry_id changes) - possibly in a different schedule if the day changed.
- Routing: resetFrequency writes sub.edited "frequency every 2 months -> the product frequency" in the customer timeline; a price a Rebill Flow gave the sub is changed with amountCents, as any price.

##### `DELETE /v1/subscription/subs/:id`

**Scope** `subscriptions.write` - **Cancel a sub**

Ends a live sub (active / paused / failed): status -> cancelled, end_cause 'user', cancel_reason = the given reason or 'cancelled by <actor>', cancelled_at now, next charge and pin cleared, the pending charge cancelled. Returns the cancelled sub. The row is kept (no hard delete).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `reason` | string; default `'cancelled by <actor>'` | no | Trimmed <= 200 chars, stored as cancel_reason. Optional JSON body (Content-Type: application/json) on a DELETE. |

**Request body**

```json
{
  "reason": "customer requested cancellation"
}
```

**Response**

```json
{
  "ok": true,
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "cancelled",
    "cycle": 2,
    "retry_step": 0,
    "next_charge_at": null,
    "current_entry_id": null,
    "last_charge_at": "2026-09-19T15:07:05.210Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": "customer requested cancellation",
    "cancelled_at": "2026-09-19T14:47:00.000Z",
    "end_cause": "user",
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-19T14:45:00.000Z",
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": null,
    "entry_scheduled_at": null,
    "entry_amount_cents": null,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `sub` | object | The sub after cancellation (SubDetailRow). |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"Not found or already ended"} - unknown id, another account's sub, or a sub already cancelled / completed / expired (no 404 on this route).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- This is a CANCEL, not a delete: the sub stays in every list with status 'cancelled' and counts as lost in monitoring.
- end_cause 'user' is final for auto-attach: the customer is never re-attached to this product automatically (a manual POST /v1/subscription/subs still can).
- A charge already in flight is not cancelled; its result is recorded but does not revive the sub.
- An invalid body (e.g. reason > 200 chars) is not a 400 - the default reason is used instead.

##### `POST /v1/subscription/subs/:id/charge-now`

**Scope** `subscriptions.write` - **Force bill one sub now**

Charges ONE customer sub right now, synchronously, through the dispatcher's own claim-then-charge path (the schedule-level Force bill runs a whole day as a job; this is the customer view's "Force bill"). The sub must be active, paused or failed - a paused / failed one is resumed at now first (retry_step 0). Its pending charge is reused when already due, else re-planned at now (the old entry is cancelled with reason 'force bill', so the next cycle counts from today); the entry is then CLAIMED atomically (scheduled -> processing, only while it is the sub's pinned charge, never under a manual job), charged (BIN rebill scrub, idempotent gateway call, the sub advanced / retried / ended by the verdict), the schedule status recomputed and the day's history stamped force_bill_sub. Returns the verdict (kind / reason / MID / transaction / amount) and the refreshed sub. v3.9.12 - an optional ROUTE (JSON body; rebill/manualRoute.ts): an ATRI (`atriId`: that ATRI replaces the split's pick and its routing chooses the MID - its profiles apply) or a MID (`midId`: that MID is the ONLY attempt - pinOnly, the dashboard Retry's rule, no cascade - , inside the active ATRI that holds it: the sub's product's own ATRI first, then the account default, then the oldest); neither (or no body) = "Use original" (the charge's schedule's ATRI split, else the account's default ATRI - the engine's own path, unchanged). Resolved and validated before anything is written; the answer names it in `route`. A charge whose day is PAUSED is refused before the sub or its charge is touched.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped), status active, paused or failed. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `atriId` | uuid | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `midId` | uuid | no | Select one account-owned active ATRI or activated MID, never both. NMI and Convesio MIDs with a supported card adapter are accepted. The ATRI must contain an activated card-capable MID; a selected MID must belong to an active ATRI. null route clears a persistent override; omit atriId/midId for the original force-bill route. |
| `requestId` | uuid | no | Stable operator intent ID. Reuse the same ID and body after a network interruption; a completed intent replays its result, while an unfinished or changed intent returns 409. |
| `expectedEntryId` | uuid | no | Refuse if the pending entry changed since review. Required when requireStoredThreeDs is true. |
| `expectedCycle` | integer | no | Expected current subscription cycle, 0..100000; a mismatch returns 409 before replanning. |
| `expectedAmountCents` | integer | no | Expected pending amount in cents, 1..100000000. Checked before and after replanning and atomically at claim. Required when requireStoredThreeDs is true. |
| `expectedCurrency` | string | no | Expected three-letter currency, case insensitive. Required when requireStoredThreeDs is true. |
| `requireStoredThreeDs` | boolean | no | Require a compatible saved PAAY proof. Missing proof refuses the gateway send; no fallback without 3DS or to another MID. The requirement survives replans of this cycle. |

**Request body**

```json
{
  "midId": "9c8b7a6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"
}
```

**Response**

```json
{
  "kind": "success",
  "reason": null,
  "midName": "MID US 02",
  "transactionId": "c0ffee00-aaaa-4bbb-8ccc-dddd00002222",
  "amountCents": 6999,
  "entryId": "0f1e2d3c-4b5a-4968-8776-655443322110",
  "scheduleId": "5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d",
  "testMode": false,
  "route": {
    "atriId": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
    "atriName": "Main Rebill",
    "midId": "9c8b7a6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
    "midName": "MID US 02"
  },
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "active",
    "cycle": 3,
    "retry_step": 0,
    "next_charge_at": "2026-10-21T15:00:00.000Z",
    "current_entry_id": "7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d",
    "last_charge_at": "2026-09-21T15:00:04.310Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-21T15:00:04.400Z",
    "subscription_name": "VIP Monthly",
    "product_atri_split": [
      {
        "id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
        "name": "Main Rebill",
        "pct": 100
      }
    ],
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-10-21T15:00:00.000Z",
    "entry_amount_cents": 6999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `kind` | enum: success\|failed\|rejected\|cancelled\|requeued\|reverted\|flow_paused\|flow_cancelled\|flow_postponed\|flow_skipped\|flow_ended | The verdict: success = paid (cycle advanced, next charge planned); failed = declined by the gateway (reason set; the sub follows the normal decline path - dunning retry or failed); rejected = BIN rebill scrub, the sub ends (binscrub); cancelled = blacklisted customer, the sub ends; requeued = transient error, the charge is re-planned by the engine; reverted = the result was superseded (the entry stopped being ours in flight). |
| `reason` | string\|null | The decline / scrub / error reason (null on success). |
| `midName` | string\|null | The MID that answered (null when nothing was sent: scrub, transport error). |
| `transactionId` | uuid\|null | The transaction row written by the charge (null when nothing was sent or in test mode). |
| `amountCents` | integer | What was charged: the sub's amount, or the retry profile's amount on a dunning retry step. |
| `entryId` | uuid | The rebill entry (charge) that was claimed and charged. |
| `scheduleId` | uuid | The schedule (New York day) the charge belongs to - today's when the charge was re-planned. |
| `testMode` | boolean | True when the schedule is in test mode: the verdict is simulated, nothing reached the gateway, the sub was not advanced. |
| `route` | object\|null | The route the charge took when one was chosen: {atriId, atriName, midId, midName} (a MID route names its ATRI too); null = "Use original". The day's force_bill_sub history row and the sub.force_billed event carry it too (the event's message: 'Force bill by <operator> on MID <name> (ATRI <name>): ...'). |
| `sub` | object\|null | The sub after the charge (SubDetailRow, see GET /v1/subscription/subs/:id): cycle / next_charge_at / last_status / status reflect the verdict. v3.9.12: + product_atri_split (the product's ATRI split - what "Use original" takes). |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `400` {"error":"Invalid request","details":<zod flatten()>}: a field of the wrong type or range, or requireStoredThreeDs true without requestId, expectedEntryId, expectedAmountCents and expectedCurrency ("Saved 3DS force bill requires requestId, expectedEntryId, expectedAmountCents and expectedCurrency").
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown sub or another account's.
- `409` {"error":"A charge is already in flight for this sub"} (its pending entry is processing - the result lands within a minute), {"error":"A manual job is running on this schedule - wait for it or cancel it first"} (a Force bill / Sample job owns the day), or {"error":"The charge was claimed by the dispatcher meanwhile - check the sub in a minute"} (the auto tick took the entry between the read and the claim; nothing is charged twice).
- `409` Stale expected entry/cycle/amount/currency, changed or unfinished requestId, or payment outcome unconfirmed (code reconciliation_required). Unfinished intents require reconciliation before another charge.
- `409` {"error":"This requestId already belongs to a different force-bill request"}, {"error":"This force-bill request is in progress or awaiting reconciliation; do not submit a new requestId"}, {"error":"The subscription cycle changed since the force-bill preflight"}, {"error":"The pending charge changed since the force-bill preflight"}, {"error":"The pending charge amount or currency changed since the force-bill preflight"}, {"error":"The charge was claimed by the dispatcher meanwhile - check the sub in a minute"}, and with "code":"reconciliation_required": {"error":"A payment of this subscription requires reconciliation before another charge"} or "Payment outcome unconfirmed - reconcile the gateway payment before another charge".
- `422` {"error":"Sub is <status> - only active, paused or failed subs can be charged"} (cancelled / completed / expired), {"error":"Could not resume the sub (...)"} (another live sub of the order on the product), {"error":"No charge could be planned (the subscription product is inactive or the sub is not active)"}, or {"error":"Schedule is <status>"} (the charge sits in a cancelled / done day). v3.9.12: {"error":"The day of this charge is paused - resume the schedule first"} (the sub's current charge sits in a paused day - nothing is touched); {"error":"Choose one route: an ATRI or a MID"} (both given), {"error":"Unknown or inactive ATRI"}, {"error":"Unknown MID"}, {"error":"MID is disabled"}, {"error":"MID is not in any active ATRI"} - v3.9.12, the route refused before anything is written.
- `422` {"error":"Today's day of this subscription is paused|cancelled|error - resume it first"} - v3.9.12: a charge that is not due yet is re-planned into the product's day of today (New York); a stopped day there refuses the Force bill BEFORE the sub or its charge is touched.
- `422` Unknown/inactive ATRI, ATRI without an activated card-capable MID, disabled MID, unsupported card adapter, MID outside active ATRIs, or both atriId and midId supplied.
- `423` {"error":"Subscription dispatch is OFF for this account"} - the account kill switch (PATCH /v1/subscription/settings/global {"enabled":true}).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Force bill could not start; no new payment was submitted"}: replay the same requestId later.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- This charges the customer's card for real (a rebill through the gateway); a declined charge follows the normal retry rules. Never send it twice without the same requestId: a lost response is recovered by replaying the same requestId and body, which returns the first result instead of charging again.
- Synchronous: the call returns once the gateway answered (a few seconds). ONE sub per call - the customer view calls it once per live sub, one after the other, never in parallel.
- A confirmed decline is HTTP 200 (kind failed). An unconfirmed gateway outcome returns HTTP 409 with code reconciliation_required; the payment may have been captured, so do not submit a fresh request.
- A charge planned for later is re-planned at now - its old entry is cancelled with reason 'force bill' and a new one lands in TODAY's schedule (created if needed) - so the next cycle counts from today, not from the old slot. A charge already due is charged as is.
- A paused / failed sub is resumed first (like POST /subs/:id/resume at now, retry_step 0); a decline then follows the normal decline path (dunning retry through the product's retry profile, else failed).
- The rebill BIN scrub applies (kind = rejected, the sub ends with end_cause binscrub) unless the schedule has scrub_bypass; a blacklisted customer answers kind = cancelled.
- The schedule's test mode applies: testMode true = simulated verdict, nothing sent, the sub untouched.
- Stamped in the day's history as force_bill_sub (actor = the caller); the schedule status is recomputed at once, so the day may read Partial until its other charges are decided.
- The route applies to THIS charge only: a retry the engine plans after a decline takes the original route. The dashboard's Force bill modal (Use original - ATRI - MID) shows each sub's original route - its product's ATRI split (`product_atri_split`), its original order's MID, its last charge's MID - and calls this route once per sub, one after the other.
- A chosen MID is still checked like any pin: the rebill routing constraints (docs/SUBSCRIPTIONS.md section 7 - a MID a rule rules out for this order is dropped), its monthly cap and the card's brand. A MID refused there is NOT sent and the charge ends as a technical error ('MID ... is not available for this charge') - no cascade to another MID; the engine then treats it like any technical error.
- With no route ("Use original"), each charge takes its own route override, else its day's, else the ATRI split (precedence: this route > charge > day > split).
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.
- Prefer charge-now-v2. This legacy URL allows requestId to be omitted, so older callers retain the prior operator replay behavior. Unknown gateway results are held for reconciliation on both URLs.
- Routing: when the product of the sub is routed by a Rebill Flow and the call names no route, the flow decides this charge and can settle it without sending it. kind is then flow_paused (the sub is paused), flow_cancelled (the sub is cancelled), flow_postponed (the charge is planned again later, same cycle: retry later or change the bill date), flow_skipped (nothing is charged for this period, same cycle number) or flow_ended (the sub ended as declined: the action end as declined, or the limit of 15 failed attempts in a cycle); reason is "Rebill Flow: paused", "Rebill Flow: cancelled", "Rebill Flow: retry later", "Rebill Flow: bill date changed", "Rebill Flow: cycle skipped" or "Rebill Flow: ended as declined", and transactionId is null. A call that names an ATRI or a gateway is charged there: the flow is not asked, and its "If approved" and "If declined" are not used. With "Use original" and a confirmed amount (expectedAmountCents), that amount is charged: a price block of the flow does not change it; the amount answered is the amount charged. A price the flow keeps for the cycle is not lost: it stays kept for the next attempt of the cycle.

##### `POST /v1/subscription/subs/:id/charge-now-v2`

**Scope** `subscriptions.write` - **Force bill one sub with a durable operator intent**

Charges one customer subscription through the shared dispatcher with durable operator idempotency. A stable requestId is required: an identical retry returns the first settled result without charging the next cycle. An unfinished intent or changed body is a 409 conflict. Optional expected entry, cycle, amount and currency bind the request to reviewed pending-charge facts. requireStoredThreeDs requires a current entry, amount and currency; it atomically consumes a compatible saved PAAY proof, refuses sends without one and forbids unprotected fallback or another MID. A future charge is advanced to now, changing its due date and the next-cycle anchor. Unknown gateway outcomes remain pinned for reconciliation, without retrying or completing the operator intent. Unlike the legacy URL, an exact account-owned active ATRI/MID pair may be supplied and is validated at request time; routing, ownership, card-brand and capacity restrictions remain in force.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped), status active, paused or failed. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `atriId` | uuid | no | An active account-owned ATRI or activated card-capable MID. Both are allowed on v2 only when the MID is an active member of that exact ATRI. Omit both for the original route. |
| `midId` | uuid | no | An active account-owned ATRI or activated card-capable MID. Both are allowed on v2 only when the MID is an active member of that exact ATRI. Omit both for the original route. |
| `requestId` | uuid | **yes** | Stable operator intent ID. Reuse the same ID and body after a network interruption; a completed intent replays its result, while an unfinished or changed intent returns 409. |
| `expectedEntryId` | uuid | no | Refuse if the pending entry changed since review. Required when requireStoredThreeDs is true. |
| `expectedCycle` | integer | no | Expected current subscription cycle, 0..100000; a mismatch returns 409 before replanning. |
| `expectedAmountCents` | integer | no | Expected pending amount in cents, 1..100000000. Checked before and after replanning and atomically at claim. Required when requireStoredThreeDs is true. |
| `expectedCurrency` | string | no | Expected three-letter currency, case insensitive. Required when requireStoredThreeDs is true. |
| `requireStoredThreeDs` | boolean | no | Require a compatible saved PAAY proof. Missing proof refuses the gateway send; no fallback without 3DS or to another MID. The requirement survives replans of this cycle. |

**Request body**

```json
{
  "requestId": "a0c0ffee-1111-4111-8111-111111111111",
  "expectedEntryId": "0f1e2d3c-4b5a-4968-8776-655443322110",
  "expectedCycle": 2,
  "expectedAmountCents": 6999,
  "expectedCurrency": "USD",
  "requireStoredThreeDs": true,
  "atriId": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
  "midId": "9c8b7a6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"
}
```

**Response**

```json
{
  "kind": "success",
  "reason": null,
  "midName": "MID US 02",
  "transactionId": "c0ffee00-aaaa-4bbb-8ccc-dddd00002222",
  "amountCents": 6999,
  "entryId": "0f1e2d3c-4b5a-4968-8776-655443322110",
  "scheduleId": "5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d",
  "testMode": false,
  "route": {
    "atriId": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
    "atriName": "Main Rebill",
    "midId": "9c8b7a6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
    "midName": "MID US 02"
  },
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "active",
    "cycle": 3,
    "retry_step": 0,
    "next_charge_at": "2026-10-21T15:00:00.000Z",
    "current_entry_id": "7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d",
    "last_charge_at": "2026-09-21T15:00:04.310Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-21T15:00:04.400Z",
    "subscription_name": "VIP Monthly",
    "product_atri_split": [
      {
        "id": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
        "name": "Main Rebill",
        "pct": 100
      }
    ],
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-10-21T15:00:00.000Z",
    "entry_amount_cents": 6999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `kind` | enum: success\|failed\|rejected\|cancelled\|requeued\|reverted\|flow_paused\|flow_cancelled\|flow_postponed\|flow_skipped\|flow_ended | The verdict: success = paid (cycle advanced, next charge planned); failed = declined by the gateway (reason set; the sub follows the normal decline path - dunning retry or failed); rejected = BIN rebill scrub, the sub ends (binscrub); cancelled = blacklisted customer, the sub ends; requeued = transient error, the charge is re-planned by the engine; reverted = the result was superseded (the entry stopped being ours in flight). |
| `reason` | string\|null | The decline / scrub / error reason (null on success). |
| `midName` | string\|null | The MID that answered (null when nothing was sent: scrub, transport error). |
| `transactionId` | uuid\|null | The transaction row written by the charge (null when nothing was sent or in test mode). |
| `amountCents` | integer | What was charged: the sub's amount, or the retry profile's amount on a dunning retry step. |
| `entryId` | uuid | The rebill entry (charge) that was claimed and charged. |
| `scheduleId` | uuid | The schedule (New York day) the charge belongs to - today's when the charge was re-planned. |
| `testMode` | boolean | True when the schedule is in test mode: the verdict is simulated, nothing reached the gateway, the sub was not advanced. |
| `route` | object\|null | The route the charge took when one was chosen: {atriId, atriName, midId, midName} (a MID route names its ATRI too); null = "Use original". The day's force_bill_sub history row and the sub.force_billed event carry it too (the event's message: 'Force bill by <operator> on MID <name> (ATRI <name>): ...'). |
| `sub` | object\|null | The sub after the charge (SubDetailRow, see GET /v1/subscription/subs/:id): cycle / next_charge_at / last_status / status reflect the verdict. v3.9.12: + product_atri_split (the product's ATRI split - what "Use original" takes). |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `400` Missing/invalid requestId, invalid expected values, or requireStoredThreeDs without expectedEntryId, expectedAmountCents and expectedCurrency.
- `400` {"error":"Invalid request","details":<zod flatten()>}: a field of the wrong type or range, or requireStoredThreeDs true without requestId, expectedEntryId, expectedAmountCents and expectedCurrency ("Saved 3DS force bill requires requestId, expectedEntryId, expectedAmountCents and expectedCurrency").
- `400` {"error":"requestId is required for charge-now-v2"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown sub or another account's.
- `409` {"error":"A charge is already in flight for this sub"} (its pending entry is processing - the result lands within a minute), {"error":"A manual job is running on this schedule - wait for it or cancel it first"} (a Force bill / Sample job owns the day), or {"error":"The charge was claimed by the dispatcher meanwhile - check the sub in a minute"} (the auto tick took the entry between the read and the claim; nothing is charged twice).
- `409` Stale expected entry/cycle/amount/currency, changed or unfinished requestId, or payment outcome unconfirmed (code reconciliation_required). Unfinished intents require reconciliation before another charge.
- `409` {"error":"This requestId already belongs to a different force-bill request"}, {"error":"This force-bill request is in progress or awaiting reconciliation; do not submit a new requestId"}, {"error":"The subscription cycle changed since the force-bill preflight"}, {"error":"The pending charge changed since the force-bill preflight"}, {"error":"The pending charge amount or currency changed since the force-bill preflight"}, {"error":"The charge was claimed by the dispatcher meanwhile - check the sub in a minute"}, and with "code":"reconciliation_required": {"error":"A payment of this subscription requires reconciliation before another charge"} or "Payment outcome unconfirmed - reconcile the gateway payment before another charge".
- `422` {"error":"Today's day of this subscription is paused|cancelled|error - resume it first"} - v3.9.12: a charge that is not due yet is re-planned into the product's day of today (New York); a stopped day there refuses the Force bill BEFORE the sub or its charge is touched.
- `422` Inactive subscription/product/day, invalid route, unavailable MID, unsupported card adapter, or MID outside the specified active ATRI.
- `423` {"error":"Subscription dispatch is OFF for this account"} - the account kill switch (PATCH /v1/subscription/settings/global {"enabled":true}).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Force bill could not start; no new payment was submitted"}: replay the same requestId later.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- This charges the customer's card for real (a rebill through the gateway); a declined charge follows the normal retry rules. Never send it twice without the same requestId: a lost response is recovered by replaying the same requestId and body, which returns the first result instead of charging again.
- Synchronous: the call returns once the gateway answered (a few seconds). ONE sub per call - the customer view calls it once per live sub, one after the other, never in parallel.
- A confirmed decline is HTTP 200 (kind failed). An unconfirmed gateway outcome returns HTTP 409 with code reconciliation_required; the payment may have been captured, so do not submit a fresh request.
- A charge planned for later is re-planned at now - its old entry is cancelled with reason 'force bill' and a new one lands in TODAY's schedule (created if needed) - so the next cycle counts from today, not from the old slot. A charge already due is charged as is.
- A paused / failed sub is resumed first (like POST /subs/:id/resume at now, retry_step 0); a decline then follows the normal decline path (dunning retry through the product's retry profile, else failed).
- The rebill BIN scrub applies (kind = rejected, the sub ends with end_cause binscrub) unless the schedule has scrub_bypass; a blacklisted customer answers kind = cancelled.
- The schedule's test mode applies: testMode true = simulated verdict, nothing sent, the sub untouched.
- Stamped in the day's history as force_bill_sub (actor = the caller); the schedule status is recomputed at once, so the day may read Partial until its other charges are decided.
- A chosen MID is still checked like any pin: the rebill routing constraints (docs/SUBSCRIPTIONS.md section 7 - a MID a rule rules out for this order is dropped), its monthly cap and the card's brand. A MID refused there is NOT sent and the charge ends as a technical error ('MID ... is not available for this charge') - no cascade to another MID; the engine then treats it like any technical error.
- With no route ("Use original"), each charge takes its own route override, else its day's, else the ATRI split (precedence: this route > charge > day > split).
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.
- The v2 URL deliberately returns 404 on older API versions instead of letting an old server ignore the safety fields. Migration 247 must be applied before deployment.
- An interrupted process can leave an unfinished intent and reconciliation hold. This release does not automatically release them: confirm the actual processor/transaction outcome before a new charge. Reset-processing and stale sweeps cannot release the hold.
- No cryptogram or card data is stored in the operator intent. A proof is conservatively consumed before sending and never returned to stock after an uncertain result.
- The route is scoped to this force-bill call. requireStoredThreeDs persists on same-cycle retries and replans; future cycles start without that operator requirement.
- Routing: when the product of the sub is routed by a Rebill Flow and the call names no route, the flow decides this charge and can settle it without sending it. kind is then flow_paused (the sub is paused), flow_cancelled (the sub is cancelled), flow_postponed (the charge is planned again later, same cycle: retry later or change the bill date), flow_skipped (nothing is charged for this period, same cycle number) or flow_ended (the sub ended as declined: the action end as declined, or the limit of 15 failed attempts in a cycle); reason is "Rebill Flow: paused", "Rebill Flow: cancelled", "Rebill Flow: retry later", "Rebill Flow: bill date changed", "Rebill Flow: cycle skipped" or "Rebill Flow: ended as declined", and transactionId is null. A call that names an ATRI or a gateway is charged there: the flow is not asked, and its "If approved" and "If declined" are not used. With "Use original" and a confirmed amount (expectedAmountCents), that amount is charged: a price block of the flow does not change it; the amount answered is the amount charged. A price the flow keeps for the cycle is not lost: it stays kept for the next attempt of the cycle.

##### `GET /v1/subscription/subs/:id/customer`

**Scope** `subscriptions.read` - **Customer view of a sub**

Returns everything about the customer behind a sub: identity from the original card-on-file sale (contact, address, IP, masked card, expiry, brand), the original sale, every sub of the order (live and ended), the full charge history of the account for that order or the same e-mail (sales and subscription charges, up to 300, newest first) and the basket products. v3.9.2 section 1: `runs` - the sale pipeline runs of every order the history lists (+ the sub's own order), newest first, <= 200, REFUSALS INCLUDED (a charge refused before any MID - cooldown, scrub, the duplicate-card guard - has a run and no transaction, so it shows here for the first time) - and `runNames`, the ATRI / MID names the runs cite. v3.9.2 section 3: `subs` lists EVERY sub of the CUSTOMER (order  union  e-mail  union  card, every product, live first - docs/SUBSCRIPTIONS.md section 3.6), no longer the subs of one order, and `customer_ref` is the key of the /v1/customers/:key/* routes (the resolved order id). v3.9.15: `history_capped` - the history lists the latest 300 charges; true when more exist.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped). |

**Response**

```json
{
  "customer": {
    "email": "jane@example.com",
    "first_name": "Jane",
    "last_name": "Doe",
    "phone": "+15555550123",
    "address1": "1 Main St",
    "city": "Austin",
    "state": "TX",
    "zip": "78701",
    "country": "US",
    "ip": "203.0.113.7",
    "masked_card": "411111******1111",
    "ccexp": "0928",
    "card_brand": "VISA"
  },
  "sale": {
    "id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "order_id": "ORD-118842",
    "created_at": "2026-08-19T15:07:44.000Z",
    "amount_cents": 4999,
    "currency": "USD",
    "status": "approved",
    "is_success": true,
    "decline_reason": null,
    "final_account_name": "MID US 01",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "refunded": false,
    "charged_back": false,
    "kind": "sale",
    "cycle": null,
    "subscription_name": null,
    "crm": "nmi",
    "dispute_kind": null,
    "wallet_provider_id": null,
    "pre_gateway": false,
    "paysource": null
  },
  "subs": [
    {
      "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "owner_email": "ops@example.com",
      "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
      "email": "jane@example.com",
      "amount_cents": 6999,
      "status": "active",
      "cycle": 2,
      "retry_step": 0,
      "next_charge_at": "2026-10-19T15:07:00.000Z",
      "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
      "last_charge_at": "2026-09-19T15:07:05.210Z",
      "last_status": "rebill_success",
      "last_decline_reason": null,
      "source": "auto",
      "attached_by": "sale",
      "cancel_reason": null,
      "cancelled_at": null,
      "end_cause": null,
      "created_at": "2026-08-19T15:07:44.000Z",
      "updated_at": "2026-09-19T15:07:05.400Z",
      "subscription_name": "VIP Monthly",
      "interval_days": 30,
      "first_after_days": 3,
      "interval_value": 1,
      "interval_unit": "months",
      "first_after_value": 3,
      "first_after_unit": "days",
      "first_name": "Jane",
      "last_name": "Doe",
      "masked_card": "411111******1111",
      "storefront_url": "https://shop.example.com/checkout",
      "country": "US",
      "sale_at": "2026-08-19T15:07:44.000Z",
      "sale_amount_cents": 4999,
      "sale_mid": "MID US 01",
      "card_brand": "VISA",
      "entry_status": "scheduled",
      "entry_scheduled_at": "2026-10-19T15:07:00.000Z",
      "entry_amount_cents": 6999,
      "product_slug": "vip-bundle",
      "product_name": "VIP Bundle",
      "last_charge_amount_cents": 6999,
      "total": 1
    }
  ],
  "history": [
    {
      "id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "order_id": "ORD-118842",
      "created_at": "2026-09-19T15:07:05.210Z",
      "amount_cents": 6999,
      "currency": "USD",
      "status": "approved",
      "is_success": true,
      "decline_reason": null,
      "final_account_name": "MID US 02",
      "masked_card": "411111******1111",
      "storefront_url": null,
      "refunded": false,
      "charged_back": false,
      "kind": "subscription",
      "cycle": 2,
      "subscription_name": "VIP Monthly",
      "crm": "nmi",
      "dispute_kind": null,
      "wallet_provider_id": null,
      "pre_gateway": false,
      "paysource": null
    }
  ],
  "history_capped": false,
  "products": [
    {
      "slug": "vip-bundle",
      "name": "VIP Bundle",
      "quantity": 1,
      "amount_cents": 4999
    }
  ],
  "runs": [
    {
      "id": "5e4d3c2b-1a09-4f8e-8d7c-6b5a49382716",
      "created_at": "2026-09-25T09:12:40.000Z",
      "order_id": "ORD-118842",
      "transaction_id": null,
      "rejection_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
      "run_no": 1,
      "resumed_from": null,
      "flow": "rebill",
      "channel": "rebill-auto",
      "trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "final_trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "bin": "411111",
      "issuer_key": "JPMORGAN CHASE",
      "card_brand": "Visa",
      "card_funding": "Debit",
      "country": "US",
      "amount_cents": 6999,
      "outcome": "rejected",
      "refused_by": "card_cooldown",
      "fell_through": false,
      "stages": [
        {
          "name": "context",
          "input": {
            "orderId": "ORD-118842",
            "flow": "rebill",
            "channel": "rebill-auto",
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "brand": "visa",
            "country": "US",
            "binSource": "warm",
            "reads": 0
          },
          "decision": {
            "action": "resolve",
            "applied": true
          },
          "durationUs": 880
        },
        {
          "name": "refusals",
          "input": {
            "flow": "rebill",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "rules": "blacklist,precheck,duplicate_card",
            "scrubbing": null
          },
          "decision": {
            "action": "refuse",
            "applied": true,
            "reason": "duplicate_card: Duplicate card: order ORD-118840 already declined today in this..."
          },
          "durationUs": 2900
        },
        {
          "name": "rebill_rules",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "mapping",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "route",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "threeds",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "send",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        }
      ],
      "total_us": 4100,
      "t_claim_us": null,
      "t_first_send_us": null,
      "t_completed_us": null
    },
    {
      "id": "0a9b8c7d-6e5f-4a4b-8c3d-2e1f0a9b8c7d",
      "created_at": "2026-09-19T15:07:05.210Z",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "rejection_id": null,
      "run_no": 1,
      "resumed_from": null,
      "flow": "rebill",
      "channel": "rebill-auto",
      "trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "final_trip_id": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
      "bin": "411111",
      "issuer_key": "JPMORGAN CHASE",
      "card_brand": "Visa",
      "card_funding": "Debit",
      "country": "US",
      "amount_cents": 6999,
      "outcome": "approved",
      "refused_by": null,
      "fell_through": true,
      "stages": [
        {
          "name": "context",
          "input": {
            "orderId": "ORD-118842",
            "flow": "rebill",
            "channel": "rebill-auto",
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "brand": "visa",
            "country": "US",
            "binSource": "warm",
            "reads": 0
          },
          "decision": {
            "action": "resolve",
            "applied": true
          },
          "durationUs": 910
        },
        {
          "name": "route",
          "input": {
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "defaultTripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
            "brand": "visa",
            "pinOnly": false,
            "pin": null,
            "mappingPool": 0,
            "mappingSingle": null,
            "strategy": "random",
            "candidates": 4,
            "eligible": 0,
            "level": "default"
          },
          "decision": {
            "action": "fallthrough",
            "applied": true,
            "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
            "pool": [
              "c1d2e3f4-a5b6-4788-9900-aabbccddeeff"
            ],
            "pool_n": 1,
            "reason": "fallthrough: no MID supports visa -> default ATRI"
          },
          "durationUs": 402000
        },
        {
          "name": "send",
          "input": {
            "tripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
            "strategy": "random",
            "ordered": 1,
            "pinned": null,
            "cascadeTripId": null,
            "retryWithoutThreeDs": false,
            "threeDs": null
          },
          "decision": {
            "action": "charge",
            "applied": true,
            "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
            "pool_n": 1,
            "reason": "approved on MID-EU-03 (1 attempt)"
          },
          "durationUs": 1977000
        }
      ],
      "total_us": 2610000,
      "t_claim_us": 6200,
      "t_first_send_us": 421000,
      "t_completed_us": 2610000
    }
  ],
  "runNames": {
    "trips": {
      "0e7bce71-1111-4222-8333-444455556666": "US Rebill",
      "481c0a6e-4107-4128-99bd-6d52ac4362e5": "US Straight Sale"
    },
    "mids": {
      "c1d2e3f4-a5b6-4788-9900-aabbccddeeff": "MID-EU-03"
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `customer` | object | {email, first_name, last_name, phone, address1, city, state, zip, country, ip, masked_card, ccexp, card_brand} from the original card-on-file sale. |
| `sale` | object\|null | The original sale as a CustomerTxnRow: {id, order_id, created_at, amount_cents, currency, status, is_success, decline_reason, final_account_name, masked_card, storefront_url, refunded, charged_back, crm, dispute_kind, wallet_provider_id, paysource, kind:'sale'\|'subscription', cycle, subscription_name} (the example's `pre_gateway` is a column still selected until it is dropped - always false on a listed row, read by nothing). |
| `subs` | array | Every sub of the order (live and ended), as SubDetailRow (see GET /v1/subscription/subs). v3.9.12: each row carries product_atri_split (what a Force bill's "Use original" takes). |
| `history` | array | Up to 300 transactions of the account for this order OR the same e-mail, newest first (sales and subscription charges, kind tells which). Each row is a CustomerTxnRow plus the facts the row's ... menu gates on: crm, dispute_kind (rdr \| ethoca \| null), wallet_provider_id, paysource - the same actions as the transaction modal (refund, external refund, RDR / Ethoca, retry, blacklist, chargeback). v3.9 section 1: `pre_gateway` no longer gates anything (a refusal before any MID is not a transaction); the column still appears in the payload, always false, until it is dropped. |
| `history_capped` | boolean | True when the customer has more than the 300 charges `history` lists (the view says so and links to /transactions with customerEmail). |
| `products` | array | [{slug, name, quantity, amount_cents}] the sale's basket. |
| `runs` | array | v3.9.2 section 1 - the sale pipeline runs (sale_pipeline_runs, 30 days kept) of the customer's orders: owner-scoped, newest first, at most 200. Each is a PIPELINE_RUN (fields below). Empty on a database without the table. |
| `PIPELINE_RUN.id / created_at / order_id / transaction_id / rejection_id` | uuid / string / string / uuid \| null / uuid \| null | One sale pipeline run (sale_pipeline_runs, migration 148). transaction_id is null for a refusal (no transactions row, v3.9 section 1) and for a discarded 3DS-policy row; rejection_id is the charge_rejections row when refused. |
| `PIPELINE_RUN.run_no / resumed_from` | integer / uuid \| null | A 3DS challenge re-submit RESUMES the run that parked: run_no 2, resumed_from = run 1 (its stages 2-4 copied as skipped: "resumed", never re-evaluated). |
| `PIPELINE_RUN.flow / channel / trip_id / final_trip_id` | string \| null ... | flow initial \| rebill; trip_id = the ATRI resolved at the start, final_trip_id = after a mapping redirect / the fall-through to the account's default ATRI (an ATRI with no eligible MID for the card never ends the charge any more). |
| `PIPELINE_RUN.bin / issuer_key / card_brand / card_funding / country / amount_cents` | scalars | The context the rules matched on: first 6 digits only, the canonical issuer key, the brand, funding and country from the bin_info preload / the payload. Never a PAN. |
| `PIPELINE_RUN.outcome / refused_by / fell_through` | enum / string \| null / boolean | outcome in approved \| declined \| error \| rejected \| parked \| replayed \| unknown; refused_by = the rejection family when rejected; fell_through = at least one stage ended in a fall-through (a technical problem routed around - the "never refused for a technical reason" counter). |
| `PIPELINE_RUN.stages[]` | array | The ordered stages - context, refusals, rebill_rules, mapping, route, threeds, send (9 entries when a cascade route/send pair was appended): { name, skipped? (not_applicable \| short_circuit \| resumed), input (ids and scalars, <= 256 B), decision: { action, applied, reason (<= 80 chars), profileId?, ruleId?, matchType?, pool (<= 5 ids), pool_n, chosen?, redirectTripId? } \| null, durationUs, error? ("timeout" \| "error" = the stage failed open) }. The whole array is <= 4 096 bytes. Every stage's vocabulary: docs/SALE_FLOW.md section 5. |
| `PIPELINE_RUN.total_us / t_claim_us / t_first_send_us / t_completed_us` | integer \| null | Microseconds from the request's receipt (the scheduler's claim instant for a Subscription charge): the result, the claim (start of stage 5), the first gateway send, the finalize. total_us is always set (a refusal has a real total: the cost of the gates); t_claim_us / t_first_send_us / t_completed_us are null for a refusal (no claim); all four are null for a swept "abandoned claim" run. |
| `runNames` | object | { trips: { <atri id>: name }, mids: { <mid id>: name } } - every ATRI / MID the runs' stages cite, resolved for display. |
| `customer_ref` | string | v3.9.2 section 3 - the order the view landed on; the key of GET /v1/customers/:key/subscriptions, /events, /events/export.csv and POST /v1/customers/:key/flag. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown sub or another account's.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- history mixes the order's transactions with OTHER orders of the same e-mail - kind ('sale' | 'subscription') and order_id tell them apart.
- customer fields fall back to the sub's own copies (e-mail, name, card) when the sale row is missing; phone / address are then null.
- The response is the bare CustomerDetail object (no wrapper key).
- `history` is the latest 300 charges (order  union  e-mail, account-wide); `history_capped` says when there are more. The Clients KPI strip reads GET /v1/customers/:key/summary instead (the list's own figures).

##### `POST /v1/subscription/subs/:id/pause`

**Scope** `subscriptions.write` - **Pause a sub**

Pauses an ACTIVE sub: status -> paused, its pending charge is cancelled (reason 'sub paused') and unpinned; a charge already in flight keeps its pin so its result still lands (a success advances the cycle, a decline is recorded). Nothing is planned until resumed. Returns the sub.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped), status active. |

**Response**

```json
{
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "paused",
    "cycle": 2,
    "retry_step": 0,
    "next_charge_at": "2026-10-19T15:07:00.000Z",
    "current_entry_id": null,
    "last_charge_at": "2026-09-19T15:07:05.210Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-19T14:40:00.000Z",
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": null,
    "entry_scheduled_at": null,
    "entry_amount_cents": null,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `sub` | object | The paused sub (SubDetailRow). |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"Only an active sub can be paused"} - also returned for an UNKNOWN id or another account's sub (there is no 404 on this route).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- No 404: a wrong id and a non-active sub both answer 422 with the same message.
- next_charge_at is kept: resume without a body restarts at that instant if still ahead, else now.
- Pausing does not count as lost in monitoring (only cancelled / failed / expired do); paused subs contribute nothing to MRR.

##### `POST /v1/subscription/subs/:id/resume`

**Scope** `subscriptions.write` - **Resume a sub**

Resumes a paused or failed sub: status -> active, retry_step reset to 0, next charge = the given instant, else the stored next_charge_at if still in the future, else now; the charge is materialised at once (a past instant lands in the next minutes for sub-day products or in today's remaining New York window otherwise). A pin kept on a charge still in flight is preserved so no second charge is planned. Returns the sub.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Sub id (account-scoped), status paused or failed. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `nextChargeAt` | ISO-8601; default `(stored next_charge_at, else now)` | no | Instant of the next charge, with offset ('Z' or +/-hh:mm). Omit to reuse the stored next_charge_at (if ahead) or charge now. |

**Request body**

```json
{
  "nextChargeAt": "2026-09-25T14:00:00Z"
}
```

**Response**

```json
{
  "sub": {
    "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "owner_email": "ops@example.com",
    "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
    "order_id": "ORD-118842",
    "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "email": "jane@example.com",
    "amount_cents": 6999,
    "status": "active",
    "cycle": 2,
    "retry_step": 0,
    "next_charge_at": "2026-09-25T14:00:00.000Z",
    "current_entry_id": "6172839f-a0b1-4c2d-9e3f-405162738f90",
    "last_charge_at": "2026-09-19T15:07:05.210Z",
    "last_status": "rebill_success",
    "last_decline_reason": null,
    "source": "auto",
    "attached_by": "sale",
    "cancel_reason": null,
    "cancelled_at": null,
    "end_cause": null,
    "created_at": "2026-08-19T15:07:44.000Z",
    "updated_at": "2026-09-19T14:45:00.000Z",
    "subscription_name": "VIP Monthly",
    "interval_days": 30,
    "first_after_days": 3,
    "interval_value": 1,
    "interval_unit": "months",
    "first_after_value": 3,
    "first_after_unit": "days",
    "first_name": "Jane",
    "last_name": "Doe",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "country": "US",
    "sale_at": "2026-08-19T15:07:44.000Z",
    "sale_amount_cents": 4999,
    "sale_mid": "MID US 01",
    "card_brand": "VISA",
    "entry_status": "scheduled",
    "entry_scheduled_at": "2026-09-25T14:00:00.000Z",
    "entry_amount_cents": 6999,
    "product_slug": "vip-bundle",
    "product_name": "VIP Bundle",
    "last_charge_amount_cents": 6999,
    "total": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `sub` | object | The resumed sub (SubDetailRow). |
| `sub.id` | uuid | Sub id. |
| `sub.subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `sub.order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `sub.email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `sub.amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `sub.status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `sub.cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `sub.next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `sub.current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `sub.last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `sub.source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `sub.end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `sub.sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `sub.product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `sub.created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - nextChargeAt not ISO-8601 with offset.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown id or another account's sub.
- `422` {"error":"Sub is <status> - only paused or failed subs resume"} - the sub is active / cancelled / completed / expired, OR the order already has another live sub on the product (the message then still quotes the current status, e.g. "Sub is paused").
- `422` {"error":"customer already holds another live subscription - allow several subscriptions first","refused":"customer_has_live_sub"} - v3.9.2 section 3 Law (a) applies to a resume (docs/SUBSCRIPTIONS.md section 3.5) unless the customer's flag is on (POST /v1/customers/:key/flag). Also {"refused":"order_has_live_sub"} when the order already has a live sub on the product.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Resuming without a body a sub paused long ago charges it NOW (today's remaining window) - send nextChargeAt to control the date.
- A 'failed' sub (declined out) can be resumed: it retries at the given instant with retry_step 0.
- The 422 message can be misleading when the real cause is a unique-index conflict (another live sub of the same order on the product).
- Resuming does not touch the amount - edit it with PATCH first if the price changed.
- v3.9.2 section 3: the refusal carries `refused` in not_resumable | order_has_live_sub | customer_has_live_sub; the resume stamps resumed_at, clears the end stamp of a failed sub and logs sub.resumed with the operator as actor.

##### `POST /v1/subscription/subs/attach-sale`

**Scope** `subscriptions.write` - **Re-run the attach for one sale**

Re-runs the settle-time attach for one card-on-file sale of the account: every active auto-attach product whose attach_on / storefronts / attach share match gets a sub (first charge = sale + first delay, materialised at once). Skips blacklisted customers, expired cards, refunded / charged-back orders, Exify-exclusive orders and products that already have a live sub on the order. Returns the attach counters.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | The SALE transaction id (NMI card sale with card on file, not a rebill charge), owned by the account. |

**Request body**

```json
{
  "transactionId": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001"
}
```

**Response**

```json
{
  "attached": 1,
  "skipped": {
    "blacklisted": 0,
    "expired": 0,
    "refunded": 0,
    "exify": 0,
    "exists": 1,
    "share": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `attached` | integer | Subs created (one per matching product). |
| `skipped` | object | {blacklisted, expired, refunded, exify, exists, share} - exists = the order already had a live sub on that product (or lost a race); share = an active auto-attach product did not match (outcome, storefront or attach share). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - transactionId missing / not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Sale not found for this account"} - not a card-on-file NMI sale, a rebill charge, or another account's transaction.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 200 with attached: 0 is normal (nothing matched or everything already attached) - inspect skipped.
- Unlike POST /v1/subscription/subs, this honours the products' attach rules (attach_on, storefronts, attach_pct) and the expiry / Exify checks.
- An old sale whose first charge is already past is charged today (remaining New York window).
- skipped.share is named after the attach share but also counts outcome / storefront mismatches.

##### `POST /v1/subscription/subs/bulk`

**Scope** `subscriptions.write` - **Bulk action on subs**

Applies one action to many subs (8 at a time): pause (active -> paused, pending charge dropped), resume (paused / failed -> active at the stored next charge if still ahead, else now, charge re-materialised), cancel (active / paused / failed -> cancelled, end_cause 'user'), change_subscription (move a live sub to another product, amount replaced unless keepAmount, pending charge re-planned) or amount (new amount for active / paused subs, pending charge re-planned). Returns done / skipped counts. Optional async:true creates a durable bulk-edit job and returns202 {jobId,job}. The legacy synchronous contract remains supported.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `action` | enum: pause\|resume\|cancel\|change_subscription\|amount | no | The action. Required in synchronous mode or when async actions[] is absent. |
| `subscriptionId` | uuid | no | change_subscription: target product of the account (422 if unknown). |
| `keepAmount` | boolean; default `false` | no | change_subscription: keep each sub's current amount instead of the new product's. |
| `amountCents` | integer | no | Single positive price in cents for action=amount. Mutually exclusive with amountCentsList; omit when supplying the price list. |
| `reason` | string | no | cancel: cancel_reason (<= 200); default 'cancelled in bulk by <actor>'. |
| `async` | boolean; default `false` | no | true submits a durable background job and returns HTTP 202 {jobId,job}; false uses the legacy synchronous operation. |
| `requestId` | uuid | no | Async idempotency key; same key and identical payload returns the original job; changed payload returns 409. |
| `actions` | object[] (1..8) | no | Async mode: ordered compound actions. Each action has action plus its fields. Use this instead of a single top-level action. |
| `amountCentsList` | integer[] (1..10000) | no | Prices in minor currency units, each 1..2147483647, for action=amount. Send exactly one of amountCents or amountCentsList. Supported in async mode only; put inside actions[] for compound edits. |
| `ids` | uuid[] | **yes** | Selected subscription IDs: 1..10000 synchronous, 1..100000 async. Async mode deduplicates IDs and rejects stale or foreign selections. |
| `actions[].action` | enum: amount\|pause\|resume\|cancel\|change_subscription | no | Async mode: one step of the compound edit (cancel_charge, credential_mode and route need a schedule and answer 422 here). |
| `actions[].amountCents` | integer | no | amount: one price in cents, 1..2147483647 (or amountCentsList, not both). |
| `actions[].amountCentsList` | integer[] | no | amount: 1..10000 prices spread over the selection. |
| `actions[].subscriptionId` | uuid | no | change_subscription: target product of the account (required for it). |
| `actions[].keepAmount` | boolean; default `false` | no | change_subscription: keep each sub's amount. |
| `actions[].reason` | string | no | cancel: reason, up to 200 characters. |

**Request body**

```json
{
  "async": true,
  "requestId": "00000000-0000-4000-8000-000000000001",
  "ids": [
    "00000000-0000-4000-8000-000000000001"
  ],
  "actions": [
    {
      "action": "amount",
      "amountCentsList": [
        1999,
        2999,
        3999,
        4999
      ]
    }
  ]
}
```

**Response**

```json
{
  "done": 2,
  "skipped": 0
}
```

| response field | type | description |
|---|---|---|
| `done` | integer | Subs the action applied to. |
| `skipped` | integer | Subs in a state the action does not apply to (pause on a non-active sub, resume on an active one, amount on an ended one...), target conflicts (the order already has a live sub on the target product), foreign / unknown ids, or per-item errors (swallowed). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - unknown action, ids empty / > 10000 / non-uuid, amountCents <= 0, reason > 200.
- `400` Async mode: {"error":"Invalid bulk edit","details":...} (selection shape), {"error":"Select at least one item"} or {"error":"Invalid action","details":...} (for example "Choose one amount or a list of prices", "Subscription required").
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` Async mode: {"error":"No account"}.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `409` Async mode: {"error":"Another bulk edit is already running for this account","jobId":"<id>"}.
- `413` Body larger than 8 MiB.
- `422` {"error":"Unknown subscription"} - change_subscription without a valid product.
- `422` {"error":"Amount required"} - action amount without amountCents.
- `422` Async mode: {"error":"This action requires a schedule"} (cancel_charge, credential_mode, route) or {"error":"Unknown subscription"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- resume on a sub whose next_charge_at is in the past charges it NOW (within minutes for sub-day products, within today's New York day otherwise).
- change_subscription keeps the sub's cycle and retry_step; a paused sub is moved but nothing is planned until resumed; an order that already has a live sub on the target is skipped, not 422.
- amount / change_subscription cancel the pending charge and create a NEW one (new entry id); a charge already in flight keeps its pin and lands on the sub.
- cancel sets end_cause 'user': the customer is never auto-attached to that product again (only decline / card_expired endings allow a re-attach by a paid legacy charge).
- Errors are swallowed per id - you never learn which ids were skipped; re-list with the filters to verify.
- Send requestId(UUID) for idempotent submission and actions[] (up to 8) for a compound edit. Selection supports up to 100000 IDs. All actions for one subscription commit atomically; separate items allow partial success. Only one active bulk edit per account is accepted; conflicts409 include jobId. Read progress and failures at /v1/subscription/bulk-jobs. Jobs persist30days after completion. No release flag controls admission.
- Send numeric cents as a JSON array, not a comma-delimited string: [1999,2999,3999,4999]. The dashboard converts its comma-separated input before calling the API.
- Price lists distribute eligible distinct subscriptions evenly (1000 eligible subscriptions / four prices = 250 per price); leftover items differ by at most one. Multiple entries belonging to one subscription do not apply multiple prices. Async assignments are snapshotted once and survive retries.
- Async jobs process each subscription atomically across all requested actions. Partial success is reported through job counters and /v1/subscription/bulk-jobs/:jobId/errors. Cancellation retains completed edits.
- Synchronous mode (async absent or false) changes up to 10 000 subs inside the request and returns {done, skipped}; async mode returns 202 {jobId, job}: follow it with the bulk edit job endpoints (GET /v1/subscription/bulk-jobs/:jobId, its errors and cancel). In synchronous mode amountCentsList and actions are ignored: send amountCents.

##### `GET /v1/subscription/subs/by-order/:orderId`

**Scope** `subscriptions.read` - **Subs of an order**

Returns every sub (live and ended) of one order in the account, newest first, plus the account's products in a compact form so one can be attached to the order (the transaction modal's "Add subscription").

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | string | **yes** | The order id, URL-encoded (the route decodes it again - a literal % in an order id cannot be passed). |

**Response**

```json
{
  "rows": [
    {
      "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "owner_email": "ops@example.com",
      "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
      "email": "jane@example.com",
      "amount_cents": 6999,
      "status": "active",
      "cycle": 2,
      "retry_step": 0,
      "next_charge_at": "2026-10-19T15:07:00.000Z",
      "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
      "last_charge_at": "2026-09-19T15:07:05.210Z",
      "last_status": "rebill_success",
      "last_decline_reason": null,
      "source": "auto",
      "attached_by": "sale",
      "cancel_reason": null,
      "cancelled_at": null,
      "end_cause": null,
      "created_at": "2026-08-19T15:07:44.000Z",
      "updated_at": "2026-09-19T15:07:05.400Z",
      "subscription_name": "VIP Monthly",
      "interval_days": 30,
      "first_after_days": 3,
      "interval_value": 1,
      "interval_unit": "months",
      "first_after_value": 3,
      "first_after_unit": "days",
      "first_name": "Jane",
      "last_name": "Doe",
      "masked_card": "411111******1111",
      "storefront_url": "https://shop.example.com/checkout",
      "country": "US",
      "sale_at": "2026-08-19T15:07:44.000Z",
      "sale_amount_cents": 4999,
      "sale_mid": "MID US 01",
      "card_brand": "VISA",
      "entry_status": "scheduled",
      "entry_scheduled_at": "2026-10-19T15:07:00.000Z",
      "entry_amount_cents": 6999,
      "product_slug": "vip-bundle",
      "product_name": "VIP Bundle",
      "last_charge_amount_cents": 6999,
      "total": 1
    }
  ],
  "products": [
    {
      "id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "name": "VIP Monthly",
      "amount_cents": 6999,
      "interval_days": 30,
      "first_after_days": 3,
      "active": true,
      "attach_on": "approved"
    }
  ],
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | SubDetailRow[] of the order (see GET /v1/subscription/subs), newest first; [] when none. |
| `rows[].id` | uuid | Sub id. |
| `rows[].subscription_id` | uuid | The product; subscription_name, interval_value/unit, first_after_value/unit (and legacy interval_days / first_after_days) are copied from it. |
| `rows[].product_atri_split` | array\|null | The product's ATRI split [{id, name, pct}]: the route a Force bill's "Use original" takes (null = the account's default ATRI). |
| `rows[].order_id` | string | The original sale (card on file); transaction_id = that sale. |
| `rows[].email` | string\|null | Customer e-mail; first_name / last_name / masked_card / card_brand / storefront_url / country come from the sale. |
| `rows[].amount_cents` | integer | The price THIS sub pays (copied from the product at attach, editable per sub). |
| `rows[].status` | enum: active\|paused\|failed\|cancelled\|completed\|expired | active / paused are live; the rest are terminal. |
| `rows[].cycle` | integer | Successful charges so far; retry_step = dunning retries used on the current cycle. |
| `rows[].next_charge_at` | string (ISO-8601)\|null | Next planned charge instant (null once terminal). |
| `rows[].current_entry_id` | uuid\|null | The materialised pending charge; entry_status / entry_scheduled_at / entry_amount_cents describe it. |
| `rows[].last_charge_at` | string\|null | Last processed charge; last_status (rebill_success\|rebill_failed\|rejected\|cancelled) and last_decline_reason alongside; last_charge_amount_cents = amount of the last PAID charge. |
| `rows[].source` | enum: auto\|manual\|legacy | How the sub was created; attached_by = 'sale' \| 'sweep' \| 'legacy charge' \| the operator. |
| `rows[].end_cause` | string\|null | refund \| chargeback \| blacklist \| binscrub \| decline \| card_expired \| completed \| product_deleted \| product_inactive \| user \| sale_declined - why a terminal sub ended; cancel_reason = free text; cancelled_at stamped on every terminal state. Five more causes exist: duplicate_card (another order already sent a charge on the same card that day), superseded (a later sale replaced a recovery sub that never paid), blocked (the charge was refused before any gateway and no retry was left), error (the charge failed for a technical reason and no retry was left), rebill_flow (a Rebill Flow cancelled the sub: its action "Cancel the subscription"). |
| `rows[].sale_at` | string\|null | Original sale instant; sale_amount_cents / sale_mid likewise. |
| `rows[].product_slug` | string\|null | First product of the sale's basket (product_name alongside). |
| `rows[].created_at` | string (ISO-8601) | Attach instant (= the sale instant for reconciled subs); updated_at likewise. |
| `products` | array | [{id, name, amount_cents, interval_days, first_after_days, active, attach_on}] the account's (non-deleted) products. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `products[].first_after_value / first_after_unit` | number / string | The exact first delay (the legacy first_after_days rounds a 6-hour delay to 0). |
| `products[].interval_value / interval_unit` | number / string | The exact interval. |
| `products[].plan_mode` | string | 'simple' \| 'advanced'. |
| `products[].plan_steps` | array\|null | The intro steps (advanced), null in simple. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Never 404: an unknown order gives rows: [].
- products exposes the legacy rounded interval_days / first_after_days only - read the full product for exact units.

##### `GET /v1/subscription/subs/ids`

**Scope** `subscriptions.read` - **Ids of every sub matching filters**

Returns the ids of every sub matching the same filters as GET /v1/subscription/subs (bulk "select all matching"), newest first, capped at 10000. limit / offset / sort / dir are accepted but ignored.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `sort` | string | no | Accepted and ignored (no sort validation here): the ids come newest sub first. |
| `dir` | enum: asc\|desc | no | Accepted and ignored. |
| `limit` | integer | no | Validated like the list (1..10000, else 400) and then ignored: at most 10 000 ids come back. |
| `offset` | integer | no | Validated like the list (>= 0, else 400) and then ignored. |
| `from` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): Start of the page range (inclusive): the grain's own date. A bare day is read in tz. |
| `to` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Date): End of the page range (inclusive). A bare day is read in tz. |
| `tz` | string | no | Filter catalog (Date): IANA timezone the days and hours are read in. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "ids": [
    "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
    "3e4f5061-7b8c-4d9e-af01-2b3c4d5e6f70"
  ],
  "capped": false
}
```

| response field | type | description |
|---|---|---|
| `ids` | uuid[] | Matching sub ids, created_at desc, max 10000. |
| `capped` | boolean | true when exactly 10000 ids were returned (more may exist). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - an unknown query key or closed-vocabulary value (as the list).
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Feed the ids straight into POST /v1/subscription/subs/bulk (which also caps at 10000).
- No filter at all returns the ids of EVERY sub of the account (up to the cap).
- The same strict catalog as GET /v1/subscription/subs (the legacy names are 400s): send the list's query unchanged.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

#### Logs

The subscription charge log, and the batches and exports of the external rebill tool.

##### `GET /v1/subscription-charge-logs`

**Scope** `operations.read` - **List charge batches sent by the external rebill tool**

Lists the charge batches the external rebill tool sent with the account's keys; despite the path, this is not the subscription engine's charge log (GET /v1/subscription/transactions). Request log of the rebill charge batches (the RB tool's rebill POST /v1/charge calls) made with the account's API keys: one row per batch request with its outcome, order counts (total / approved / declined / no card) and duration.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer, 1..10000; default `50` | no | Rows per page. |
| `offset` | integer >= 0; default `0` | no | Rows to skip. |
| `outcome` | string (accepted \| invalid \| error) | no | Exact filter on the batch outcome. Not validated: another value returns no rows. |

**Response**

```json
{
  "rows": [
    {
      "id": "f0e1d2c3-b4a5-4968-8776-655443322110",
      "created_at": "2026-09-19T04:00:11.300Z",
      "remote_ip": "203.0.113.42",
      "outcome": "accepted",
      "status_code": 200,
      "order_count": 100,
      "success_count": 61,
      "declined_count": 37,
      "no_card_count": 2,
      "duration_ms": 48210,
      "error": null
    }
  ],
  "total": 812
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | rb_charge_logs rows, newest first. |
| `rows[].outcome` | enum: accepted\|invalid\|error | accepted = batch processed; invalid = rejected by validation; error = server error. |
| `rows[].status_code` | integer | HTTP status answered to the RB tool. |
| `rows[].order_count / success_count / declined_count / no_card_count` | integer\|null | Orders in the batch, approved, declined, refused for missing card-on-file. |
| `rows[].duration_ms` | integer\|null | Batch processing time. |
| `rows[].error` | string\|null | Validation / server error text. |
| `total` | integer | Total rows for paging. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: limit or offset out of range or not an integer.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `subscriptions`) when the plan lacks the subscriptions module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- These are BATCH requests (rebill POST /v1/charge calls), not per-order results; read the transactions for individual orders.
- Rows without an API key (before the per-account log) are invisible to every account.
- An empty page past the end still reports the real total.

##### `GET /v1/subscription-export-logs`

**Scope** `operations.read` - **List export sessions pulled by the external rebill tool**

Lists the export sessions the external rebill tool pulled (POST /api/exportrb-v2 pages grouped per import); it is not related to the subscription engine. Request log of the rebill export endpoint (POST /api/exportrb-v2 pulls), grouped by import session: all pages of one import (same date range, type, owner and IP, less than 5 minutes apart) collapse into one row with page count, totals and whether every page was accepted. The account's own sessions only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer, 1..10000; default `50` | no | Sessions per page. |
| `offset` | integer >= 0; default `0` | no | Sessions to skip. |
| `outcome` | string | no | Accepted and ignored (a session carries ok / error_count instead). |

**Response**

```json
{
  "rows": [
    {
      "started": "2026-09-19T03:00:02.114Z",
      "finished": "2026-09-19T03:01:40.902Z",
      "date_from": "2026-09-18",
      "date_to": "2026-09-18",
      "import_type": "daily",
      "owner": "owner@example.com",
      "remote_ip": "203.0.113.42",
      "pages": 4,
      "total_items": 1820,
      "total_exify": 1200,
      "total_not_exify": 620,
      "rows_returned": 1820,
      "duration_ms": 3410,
      "ok": true,
      "error_count": 0
    }
  ],
  "total": 61
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Sessions, newest started first. |
| `rows[].started / finished` | string (ISO-8601) | First / last page request of the session. |
| `rows[].date_from / date_to / import_type` | string\|null | Parameters of the export pulled. |
| `rows[].owner` | string\|null | Account email stamped on the request (= the caller). |
| `rows[].remote_ip` | string\|null | Caller IP of the RB tool. |
| `rows[].pages` | integer | Page requests in the session. |
| `rows[].total_items / total_exify / total_not_exify` | integer\|null | Totals reported by the export (max over pages): items, Exify-split items, in-house items. |
| `rows[].rows_returned` | integer\|null | sum of rows returned across pages. |
| `rows[].duration_ms` | integer\|null | sum of server time across pages. |
| `rows[].ok` | boolean | Every page had outcome accepted. |
| `rows[].error_count` | integer | Pages with a non-accepted outcome (unauthorized / invalid / unconfigured / error). |
| `total` | integer | Total sessions for paging. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: limit or offset out of range or not an integer.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `subscriptions`) when the plan lacks the subscriptions module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- `outcome` does nothing here (it does on GET /v1/subscription-charge-logs).
- Rows without an owner stamp are invisible to every account (the filter is the owner e-mail).
- A session is a heuristic (a 5-minute gap starts a new one): a slow import can split into two rows.
- An empty page past the end still reports the real total.

##### `GET /v1/subscription/transactions`

**Scope** `subscriptions.read` - **List subscription engine charges (charge log)**

The subscription engine's charge log (the decided charges of the account's subscriptions); the external rebill tool's batches are GET /v1/subscription-charge-logs and every POST /v1/charge request is in GET /v1/charge-logs. Pages through the account's DECIDED charges (rebill_success / rebill_failed, non-test) whose CHARGE day (v3.9.9: the day of `tz` the /transactions list files the charge on - its transaction's creation, else the decision instant) is in [from, to], joined to the original sale and card info, with server-side filters and breakdowns (summary, by brand, by card type, top 10 BINs) computed over the WHOLE filtered set, not just the page. Newest charge first. summary.charges = success + declined = the list's engine=subscription,legacy rows of the window.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | 1..10000. |
| `offset` | integer; default `0` | no | >= 0. |
| `from` | string (YYYY-MM-DD) | **yes** | First charge day (YYYY-MM-DD, a day of `tz`), inclusive. Required. |
| `to` | string (YYYY-MM-DD) | **yes** | Last charge day inclusive (YYYY-MM-DD, a day of `tz`). Required; before `from` -> 400. |
| `tz` | string; default `the account's display timezone` | no | IANA timezone of the charge days (a catalog key); absent = the account's display timezone. An unknown zone is a 400. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "id": "9b7e6d5c-1111-4f22-a333-444455556666",
      "schedule_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "order_id": "ORD-118842",
      "sub_id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "run_day": "2026-09-19",
      "scheduled_at": "2026-09-19T15:07:00.000Z",
      "amount_cents": 6999,
      "currency": "USD",
      "rebill_number": 2,
      "rebill_type": "recurring",
      "status": "rebill_success",
      "decline_reason": null,
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "mid_name": "MID US 02",
      "processed_at": "2026-09-19T15:07:05.210Z",
      "email": "jane@example.com",
      "masked_card": "411111******1111",
      "bin": "411111",
      "card_brand": "VISA",
      "card_type": "CREDIT",
      "storefront_url": "https://shop.example.com/checkout",
      "sale_amount_cents": 4999,
      "total": 0
    }
  ],
  "total": 210,
  "summary": {
    "total": 210,
    "success": 176,
    "failed": 34,
    "volume_cents": 1469790,
    "success_cents": 1231824,
    "failed_cents": 237966
  },
  "byBrand": [
    {
      "key": "VISA",
      "total": 130,
      "success": 112
    },
    {
      "key": "MASTERCARD",
      "total": 70,
      "success": 58
    }
  ],
  "byType": [
    {
      "key": "CREDIT",
      "total": 150,
      "success": 130
    },
    {
      "key": "DEBIT",
      "total": 60,
      "success": 46
    }
  ],
  "topBins": [
    {
      "key": "411111",
      "total": 40,
      "success": 36
    }
  ],
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The page of charges with sale / card joins. |
| `rows[].id` | uuid | Charge (rebill_entries) id. |
| `rows[].schedule_id` | uuid | The day the charge belongs to. |
| `rows[].order_id` | string | The original sale order id (card on file). |
| `rows[].sub_id` | uuid\|null | The customer sub this charge belongs to; null on legacy charges. |
| `rows[].run_day` | string (YYYY-MM-DD) | New York day of the slot. |
| `rows[].scheduled_at` | string (ISO-8601) | UTC instant the charge fires (minute-truncated). |
| `rows[].amount_cents` | integer | Amount to charge, in cents; currency alongside (USD). |
| `rows[].rebill_number` | integer | Cycle number of the charge (retries of a cycle keep it). |
| `rows[].rebill_type` | enum: first\|recurring\|insufficient_funds | 'insufficient_funds' = a dunning retry at the retry profile's amount. |
| `rows[].status` | enum: scheduled\|processing\|rebill_success\|rebill_failed\|cancelled\|rejected\|missed | rejected = refused by the BIN scrub before any attempt; missed = never dispatched within a day of its slot. |
| `rows[].decline_reason` | string\|null | Gateway decline text, or the internal reason for cancelled / missed / rejected. |
| `rows[].decline_normalized` | string\|null | Normalised decline (e.g. 'insufficient_funds', 'expired_card') when known. |
| `rows[].transaction_id` | uuid\|null | The transactions row created by the charge (success or decline). |
| `rows[].mid_name` | string\|null | Gateway (MID) that processed the charge; preferred_mid = the same-MID preference, if any. |
| `rows[].attempt_count` | integer | Transport-level attempts (reverts to scheduled). |
| `rows[].claimed_at` | string\|null | Claim instant while processing; claim_job = 'auto:<iso>' or 'job:<job id>'. |
| `rows[].processed_at` | string (ISO-8601)\|null | When the result was written. |
| `rows[].is_test` | boolean | Simulated charge (test schedule). |
| `rows[].email` | string\|null | Customer of the original sale (first_name / last_name alongside). |
| `rows[].masked_card` | string\|null | Masked card of the sale; bin = its first 6 digits; ccexp = expiry as stored (MMYY). |
| `rows[].card_brand` | string\|null | From bin_info: card_brand, card_type, card_country, card_issuer, card_level, card_prepaid, card_currency. |
| `rows[].storefront_url` | string\|null | Original sale storefront; country, ip_address, useragent, fbclid, ttclid likewise from the sale. |
| `rows[].purchase_at` | string (ISO-8601)\|null | Original sale instant; sale_mid / sale_amount_cents = the MID and amount of that sale. |
| `rows[].next_schedule_id` | uuid\|null | The order's next live charge elsewhere (next_schedule_name, next_run_day) - null when none. |
| `rows[].total` | integer | Per-row copy of the total in some queries (0 when the count was computed separately) - use the top-level total. |
| `total` | integer | Charges matching the filters (all pages). |
| `summary` | object | {total (every decided entry - the pager), charges (v3.9.9: success + failed = the list's engine=subscription,legacy rows), success, failed (declined with a transaction row), blocked (before any MID or no transaction row - inside total, outside charges), volume_cents (all attempted), success_cents, failed_cents} over the filtered set. |
| `byBrand` | array | [{key, total, success}] per card brand ('UNKNOWN' when bin_info has none). |
| `byType` | array | [{key, total, success}] per card type. |
| `topBins` | array | [{key, total, success}] the 10 most frequent BINs. |
| `timezone` | string | The timezone the charge days are cut in: `tz`, else the account's display timezone. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - from / to missing or not YYYY-MM-DD, a reversed range, an unknown query key (a legacy name included) or closed-vocabulary value, limit out of range.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Only rebill_success / rebill_failed charges: pending, cancelled, rejected and missed charges are NOT in this log (use the schedule entries endpoint).
- The window is on the CHARGE day (the /transactions date) in `tz`, no longer on run_day; rows are ordered by the decision instant, newest first (the run day is a column).
- `total` counts every decided entry, the blocked ones included (they are rows of this log but not of /transactions): compare summary.charges with the list.
- rows[].total is always 0 here - read the top-level total.
- BREAKING: status (success | failed | blocked) -> entryStatus (rebill_success | declined | blocked), brand / cardType take the catalog words (Visa...; the card type of the BIN), bin (prefix) -> first6, orderId -> q. `status` is now the CHARGE status of the entry's transaction (failed = declined + error). A legacy value is a 400.
- The summary and the three breakdowns are ONE pass over the filtered window (the breakdowns keep the sale's BIN data for display); the page runs beside it (W1 unfiltered ~0.95 s, device + country ~1.7-2.0 s).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

#### Retry

Retry profiles and the decline map.

##### `POST /v1/subscription/decline-map`

**Scope** `subscriptions.write` - **Map a decline text to insufficient funds**

Adds a raw gateway decline text to the account's decline map as 'insufficient_funds' (stored lower-cased and trimmed). The map decides which declines a scope 'insufficient' retry profile applies to (sub dunning and legacy retry children). Seeds the default mappings first when the account has none.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `reason` | string | **yes** | Trimmed 1..200 chars; compared case-insensitively to the exact decline text (no wildcard). |

**Request body**

```json
{
  "reason": "Insufficient Funds - retry later"
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true when the mapping was inserted. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - reason blank or > 200 chars.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `409` {"error":"This reason is already mapped"} - the lower-cased text is already in the map (whatever it maps to).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only the normalised value 'insufficient_funds' can be created through the API - other normalisations (expired_card, do_not_honor...) exist only in the seed.
- Matching is exact on the whole lower-cased decline text; a text with a different suffix is a different key.
- The decline engine's own classification (decline_normalized) wins when present; the map is the fallback for un-normalised declines.

##### `DELETE /v1/subscription/decline-map`

**Scope** `subscriptions.write` - **Remove a decline mapping**

Removes a raw decline text from the account's decline map (lower-cased / trimmed match). Idempotent: removing an unknown text still returns ok.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `reason` | string | **yes** | Trimmed 1..200 chars - the text to unmap. Sent in a JSON BODY on a DELETE (Content-Type: application/json). |

**Request body**

```json
{
  "reason": "nsf"
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true (even when nothing matched). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - reason missing - remember the body must be JSON on this DELETE.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A DELETE with a JSON body: set Content-Type: application/json, or the body is ignored and you get a 400.
- Removing a seeded default is permanent - seeding only happens while the account has ZERO mappings.
- No 404: the response does not tell whether the text existed.

##### `GET /v1/subscription/profiles`

**Scope** `subscriptions.read` - **List retry profiles**

Returns the account's retry profiles (the dunning rule a product applies after a decline: amount, delay, scope, ATRI split) together with the raw decline texts currently mapped to 'insufficient_funds' (the account's decline map, seeded with defaults on first read).

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
      "owner_email": "ops@example.com",
      "name": "NSF +48h at $49.99",
      "scope": "insufficient",
      "amount_cents": 4999,
      "delay_hours": 48,
      "atri_split": null,
      "created_at": "2026-06-01T10:00:00.000Z",
      "updated_at": "2026-06-01T10:00:00.000Z"
    }
  ],
  "declineMap": [
    "insufficient funds",
    "nsf",
    "not sufficient funds",
    "card declined - insufficient funds",
    "declined - insufficient funds",
    "insuff funds",
    "insufficient_funds"
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Retry profiles, newest first. |
| `rows[].id` | uuid | Profile id (referenced by products and schedules). |
| `rows[].name` | string | Label (not unique). |
| `rows[].scope` | enum: all\|insufficient | 'all' retries any decline; 'insufficient' only declines normalised to insufficient_funds. |
| `rows[].amount_cents` | integer | The retry charges THIS amount (a lower price point), not the sub's. |
| `rows[].delay_hours` | integer | Hours after the decline (the decline engine may shorten it). |
| `rows[].atri_split` | array\|null | ATRI split for retry charges (legacy retry children); null = the schedule's / account default. |
| `declineMap` | string[] | Lower-cased raw decline texts mapped to 'insufficient_funds' for this account. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Reading seeds the decline map with the default mappings when the account has none yet (a write on a GET).
- A retry only happens when the account setting retry_enabled is true AND the product has a retry profile; it fires ONCE per cycle (retry_step) - 'retry soon' transient retries are separate and profile-independent.

##### `POST /v1/subscription/profiles`

**Scope** `subscriptions.write` - **Create a retry profile**

Creates a retry profile for the account: the amount and delay of the single dunning retry a declined subscription charge gets, its scope (every decline or insufficient-funds only) and an optional ATRI split. Returns 201 with the row.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1..120 chars. Not unique. |
| `scope` | enum: all\|insufficient; default `all` | no | 'insufficient' = only declines whose normalised reason is insufficient_funds (per the decline map / engine). |
| `amountCents` | integer | **yes** | > 0. Amount charged by the retry, in cents. |
| `delayHours` | integer | **yes** | 1..2160 (90 days). Retry = processing time of the decline + delayHours. |
| `atriSplit` | array\|null; default `null` | no | [{id: uuid, name: <=200 chars, pct: 0..100}] max 20 items. Percentages are NOT validated to sum to 100. Stored null when omitted. |
| `atriSplit[].id` | uuid | no | ATRI of the account the retry share goes to. |
| `atriSplit[].name` | string <= 200 | no | Display name stored with the share. |
| `atriSplit[].pct` | number 0..100 | no | Share of the retries, in percent. The shares are not checked to add up to 100. |
| `steps` | array | no | v3.9.2 section 3 - the dunning ladder (docs/SUBSCRIPTIONS.md section 5.4): <= 10 ordered {after_hours (1..2160), amount_cents (positive integer, or null = the sub's own amount), scope ('nsf' \| 'soft' \| 'all')}; rebill_subs.retry_step indexes it. Given -> written as is (scope / amountCents / delayHours are then the legacy mirror of step 1); absent -> step 1 is rewritten from the legacy fields and the later steps are kept. R5.4.4: a profile used by an auto-attach product must hold a step of scope soft or all, else 422. |
| `steps[].after_hours` | integer 1..2160 | no | Hours after the decline (or the previous step) when this step retries. |
| `steps[].amount_cents` | integer > 0 \| null | no | Amount of this retry in cents; null charges the subscription's own amount. |
| `steps[].scope` | enum: nsf \| soft \| all | no | Which declines the step retries: nsf = insufficient funds only, soft = soft declines, all = every decline. |

**Request body**

```json
{
  "name": "NSF then soft",
  "scope": "insufficient",
  "amountCents": 2999,
  "delayHours": 24,
  "steps": [{"after_hours": 24, "amount_cents": 2999, "scope": "nsf"}, {"after_hours": 24, "amount_cents": null, "scope": "soft"}]
}
```

**Response**

```json
{
  "profile": {
    "id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "owner_email": "ops@example.com",
    "name": "NSF +48h at $49.99",
    "scope": "insufficient",
    "amount_cents": 4999,
    "delay_hours": 48,
    "atri_split": null,
    "created_at": "2026-09-19T14:10:00.000Z",
    "updated_at": "2026-09-19T14:10:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The inserted row (snake_case: amount_cents, delay_hours, atri_split). |
| `profile.id` | uuid | Use it as retryProfileId on a subscription product. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - blank name, amountCents <= 0, delayHours out of 1..2160, bad atriSplit.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"<validateLadder text>"} - a step is invalid, or the ladder has no soft / all step while an auto-attach product uses the profile (Law (b): a soft decline never ends a sub by itself).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- 201, not 200, on success.
- Body keys are camelCase (amountCents, delayHours, atriSplit); the response is snake_case.
- Creating a profile does nothing by itself - assign it to a product (retryProfileId) and keep the account setting retry_enabled on.
- v3.9.2 section 3: the response row carries `steps` (the ladder); the engine reads the ladder and nothing else - the legacy columns only feed the legacy child schedules.

##### `GET /v1/subscription/profiles/:id`

**Scope** `subscriptions.read` - **Get a retry profile**

Returns one retry profile of the account with the last 50 schedules that reference it (id, name, run_day, status, total_clients).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id (account-scoped). |

**Response**

```json
{
  "profile": {
    "id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "owner_email": "ops@example.com",
    "name": "NSF +48h at $49.99",
    "scope": "insufficient",
    "amount_cents": 4999,
    "delay_hours": 48,
    "atri_split": null,
    "created_at": "2026-06-01T10:00:00.000Z",
    "updated_at": "2026-06-01T10:00:00.000Z"
  },
  "schedules": [
    {
      "id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "name": "VIP Monthly - 2026-09-19",
      "run_day": "2026-09-19",
      "status": "partial",
      "total_clients": 412
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The profile row. |
| `schedules` | array | [{id, name, run_day, status, total_clients}] schedules using the profile, newest run_day first, max 50. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown id or another account's profile.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Subscription products using the profile are not listed here - filter GET /v1/subscription/subscriptions on retry_profile_id.

##### `PUT /v1/subscription/profiles/:id`

**Scope** `subscriptions.write` - **Replace a retry profile**

Full replacement of a retry profile (same schema as create - every field except scope / atriSplit is required). Products and schedules referencing the profile use the new values for their NEXT decline; nothing already planned is re-priced. Returns the updated row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id (account-scoped). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `name` | string | **yes** | Trimmed, 1..120 chars. |
| `scope` | enum: all\|insufficient; default `all` | no | Which declines the retry applies to. |
| `amountCents` | integer | **yes** | > 0, cents charged by the retry. |
| `delayHours` | integer | **yes** | 1..2160. |
| `atriSplit` | array\|null; default `null` | no | [{id, name, pct}] <= 20 items; OMITTING IT SETS null (full replace). |
| `atriSplit[].id` | uuid | no | ATRI of the account the retry share goes to. |
| `atriSplit[].name` | string <= 200 | no | Display name stored with the share. |
| `atriSplit[].pct` | number 0..100 | no | Share of the retries, in percent. The shares are not checked to add up to 100. |
| `steps` | array | no | v3.9.2 section 3 - the dunning ladder (docs/SUBSCRIPTIONS.md section 5.4): <= 10 ordered {after_hours (1..2160), amount_cents (positive integer, or null = the sub's own amount), scope ('nsf' \| 'soft' \| 'all')}; rebill_subs.retry_step indexes it. Given -> written as is (scope / amountCents / delayHours are then the legacy mirror of step 1); absent -> step 1 is rewritten from the legacy fields and the later steps are kept. R5.4.4: a profile used by an auto-attach product must hold a step of scope soft or all, else 422. |
| `steps[].after_hours` | integer 1..2160 | no | Hours after the decline (or the previous step) when this step retries. |
| `steps[].amount_cents` | integer > 0 \| null | no | Amount of this retry in cents; null charges the subscription's own amount. |
| `steps[].scope` | enum: nsf \| soft \| all | no | Which declines the step retries: nsf = insufficient funds only, soft = soft declines, all = every decline. |

**Request body**

```json
{
  "name": "NSF then soft",
  "scope": "insufficient",
  "amountCents": 2999,
  "delayHours": 24,
  "steps": [{"after_hours": 24, "amount_cents": 2999, "scope": "nsf"}, {"after_hours": 24, "amount_cents": null, "scope": "soft"}]
}
```

**Response**

```json
{
  "profile": {
    "id": "7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
    "owner_email": "ops@example.com",
    "name": "NSF +72h at $39.99",
    "scope": "insufficient",
    "amount_cents": 3999,
    "delay_hours": 72,
    "atri_split": null,
    "created_at": "2026-06-01T10:00:00.000Z",
    "updated_at": "2026-09-19T14:12:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `profile` | object | The updated row (snake_case), updated_at bumped. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a required field is missing - this is a full replace, not a patch.
- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - unknown id or another account's profile.
- `422` {"error":"<validateLadder text>"} - a step is invalid, or the ladder has no soft / all step while an auto-attach product uses the profile (Law (b): a soft decline never ends a sub by itself).
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- PUT is a FULL replace: omitting atriSplit clears it to null, omitting scope resets it to "all".
- Retry charges already materialised keep their amount and slot; the change applies to declines decided after the update.
- v3.9.2 section 3: the response row carries `steps` (the ladder); the engine reads the ladder and nothing else - the legacy columns only feed the legacy child schedules.

##### `DELETE /v1/subscription/profiles/:id`

**Scope** `subscriptions.write` - **Delete a retry profile**

Deletes a retry profile of the account. Products and schedules that referenced it get retry_profile_id = null (FK on delete set null): their declines will no longer be retried through a profile.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Profile id (account-scoped). |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- No "in use" check: products using the profile silently lose their dunning retry (a decline then ends the sub as failed, unless the engine says retry soon).
- Not reversible - recreate the profile and re-assign it to each product.

#### Settings

Subscription settings, the dispatch kill switch, rebill routing constraints and the rebill scrub BINs.

- The routing warning lines are derived in the browser from `GET /v1/subscription/routing-constraints/feasibility`.

##### `PATCH /v1/subscription/routing-constraints`

**Scope** `subscriptions.write` - **Set the rebill routing constraints**

v3.9.2 section 3 (docs/SUBSCRIPTIONS.md section 7) - writes the account's rebill routing constraints WHOLE: five dimensions (mid - category - bank - processor - company) x three states (none - never_previous - always_initial), the relaxation order and the warning threshold. The pipeline's rebill_rules stage resolves them into one pool of MIDs per recurring charge over the ATRI's candidates (relaxing rule by rule when nothing is left - a rebill is never refused by them), stamps the outcome on transactions.rebill_routing and emits rebill.routing.constrained / rebill.routing.relaxed to the customer Logs. Takes effect within 60 s on other instances, at once on this one. Returns the full settings row.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `rules` | object | **yes** | Exactly the five dimensions mid, category, bank, processor, company - each 'none' \| 'never_previous' \| 'always_initial'. Unknown dimension or state -> 400. |
| `rules.mid` | enum: none \| never_previous \| always_initial | **yes** | Rule on the gateway (MID) of a rebill: none = no constraint; never_previous = never the gateway (MID) of the previous charge; always_initial = always the gateway (MID) of the initial sale. |
| `rules.category` | enum: none \| never_previous \| always_initial | **yes** | Rule on the gateway category of a rebill: none = no constraint; never_previous = never the gateway category of the previous charge; always_initial = always the gateway category of the initial sale. |
| `rules.bank` | enum: none \| never_previous \| always_initial | **yes** | Rule on the acquiring bank of a rebill: none = no constraint; never_previous = never the acquiring bank of the previous charge; always_initial = always the acquiring bank of the initial sale. |
| `rules.processor` | enum: none \| never_previous \| always_initial | **yes** | Rule on the processor of a rebill: none = no constraint; never_previous = never the processor of the previous charge; always_initial = always the processor of the initial sale. |
| `rules.company` | enum: none \| never_previous \| always_initial | **yes** | Rule on the company of a rebill: none = no constraint; never_previous = never the company of the previous charge; always_initial = always the company of the initial sale. |
| `relax_order` | string[]; default `["category","bank","processor","company","mid"]` | no | The five dimensions, each exactly once, in the order they are DROPPED when a rebill has nothing left (first = dropped first). Default ['category','bank','processor','company','mid']. |
| `min_pool_warn` | integer; default `3` | no | 1..50 - the pool size under which the settings page warns. |
| `confirm` | boolean; default `false` | no | Required (true) when NO dimension is left at 'none': every rebill would then have to drop at least one rule. Without it the write is a 422 with requiresConfirm: true. |
| `version` | integer | no | Accepted and ignored (the dashboard sends 1): the API always stores version 1. |

**Request body**

```json
{
  "rules": {
    "mid": "none",
    "category": "never_previous",
    "bank": "none",
    "processor": "never_previous",
    "company": "always_initial"
  },
  "relax_order": [
    "category",
    "bank",
    "processor",
    "company",
    "mid"
  ],
  "min_pool_warn": 3
}
```

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "same_mid_rebill": false,
    "api_key_id": null,
    "auto_dispatch_enabled": false,
    "auto_schedule_enabled": false,
    "retry_enabled": true,
    "price_points_cents": [
      2999,
      3999,
      4999,
      5999,
      6999,
      7999,
      8999,
      9999
    ],
    "safeguard_enabled": true,
    "safeguard_min_charges": 50,
    "safeguard_min_ar_pct": 20,
    "routing_constraints": {
      "version": 1,
      "rules": {
        "mid": "none",
        "category": "never_previous",
        "bank": "none",
        "processor": "never_previous",
        "company": "always_initial"
      },
      "relax_order": [
        "category",
        "bank",
        "processor",
        "company",
        "mid"
      ],
      "min_pool_warn": 3
    },
    "created_at": "2026-05-02T09:00:00.000Z",
    "updated_at": "2026-09-19T14:15:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `settings` | object | The full settings row after the write (see GET /v1/subscription/settings); settings.routing_constraints is the normalised value written. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a dimension missing / unknown, a state outside the three, relax_order not 5 entries, min_pool_warn outside 1..50.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"<text>"} - relax_order lists a dimension twice or misses one; or {"error":"Every dimension is constrained - at least one must stay \"No constraint\", or confirm","requiresConfirm":true} when no rule is 'none' and confirm is not true.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The object is written whole (not merged): send every rule each time.
- always_initial on a dimension the initial sale has no value for (a sale that reached no MID, a company unknown on the MID) is INERT for that customer and recorded as such on the charge (rebill_routing.inert) - never a refusal.
- 'Previous charges' are the decisive MIDs of the order's earlier transactions (approved or declined), not the MIDs that lost a cascade.
- A BIN mapping rule still applies first: the constraint pool is intersected with the mapping pool by the route stage; when nothing intersects the mapping wins.
- The legacy same_mid_rebill column is not touched by this route (migration 156 set it to false; read nowhere).

##### `GET /v1/subscription/routing-constraints/feasibility`

**Scope** `subscriptions.read` - **Feasibility of a routing-constraints draft**

v3.9.2 section 3 (docs/SUBSCRIPTIONS.md section 7.5) - what a routing-constraints DRAFT (passed as query params) would leave to today's live subs (status active - paused, the 10 000 most recent), on the pipeline's own pool logic (repo.ts loadTripCascade per ATRI a product's split names, or the account's default ATRI) and the pipeline's own resolver (rebill/routingConstraints.ts resolveRoutingPool), with each sub's previous charges (decisive MIDs, five most recent) and initial sale read the way the rebill context reads them. Read-only; the settings page calls it (debounced) while the operator edits the section and renders the warning lines from it. Approximations: a sub is counted once per ATRI of its product's split (share > 0); the route's eligibility (monthly cap, brand, tried) and a BIN mapping pool are not simulated.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `mid` | enum: none\|never_previous\|always_initial; default `none` | no | The MID dimension's state of the draft. |
| `category` | enum: none\|never_previous\|always_initial; default `none` | no | The gateway-category dimension's state. |
| `bank` | enum: none\|never_previous\|always_initial; default `none` | no | The acquiring-bank dimension's state. |
| `processor` | enum: none\|never_previous\|always_initial; default `none` | no | The processor dimension's state. |
| `company` | enum: none\|never_previous\|always_initial; default `none` | no | The company dimension's state. |
| `relax_order` | string; default `category,bank,processor,company,mid` | no | Comma-separated, the five dimensions each once (the order they are dropped in). Default category,bank,processor,company,mid. |
| `min_pool_warn` | integer; default `3` | no | 1..50 - the threshold of the under_min_pool counters. |

**Response**

```json
{
  "constraints": {
    "version": 1,
    "rules": {
      "mid": "none",
      "category": "never_previous",
      "bank": "none",
      "processor": "never_previous",
      "company": "always_initial"
    },
    "relax_order": [
      "category",
      "bank",
      "processor",
      "company",
      "mid"
    ],
    "min_pool_warn": 3
  },
  "subs": 2310,
  "products": 2,
  "truncated": false,
  "excluded": {
    "gateway": 0,
    "rebill_flow": 0
  },
  "atris": [
    {
      "trip_id": "9a4c1f2e-0000-4000-8000-000000000001",
      "name": "Main Rebill",
      "is_default": false,
      "members": 15,
      "distinct": {
        "mid": 15,
        "category": 4,
        "bank": 6,
        "processor": 8,
        "company": 5
      },
      "subs": 2310,
      "empty_strict": 190,
      "relaxed_to_none": 12,
      "under_min_pool": 190,
      "initial_unknown": 135
    }
  ],
  "summary": {
    "empty_strict": 190,
    "relaxed_to_none": 12,
    "under_min_pool": 190
  }
}
```

| response field | type | description |
|---|---|---|
| `constraints` | object | The normalised draft (defaults filled in) the report was computed for. |
| `subs` | integer | Live subs considered (active + paused; capped at 10 000, then `truncated` is true). |
| `products` | integer | Subscription products of the account (their atri_split names the ATRIs). |
| `atris` | object[] | One row per ATRI a product may route to: trip_id, name, is_default, members (activated MIDs in the ATRI), distinct (distinct non-null values per dimension - a never_previous rule runs out after that many rebills), subs (live subs that may land on it), empty_strict (subs the rules as set leave NOTHING for today - the engine would relax), relaxed_to_none (subs for which every rule would be dropped - normal routing), under_min_pool (subs whose final pool holds fewer than min_pool_warn MIDs), initial_unknown (subs whose initial sale reached no MID - always_initial inert). |
| `summary` | object | empty_strict / relaxed_to_none / under_min_pool counted ONCE per sub across its ATRIs. |
| `truncated` | boolean | true when the account holds more than 10 000 live subs (the most recent were used). |
| `excluded` | object | Live subs left out of the report because their product does not route by an ATRI split: { gateway, rebill_flow }. A product in the gateway mode pins one gateway, outside the constraint pool; a product in the rebill_flow mode is decided at each charge. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a state outside the three, min_pool_warn outside 1..50.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `422` {"error":"<text>"} - relax_order lists a dimension twice, misses one or names an unknown one.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Three statements plus one pool load per ATRI: a few hundred ms on 2 300 live subs; the page debounces it (400 ms).
- A draft with every rule 'none' answers zeros - the page does not even call it then.
- No sub has two paid rebills yet (2026-09-26): 'never the same as a previous charge' bites on the sale only - the counters grow with the history.
- subs, atris and summary cover the subs of the products in the atri routing mode only; excluded counts the others.

##### `GET /v1/subscription/scrub-bins`

**Scope** `subscriptions.read` - **List the subscription engine's scrub BINs**

Lists the subscription engine's scrub BINs (refused before any gateway attempt on a subscription charge); the list synced by the external rebill tool is GET /v1/scrub-bins. DEPRECATED (v3.9 section 5 D9, removed next release): Returns the account's REBILL scrub list (card BINs whose subscription charges are refused before any gateway attempt - separate from the straight-sale BIN scrub), ordered by BIN, with the default parameters of the optimised recalculation.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b",
      "owner_email": "ops@example.com",
      "bin": "411111",
      "label": "AR 7.5% - refund 33.3% - net $-12 - 120 attempts/90d - approval rate 7.5% < 15%; refund/CB rate 33.3% >= 25%",
      "enabled": true,
      "source": "auto",
      "created_at": "2026-09-19T14:50:00.000Z"
    },
    {
      "id": "a2b3c4d5-e6f7-4089-9a0b-1c2d3e4f5a6b",
      "owner_email": "ops@example.com",
      "bin": "512345",
      "label": "Chargeback ring",
      "enabled": true,
      "source": "manual",
      "created_at": "2026-07-01T09:00:00.000Z"
    }
  ],
  "defaults": {
    "windowDays": 90,
    "minAttempts": 30,
    "minApprovals": 5,
    "arMaxPct": 15,
    "refundMaxPct": 25
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Scrub BIN rows ordered by bin. |
| `rows[].bin` | string | Exactly 6 digits. |
| `rows[].label` | string\|null | Free label; for 'auto' BINs the evidence string of the last recalculation. |
| `rows[].enabled` | boolean | Only enabled BINs are enforced at dispatch. |
| `rows[].source` | enum: manual\|csv\|auto | 'auto' rows are managed by the recalculation; manual / csv rows are never touched by it. |
| `defaults` | object | {windowDays: 90, minAttempts: 30, minApprovals: 5, arMaxPct: 15, refundMaxPct: 25} - the recalculation defaults. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- This list is independent from the straight-sale BIN scrub rules - adding a BIN here does not block new sales.

##### `POST /v1/subscription/scrub-bins`

**Scope** `subscriptions.write` - **Add scrub BINs to the subscription engine**

Adds BINs to the subscription engine's scrub list; the list synced by the external rebill tool is replaced with PUT /v1/scrub-bins. DEPRECATED (v3.9 section 5 D9, removed next release): Upserts BINs into the account's rebill scrub list (manual entry or CSV import): a new BIN is inserted with the given source and label; an existing one is re-ENABLED and its label replaced when a label is given (its source is unchanged). One 'added' history row is written per BIN.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `bins` | array | **yes** | 1..20000 items {bin: exactly 6 digits, label?: string <= 200 \| null}. |
| `source` | enum: manual\|csv; default `manual` | no | Source stamped on NEW rows (existing rows keep theirs). Friendlies transactions use source=friendlies and are excluded from Straight/Subscription. |
| `bins[].bin` | string | **yes** | Exactly 6 digits. |
| `bins[].label` | string\|null | no | Up to 200 characters. |

**Request body**

```json
{
  "bins": [
    {
      "bin": "512345",
      "label": "Chargeback ring"
    },
    {
      "bin": "601100"
    }
  ],
  "source": "manual"
}
```

**Response**

```json
{
  "upserted": 2
}
```

| response field | type | description |
|---|---|---|
| `upserted` | integer | Rows inserted or updated (an existing BIN counts as 1 too). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - a bin not matching ^\d{6}$, empty list, > 20000 items, label > 200.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- Re-adding a disabled BIN re-enables it. Re-adding an existing 'auto' BIN by hand keeps source 'auto' (only label / enabled are updated), so the next recalculation may still remove it - to make it permanent, DELETE it first, then POST it again with source 'manual'.
- Processed in chunks of 200; the response arrives after every chunk is written.
- Charges already claimed / processing are not affected; the scrub is applied at claim time for future charges.

##### `PATCH /v1/subscription/scrub-bins/:bin`

**Scope** `subscriptions.write` - **Enable or disable a scrub BIN**

DEPRECATED (v3.9 section 5 D9, removed next release): Toggles one BIN of the account's rebill scrub list: disabled BINs stay listed but are no longer enforced at dispatch. Writes an 'enabled' / 'disabled' history row.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `bin` | string | **yes** | The 6-digit BIN as stored (no format validation on the path - an unknown / malformed value is a 404). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | **yes** | true = enforce, false = keep but ignore. |

**Request body**

```json
{
  "enabled": false
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - enabled missing / not a boolean.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the BIN is not in the account's list.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- Disabling an 'auto' BIN does not protect it: the next real recalculation may delete it (if it no longer qualifies) or leave it disabled (if it still does).
- Re-adding a disabled BIN through POST re-enables it.

##### `DELETE /v1/subscription/scrub-bins/:bin`

**Scope** `subscriptions.write` - **Remove a scrub BIN**

DEPRECATED (v3.9 section 5 D9, removed next release): Deletes one BIN from the account's rebill scrub list and writes a 'removed' history row ('removed manually').

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `bin` | string | **yes** | The 6-digit BIN as stored. |

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - the BIN is not in the account's list.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- Deleting an 'auto' BIN that still meets a rule is temporary: the next non-dry recalculation adds it back. Disable it instead, or make it manual.
- Charges already rejected stay rejected (and their subs ended).

##### `GET /v1/subscription/scrub-bins/history`

**Scope** `subscriptions.read` - **Scrub BIN history**

DEPRECATED (v3.9 section 5 D9, removed next release): Returns the audit trail of the account's rebill scrub list - added / removed / enabled / disabled events with their source, reason, actor and originating run - newest first, capped at 300 rows, optionally for one BIN.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `bin` | string | no | Exactly 6 digits - restrict to one BIN. |

**Response**

```json
{
  "rows": [
    {
      "id": "b1c2d3e4-f5a6-4b7c-8d9e-0f1a2b3c4d5e",
      "bin": "411111",
      "action": "added",
      "source": "auto",
      "reason": "approval rate 7.5% < 15%; refund/CB rate 33.3% >= 25%",
      "actor": "ops@example.com",
      "run_id": "e1f2a3b4-c5d6-4e7f-8091-a2b3c4d5e6f7",
      "created_at": "2026-09-19T14:50:00.000Z"
    },
    {
      "id": "c2d3e4f5-a6b7-4c8d-9e0f-1a2b3c4d5e6f",
      "bin": "512345",
      "action": "disabled",
      "source": null,
      "reason": null,
      "actor": "ops@example.com",
      "run_id": null,
      "created_at": "2026-09-10T08:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | History rows, newest first (max 300). |
| `rows[].action` | enum: added\|removed\|enabled\|disabled\|updated | What happened. |
| `rows[].source` | string\|null | manual / csv / auto for added rows; null for enable / disable / manual removal. |
| `rows[].reason` | string\|null | The label given, the rule evidence ('auto'), 'no longer meets a scrub rule', or 'removed manually'. |
| `rows[].run_id` | uuid\|null | The recalculation run that produced the event (null for manual actions). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - bin not exactly 6 digits.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- Manual add / enable / disable / delete rows are written fire-and-forget (best effort).
- A dry run writes no history rows (only a run row).

##### `POST /v1/subscription/scrub-bins/recalculate`

**Scope** `subscriptions.write` - **Recalculate auto scrub BINs**

DEPRECATED (v3.9 section 5 D9, removed next release): Evaluates every BIN of the account's rebill history over a window (the live and completed rebill charges of the last windowDays - v3.9 section 1 APPROVAL_BASE_SQL: no test card, no CSV import, no 3DS park, no pending / duplicate row; a refusal cocoapi made before any MID is not a transaction and never an attempt) against the scrub rules - with >= minAttempts attempts: approval rate < arMaxPct, OR (>= minApprovals approvals and) refund/CB rate >= refundMaxPct, OR net <= 0 - and, unless dryRun, adds the qualifying BINs as source 'auto', refreshes the evidence labels and removes 'auto' BINs that no longer qualify. Manual / CSV BINs are never touched. Every run (dry or not) is logged in rebill_scrub_runs.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `dryRun` | boolean; default `true` | no | true = evaluate and log only, change nothing. DEFAULTS TO TRUE - send false to apply. |
| `params` | object; default `{windowDays: 90, minAttempts: 30, minApprovals: 5, arMaxPct: 15, refundMaxPct: 25}` | no | Optional {windowDays (7..365), minAttempts (1..10000), minApprovals (1..10000), arMaxPct (0..100), refundMaxPct (0..100)}. Values are rounded and CLAMPED into range (never rejected); non-numeric -> default. |
| `params.windowDays` | number; default `90` | no | History window in days (normalized to 7..365). |
| `params.minAttempts` | number; default `30` | no | Minimum attempts of a BIN to qualify (normalized to 1..10000). |
| `params.minApprovals` | number; default `5` | no | Approvals under which a BIN is scrubbed (normalized to 1..10000). |
| `params.arMaxPct` | number; default `15` | no | Approval-rate ceiling in percent (normalized to 0..100). |
| `params.refundMaxPct` | number; default `25` | no | Refund-rate ceiling in percent (normalized to 0..100). Every value is rounded to an integer; a non-number falls back to its default. |

**Request body**

```json
{
  "dryRun": false,
  "params": {
    "windowDays": 60,
    "minAttempts": 20,
    "arMaxPct": 12
  }
}
```

**Response**

```json
{
  "runId": "e1f2a3b4-c5d6-4e7f-8091-a2b3c4d5e6f7",
  "dryRun": false,
  "params": {
    "windowDays": 60,
    "minAttempts": 20,
    "minApprovals": 5,
    "arMaxPct": 12,
    "refundMaxPct": 25
  },
  "binsEvaluated": 812,
  "scrubbed": 14,
  "added": 6,
  "removed": 2,
  "keptManual": 31,
  "decisions": [
    {
      "bin": "411111",
      "attempts": 120,
      "approvals": 9,
      "gross_cents": 62991,
      "net_cents": -1240,
      "refund_count": 3,
      "refund_cents": 20997,
      "ar_pct": 7.5,
      "refund_rate_pct": 33.3,
      "loss_rate_pct": 33.3,
      "scrub": true,
      "reasons": [
        "approval rate 7.5% < 15%",
        "refund/CB rate 33.3% >= 25%",
        "net -12.40 <= 0 after fees + refunds"
      ]
    }
  ],
  "removedBins": [
    "400012",
    "522222"
  ],
  "alreadyManual": [
    "512345"
  ]
}
```

| response field | type | description |
|---|---|---|
| `runId` | uuid | The logged run (GET /v1/subscription/scrub-bins/runs/:runId). |
| `dryRun` | boolean | Echo. |
| `params` | object | The normalised parameters actually used. |
| `binsEvaluated` | integer | Distinct BINs with rebill attempts in the window. |
| `scrubbed` | integer | BINs meeting at least one rule (whatever their current state). |
| `added` | integer | Qualifying BINs not yet in the list (inserted as 'auto' unless dryRun). |
| `removed` | integer | 'auto' BINs that no longer qualify (deleted unless dryRun); removedBins lists them. |
| `keptManual` | integer | manual / csv BINs in the list (untouched); alreadyManual = qualifying BINs that are already manual / csv. |
| `decisions` | array | Per-BIN evidence (max 2000): {bin, attempts, approvals, gross_cents, net_cents, refund_count, refund_cents, ar_pct, refund_rate_pct, loss_rate_pct, scrub, reasons[]} - ONLY the scrubbed BINs and the ones being removed; non-qualifying BINs are not listed. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - dryRun not a boolean, params not an object.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- dryRun defaults to TRUE: a call without {"dryRun": false} changes nothing (but is still logged as a run).
- Out-of-range params are clamped silently (windowDays 1000 -> 365) - read `params` in the response.
- Percent thresholds are PERCENTAGES (15 = 15 %), unlike the monitoring ratios.
- Metrics come from the rebill-channel charges on the central approval base (v3.9 section 1 APPROVAL_BASE_SQL: live AND completed - test-card, CSV-imported, parked, pending and duplicate rows out): `attempts` is that population, `approvals` its approved rows, and approvals / attempts is the BIN approval rate the rule judges; refunds + chargebacks are counted with their fees. A refusal cocoapi made before any MID is not a transaction any more, so it is in no figure.
- Can take several seconds on a large history; run it from a job, not a UI hot path.

##### `GET /v1/subscription/scrub-bins/runs`

**Scope** `subscriptions.read` - **List scrub recalculation runs**

DEPRECATED (v3.9 section 5 D9, removed next release): Returns the last 50 recalculation runs of the account (dry and real), newest first, without their per-BIN details.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": "e1f2a3b4-c5d6-4e7f-8091-a2b3c4d5e6f7",
      "actor": "ops@example.com",
      "dry_run": false,
      "params": {
        "windowDays": 90,
        "minAttempts": 30,
        "minApprovals": 5,
        "arMaxPct": 15,
        "refundMaxPct": 25
      },
      "window_from": "2026-06-21T14:50:00.000Z",
      "window_to": "2026-09-19T14:50:00.000Z",
      "bins_evaluated": 812,
      "scrubbed": 14,
      "added": 6,
      "removed": 2,
      "kept_manual": 31,
      "created_at": "2026-09-19T14:50:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Run summaries, newest first (max 50). |
| `rows[].dry_run` | boolean | Whether the run applied changes. |
| `rows[].params` | object | Normalised parameters used. |
| `rows[].window_from` | string (ISO-8601) | Evaluated window [window_from, window_to]. |
| `rows[].bins_evaluated` | integer | Counters: bins_evaluated, scrubbed, added, removed, kept_manual. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- details (per-BIN decisions) are only in GET .../runs/:runId.
- No pagination beyond the 50 most recent runs.

##### `GET /v1/subscription/scrub-bins/runs/:runId`

**Scope** `subscriptions.read` - **Get a scrub recalculation run**

DEPRECATED (v3.9 section 5 D9, removed next release): Returns one recalculation run of the account with every column, including `details` - the per-BIN decisions (metrics, rates, reasons) recorded at the time.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `runId` | uuid | **yes** | Run id (account-scoped). |

**Response**

```json
{
  "run": {
    "id": "e1f2a3b4-c5d6-4e7f-8091-a2b3c4d5e6f7",
    "owner_email": "ops@example.com",
    "actor": "ops@example.com",
    "dry_run": false,
    "params": {
      "windowDays": 90,
      "minAttempts": 30,
      "minApprovals": 5,
      "arMaxPct": 15,
      "refundMaxPct": 25
    },
    "window_from": "2026-06-21T14:50:00.000Z",
    "window_to": "2026-09-19T14:50:00.000Z",
    "bins_evaluated": 812,
    "scrubbed": 14,
    "added": 6,
    "removed": 2,
    "kept_manual": 31,
    "details": [
      {
        "bin": "411111",
        "attempts": 120,
        "approvals": 9,
        "gross_cents": 62991,
        "net_cents": -1240,
        "refund_count": 3,
        "refund_cents": 20997,
        "ar_pct": 7.5,
        "refund_rate_pct": 33.3,
        "loss_rate_pct": 33.3,
        "scrub": true,
        "reasons": [
          "approval rate 7.5% < 15%",
          "refund/CB rate 33.3% >= 25%",
          "net -12.40 <= 0 after fees + refunds"
        ]
      }
    ],
    "created_at": "2026-09-19T14:50:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `run` | object | The rebill_scrub_runs row. |
| `run.details` | array | BinDecision[] (max 2000): {bin, attempts, approvals, gross_cents, net_cents, refund_count, refund_cents, ar_pct, refund_rate_pct, loss_rate_pct, scrub, reasons[]}. |
| `run.dry_run` | boolean | Dry runs record the same details without having applied anything. |

**Errors**

- `400` {"error":"A value has an invalid format."} - a path id that is not a uuid (Postgres 22P02 mapped by the global error handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Since migration 105 the charge path no longer consults this list: a subscription charge is refused by the SCRUBBING PROFILE of the ATRI it lands on (bin_rules - GET /v1/bin-profiles/:id/rules; the subscription default profile inherited this list). These routes keep reading / writing the legacy rebill_scrub_bins table for one release so RB tooling keeps its endpoints; use the profile rules instead.
- details only contain BINs that qualified or were removed in that run - not the whole population.

##### `GET /v1/subscription/settings`

**Scope** `subscriptions.read` - **Get subscription settings**

Returns the account's subscription-engine settings (rebill_settings row, created with defaults on first read): retry enabled, Safe-Guard thresholds, the stored-credential (MIT) switch and share (migration 171), the rebill routing constraints (v3.9.2 section 3, docs/SUBSCRIPTIONS.md section 7), plus the account's dispatch kill switch (globalDispatchEnabled, from account settings), the engine timezone and the caller's effective role.

*No parameters.*

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "same_mid_rebill": false,
    "api_key_id": null,
    "auto_dispatch_enabled": false,
    "auto_schedule_enabled": false,
    "retry_enabled": true,
    "price_points_cents": [
      2999,
      3999,
      4999,
      5999,
      6999,
      7999,
      8999,
      9999
    ],
    "safeguard_enabled": true,
    "safeguard_min_charges": 50,
    "safeguard_min_ar_pct": 20,
    "mit_enabled": false,
    "mit_pct": 0,
    "routing_constraints": {
      "version": 1,
      "rules": {
        "mid": "none",
        "category": "never_previous",
        "bank": "none",
        "processor": "never_previous",
        "company": "always_initial"
      },
      "relax_order": [
        "category",
        "bank",
        "processor",
        "company",
        "mid"
      ],
      "min_pool_warn": 3
    },
    "created_at": "2026-05-02T09:00:00.000Z",
    "updated_at": "2026-09-19T14:15:00.000Z"
  },
  "globalDispatchEnabled": true,
  "timezone": "America/New_York",
  "role": "admin"
}
```

| response field | type | description |
|---|---|---|
| `settings` | object | The rebill_settings row (snake_case). |
| `settings.same_mid_rebill` | boolean | LEGACY (v3.9.2 section 3, migration 156): folded into routing_constraints.rules.mid ('always_initial'); still returned, read nowhere, cannot be set any more. |
| `settings.retry_enabled` | boolean | Master switch of the dunning retry through retry profiles. |
| `settings.safeguard_enabled` | boolean | Safe-Guard: after each batch a schedule with >= safeguard_min_charges decided charges and an approval rate < safeguard_min_ar_pct is cancelled (charges cancelled, subs paused). |
| `settings.safeguard_min_charges` | integer | Decided charges before Safe-Guard may judge a day. |
| `settings.safeguard_min_ar_pct` | number | Approval-rate floor in PERCENT (0..100), e.g. 20 = 20 %. |
| `settings.mit_enabled` | boolean | Migration 171 - send subscription charges as merchant-initiated (stored credential, carrying the original sale's NMI transaction id). false (default) = every charge stays CIT. |
| `settings.mit_pct` | integer | 0..100 - the share of subscription charges that go MIT while mit_enabled. Deterministic per ORDER (hash bucket), so a subscription keeps one mode for life. A charge whose sale was not an NMI card sale (a ConvesioPay wallet MID, no original transaction id) is always CIT; a per-charge override (POST .../schedules/:id/entries/bulk action credential_mode) wins over the share. |
| `settings.routing_constraints` | object | v3.9.2 section 3 - the rebill routing constraints (docs/SUBSCRIPTIONS.md section 7.1, migration 156), always parsed: {version: 1, rules, relax_order, min_pool_warn}. An unreadable row reads as the default (every rule 'none'). |
| `settings.routing_constraints.rules` | object | One state per dimension - mid - category (gateway category) - bank (acquiring bank) - processor - company - each 'none' (no constraint) \| 'never_previous' (never the same as ANY previous charge of the order, decisive MIDs only) \| 'always_initial' (always the same as the initial sale; inert when the sale reached no MID). |
| `settings.routing_constraints.relax_order` | string[] | The order in which the rules are DROPPED when nothing is left for a rebill (first = dropped first); every dimension exactly once. The stage never refuses a rebill: with every rule dropped the charge routes normally. |
| `settings.routing_constraints.min_pool_warn` | integer | 1..50 - the pool size under which the settings page warns (feasibility). |
| `settings.api_key_id` | uuid\|null | Deprecated / unused: charges are made by the account itself. |
| `settings.auto_dispatch_enabled` | boolean | Legacy columns also present: auto_dispatch_enabled, auto_schedule_enabled, price_points_cents - no longer read by the engine. |
| `globalDispatchEnabled` | boolean | The ACCOUNT's dispatch kill switch (account settings rebill_dispatch_enabled). false = nothing of this account is charged. |
| `timezone` | string | Always 'America/New_York' - the calendar every run_day / 'today' in this API is expressed in. |
| `role` | enum: super_admin\|admin\|user | Caller's effective role (an API key is always 'admin'). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- First read inserts the settings row with defaults (a write on a GET).
- safeguard_min_ar_pct is a percentage (20), not a ratio (0.2) - unlike the monitoring endpoint's rates.
- Legacy columns (auto_dispatch_enabled, auto_schedule_enabled, price_points_cents) are returned but inert and cannot be set through PUT.
- routing_constraints is edited through PATCH /v1/subscription/routing-constraints (not through PUT /settings); the feasibility of a draft is GET /v1/subscription/routing-constraints/feasibility.
- Convesio card-on-file rebills use its S2S card adapter; this is distinct from an Apple Pay or Google Pay wallet session. A persistent unavailable override can fall back charge -> day -> original route. An explicit Force bill/charge-now pinned MID remains the only attempted route.

##### `PUT /v1/subscription/settings`

**Scope** `subscriptions.write` - **Update subscription settings**

Partially updates the account's subscription settings (only the fields present are written) and returns the full settings row. Governs the dunning retry master switch, the Safe-Guard thresholds and the stored-credential (MIT) switch + share (migration 171). The rebill routing (v3.9.2 section 3) is PATCH /v1/subscription/routing-constraints; sameMidRebill is gone (migration 156 folded it into the constraints).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `retryEnabled` | boolean | no | false disables the profile-based retry for every product (declines then end the sub as failed unless the engine asks for a transient retry). |
| `safeguardEnabled` | boolean | no | Enable Safe-Guard. |
| `safeguardMinCharges` | integer | no | 1..100000 decided charges before a day can be stopped. |
| `safeguardMinArPct` | number | no | 0..100 - approval-rate floor in percent (decimals allowed). |
| `mitEnabled` | boolean | no | Migration 171 - send subscription charges as merchant-initiated (stored credential). false = every charge stays CIT. |
| `mitPct` | integer | no | 0..100 - the share of subscription charges that go MIT while mitEnabled (deterministic per order). 0 = none. |

**Request body**

```json
{
  "retryEnabled": true,
  "safeguardEnabled": true,
  "safeguardMinCharges": 50,
  "safeguardMinArPct": 20,
  "mitEnabled": true,
  "mitPct": 50
}
```

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "same_mid_rebill": false,
    "api_key_id": null,
    "auto_dispatch_enabled": false,
    "auto_schedule_enabled": false,
    "retry_enabled": true,
    "price_points_cents": [
      2999,
      3999,
      4999,
      5999,
      6999,
      7999,
      8999,
      9999
    ],
    "safeguard_enabled": true,
    "safeguard_min_charges": 50,
    "safeguard_min_ar_pct": 20,
    "mit_enabled": false,
    "mit_pct": 0,
    "routing_constraints": {
      "version": 1,
      "rules": {
        "mid": "none",
        "category": "never_previous",
        "bank": "none",
        "processor": "never_previous",
        "company": "always_initial"
      },
      "relax_order": [
        "category",
        "bank",
        "processor",
        "company",
        "mid"
      ],
      "min_pool_warn": 3
    },
    "created_at": "2026-05-02T09:00:00.000Z",
    "updated_at": "2026-09-19T14:15:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `settings` | object | The full settings row after the update (see GET). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - non-boolean flag, safeguardMinCharges out of 1..100000, safeguardMinArPct out of 0..100, mitPct not an integer in 0..100.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Despite PUT this is a PATCH: absent fields are untouched; an empty body {} is valid and returns the unchanged settings.
- Body is camelCase (safeguardMinArPct), response is snake_case (safeguard_min_ar_pct).
- The dispatch kill switch is NOT here - use PATCH /v1/subscription/settings/global.
- Safe-Guard evaluates after each dispatch batch; changing thresholds affects days currently running.
- sameMidRebill is no longer accepted (v3.9.2 section 3): set routing_constraints.rules.mid = 'always_initial' through PATCH /v1/subscription/routing-constraints instead.
- Saving drops the per-account credential-mode cache (rebill/credentialMode.ts): the very next subscription charge reads the new mitEnabled / mitPct. The mode a charge ended up on is transactions.credential_mode - the `credentialMode` filter of the unified catalog (mit | cit).

##### `PATCH /v1/subscription/settings/global`

**Scope** `subscriptions.write` - **Set the account dispatch kill switch**

Turns the ACCOUNT's subscription dispatch on or off (account settings rebill_dispatch_enabled). Off: the auto dispatcher skips every schedule of the account, running manual jobs pause themselves ('Subscription dispatch is OFF for this account') and POST .../jobs answers 423. On: dispatch resumes on the next tick (paused jobs must be resumed by hand).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | **yes** | true = dispatch allowed, false = nothing is charged for this account. |

**Request body**

```json
{
  "enabled": false
}
```

**Response**

```json
{
  "globalDispatchEnabled": false
}
```

| response field | type | description |
|---|---|---|
| `globalDispatchEnabled` | boolean | The value just written. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - enabled missing or not a boolean.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Despite the name 'global' it is PER ACCOUNT - it never touches another account's dispatch.
- Turning it off does not cancel anything: charges keep their slots and fire as soon as it is back on (overdue ones are re-spread over the remaining day, missed ones after a day are re-planned by the engine).
- Jobs paused by the switch stay 'paused' after re-enabling - POST /v1/subscription/jobs/:jobId/resume them.
- Also settable through the general account settings endpoint (rebillDispatchEnabled).

#### Metrics

The subscription metric catalogue and the background metric calculations.

##### `GET /v1/subscription/metrics/catalogue`

**Scope** `subscriptions.read` - **Get the subscription metric catalogue**

Definition of every subscription metric key the Overview, tabs and export use: key, block (M1 to M17), kind (snapshot / flow / rate / window / derived), unit, Total rule in words, label, formula, definition, and whether the key heads a card, is an export column or is computed at read time. Synchronous.

*No parameters.*

**Response**

```json
{
  "metrics": [
    {
      "key": "active",
      "block": "M1",
      "kind": "snapshot",
      "unit": "count",
      "total": "value at range end (last day)",
      "label": "Scheduled subscriptions",
      "formula": "COUNT(subscriptions WHERE state_at(t) = 'active')",
      "definition": "Subscriptions enrolled in a schedule, including those whose first charge has never been attempted. Payment outcomes do not activate a subscription. Collection pauses do not remove membership.",
      "card": true,
      "export": true,
      "live": false
    },
    {
      "key": "at_risk_mrr",
      "block": "M6",
      "kind": "snapshot",
      "unit": "minor",
      "total": "value at range end (last day)",
      "label": "At-risk MRR",
      "formula": "sum of mrr(sub) over state_at(t) = past_due",
      "definition": "The MRR of the past-due subscriptions (shown apart; MRR_INCLUDES_PAST_DUE = false).",
      "card": false,
      "export": true,
      "live": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `metrics` | object[] | [{key, block, kind, unit, total, label, formula, definition, card, export, live}] in catalogue order. live is true for the read-time keys (mrr_collectible, approval_rebill_30d), which are never stored as daily rows. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- The keys are the property names of the Overview series, total and export values. Read-time keys (live: true) exist only in those payloads, never as stored daily rows.
- The MRR card heads mrr_collectible (contract MRR times the trailing 30-day rebill approval); mrr is the contract MRR used by the invariants, ARPU and MRR movements.
- Labels and definitions follow the current definition version (the `basis` suffix of a calculation); read them here instead of hard-coding them.

##### `GET /v1/subscription/metrics/jobs`

**Scope** `subscriptions.read` - **List subscription metrics jobs**

Lists up to 20 subscription statistics jobs of the caller, queued and running first, then newest first; finished jobs stay listed about 30 days after their expiry.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "6a2f0c9e-3b7d-4e18-a5c4-9d1e2f3a4b50",
      "kind": "overview",
      "request_id": "1c7e9a2b-4d3f-4a6e-8b5c-0f2d7e9a1b36",
      "from": "2026-10-22",
      "to": "2026-11-20",
      "tz": "America/New_York",
      "basis": "America/New_York",
      "status": "running",
      "processed": 0,
      "total": 1,
      "succeeded": 0,
      "skipped": 0,
      "failed": 0,
      "cancel_requested": false,
      "error": null,
      "errors": [],
      "snapshot_at": null,
      "created_at": "2026-11-20T14:00:00.000Z",
      "updated_at": "2026-11-20T14:00:02.000Z",
      "finished_at": null,
      "expires_at": "2026-11-21T14:00:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | At most 20 jobs (no result payload). |
| `jobs[].id` | string (uuid) | Job id. |
| `jobs[].kind` | enum: manual \| daily \| catchup \| overview \| tabs \| invariants | manual = recompute and store the account's daily subscription metrics for a day range; overview / tabs / invariants = build the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring in the background; daily and catchup are the automatic jobs. |
| `jobs[].request_id` | string (uuid) | The requestId sent at creation (system-generated for automatic jobs). |
| `jobs[].from` | string (YYYY-MM-DD) | First day of the range, in the account timezone. |
| `jobs[].to` | string (YYYY-MM-DD) | Last day of the range (never after today). |
| `jobs[].tz` | string | Account timezone frozen at creation. |
| `jobs[].basis` | string | Metric day basis frozen at creation (derived from tz). |
| `jobs[].status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `jobs[].processed` | integer | Days (manual) or steps committed so far. |
| `jobs[].total` | integer | Steps of the job: the number of days plus one final step (1 for a report job). |
| `jobs[].succeeded` | integer | Same value as processed. |
| `jobs[].skipped` | integer | Always 0. |
| `jobs[].failed` | integer | 1 when status is failed, else 0. |
| `jobs[].cancel_requested` | boolean | True once a cancel was requested; a running job stops at its next checkpoint. |
| `jobs[].error` | string \| null | Failure reason. |
| `jobs[].errors` | object[] | Empty, or one entry {itemId (the day being processed, or "Validation"), reason} when error is set. |
| `jobs[].snapshot_at` | string \| null | When the result was computed. |
| `jobs[].created_at` | string (ISO 8601) | Creation time. |
| `jobs[].updated_at` | string (ISO 8601) | Last progress time. |
| `jobs[].finished_at` | string \| null | End time (success), else null. |
| `jobs[].expires_at` | string (ISO 8601) | When the result stops being readable: 24 hours after creation, reset to 24 hours after the last progress write. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"API key permissions changed"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- No pagination.
- A job is visible to the caller that created it (the same API key, or the same login) and, for every caller of the account, the automatic daily and catch-up jobs; another key's jobs answer 404.

##### `POST /v1/subscription/metrics/jobs`

**Scope** `subscriptions.write` - **Queue a subscription metrics calculation**

Queues a background subscription statistics job and answers 202 {jobId, job}. kind overview, tabs or invariants builds the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring for a long range without holding the request open; kind manual recomputes and stores the account's daily subscription metrics day by day (the recompute of Subscriptions > Monitoring). Read the result with GET /v1/subscription/metrics/jobs/:id/result once status is success.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Your idempotency key. Resending the same requestId with the same input returns the existing job (202 again); the same requestId with a different input answers 409. |
| `kind` | enum: manual \| overview \| tabs \| invariants | **yes** | overview / tabs / invariants = a background build of the matching report; manual = recompute and store the daily metrics of every day of the range. |
| `query` | object | **yes** | The day range. Send {} for the default range. |
| `query.from` | string (YYYY-MM-DD) | no | First day, a real calendar day. Default: to minus (days - 1); for kind manual, the account's first subscription day. |
| `query.to` | string (YYYY-MM-DD); default `today` | no | Last day, a real calendar day; a day after today (account timezone) is clamped to today. |
| `query.days` | integer; default `30` | no | Range length used when from is absent, 1 to 731. |

**Request body**

```json
{
  "requestId": "1c7e9a2b-4d3f-4a6e-8b5c-0f2d7e9a1b36",
  "kind": "overview",
  "query": {
    "days": 30
  }
}
```

**Response**

```json
{
  "jobId": "6a2f0c9e-3b7d-4e18-a5c4-9d1e2f3a4b50",
  "job": {
    "id": "6a2f0c9e-3b7d-4e18-a5c4-9d1e2f3a4b50",
    "kind": "overview",
    "request_id": "1c7e9a2b-4d3f-4a6e-8b5c-0f2d7e9a1b36",
    "from": "2026-10-22",
    "to": "2026-11-20",
    "tz": "America/New_York",
    "basis": "America/New_York",
    "status": "queued",
    "processed": 0,
    "total": 1,
    "succeeded": 0,
    "skipped": 0,
    "failed": 0,
    "cancel_requested": false,
    "error": null,
    "errors": [],
    "snapshot_at": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:00.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T14:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | string (uuid) | The job id. |
| `job` | object | The job (HTTP 202). |
| `job.id` | string (uuid) | Job id. |
| `job.kind` | enum: manual \| daily \| catchup \| overview \| tabs \| invariants | manual = recompute and store the account's daily subscription metrics for a day range; overview / tabs / invariants = build the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring in the background; daily and catchup are the automatic jobs. |
| `job.request_id` | string (uuid) | The requestId sent at creation (system-generated for automatic jobs). |
| `job.from` | string (YYYY-MM-DD) | First day of the range, in the account timezone. |
| `job.to` | string (YYYY-MM-DD) | Last day of the range (never after today). |
| `job.tz` | string | Account timezone frozen at creation. |
| `job.basis` | string | Metric day basis frozen at creation (derived from tz). |
| `job.status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `job.processed` | integer | Days (manual) or steps committed so far. |
| `job.total` | integer | Steps of the job: the number of days plus one final step (1 for a report job). |
| `job.succeeded` | integer | Same value as processed. |
| `job.skipped` | integer | Always 0. |
| `job.failed` | integer | 1 when status is failed, else 0. |
| `job.cancel_requested` | boolean | True once a cancel was requested; a running job stops at its next checkpoint. |
| `job.error` | string \| null | Failure reason. |
| `job.errors` | object[] | Empty, or one entry {itemId (the day being processed, or "Validation"), reason} when error is set. |
| `job.snapshot_at` | string \| null | When the result was computed. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last progress time. |
| `job.finished_at` | string \| null | End time (success), else null. |
| `job.expires_at` | string (ISO 8601) | When the result stops being readable: 24 hours after creation, reset to 24 hours after the last progress write. |

**Errors**

- `400` {"error":"Invalid calculation","details":<zod flatten()>} for an invalid body; {"error":"from <day> is after to <day>"}; {"error":"range too long: <n> days (max 731)"}; {"error":"At most 731 days per calculation"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"API key permissions changed"} when the key was deactivated, its owner banned or the account changed.
- `404` {"error":"No subscription on this account"} for kind manual when the account has no subscription.
- `409` {"error":"Request ID belongs to a different calculation"}; {"error":"Three subscription calculations are already running. Cancel one or wait."}
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Background subscription statistics are disabled"} when background jobs are off on this deployment.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- Strict body: an unknown field is a 400. query is required (send {} for the default 30 days).
- At most 731 days; from after to is a 400.
- At most three queued or running calculations per account (any caller): a fourth answers 409. One job runs at a time per account; the others wait.
- Same requestId and same input returns the existing job (also while it is still running). After an uncertain answer, resend with the same requestId instead of a new one.
- kind manual on an account with no subscription answers 404.
- The timezone and day basis are frozen at creation; a later change of the account timezone does not affect a queued job.
- A job is visible to the caller that created it (the same API key, or the same login) and, for every caller of the account, the automatic daily and catch-up jobs; another key's jobs answer 404.
- Scope subscriptions.write for every kind, including the read-only computations overview, tabs and invariants: the dashboard GET shortcuts that queued them with subscriptions.read are not public.

##### `GET /v1/subscription/metrics/jobs/:id`

**Scope** `subscriptions.read` - **Get a subscription metrics job**

Reads one job's progress without its result payload. Poll it until status is success, failed or cancelled.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. A value that is not a uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "6a2f0c9e-3b7d-4e18-a5c4-9d1e2f3a4b50",
    "kind": "overview",
    "request_id": "1c7e9a2b-4d3f-4a6e-8b5c-0f2d7e9a1b36",
    "from": "2026-10-22",
    "to": "2026-11-20",
    "tz": "America/New_York",
    "basis": "America/New_York",
    "status": "running",
    "processed": 0,
    "total": 1,
    "succeeded": 0,
    "skipped": 0,
    "failed": 0,
    "cancel_requested": false,
    "error": null,
    "errors": [],
    "snapshot_at": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:02.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T14:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job. |
| `job.id` | string (uuid) | Job id. |
| `job.kind` | enum: manual \| daily \| catchup \| overview \| tabs \| invariants | manual = recompute and store the account's daily subscription metrics for a day range; overview / tabs / invariants = build the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring in the background; daily and catchup are the automatic jobs. |
| `job.request_id` | string (uuid) | The requestId sent at creation (system-generated for automatic jobs). |
| `job.from` | string (YYYY-MM-DD) | First day of the range, in the account timezone. |
| `job.to` | string (YYYY-MM-DD) | Last day of the range (never after today). |
| `job.tz` | string | Account timezone frozen at creation. |
| `job.basis` | string | Metric day basis frozen at creation (derived from tz). |
| `job.status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `job.processed` | integer | Days (manual) or steps committed so far. |
| `job.total` | integer | Steps of the job: the number of days plus one final step (1 for a report job). |
| `job.succeeded` | integer | Same value as processed. |
| `job.skipped` | integer | Always 0. |
| `job.failed` | integer | 1 when status is failed, else 0. |
| `job.cancel_requested` | boolean | True once a cancel was requested; a running job stops at its next checkpoint. |
| `job.error` | string \| null | Failure reason. |
| `job.errors` | object[] | Empty, or one entry {itemId (the day being processed, or "Validation"), reason} when error is set. |
| `job.snapshot_at` | string \| null | When the result was computed. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last progress time. |
| `job.finished_at` | string \| null | End time (success), else null. |
| `job.expires_at` | string (ISO 8601) | When the result stops being readable: 24 hours after creation, reset to 24 hours after the last progress write. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"API key permissions changed"}.
- `404` {"error":"Not found"} when id is not a uuid; {"error":"Calculation not found"} when the job is not visible to the caller.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- Progress is a count of committed days or steps, never an estimated percentage.
- A job is visible to the caller that created it (the same API key, or the same login) and, for every caller of the account, the automatic daily and catch-up jobs; another key's jobs answer 404.

##### `POST /v1/subscription/metrics/jobs/:id/cancel`

**Scope** `subscriptions.write` - **Cancel a subscription metrics job**

Requests cancellation and returns the job. A queued job becomes cancelled at once; a running job keeps status running with cancel_requested true until the worker stops at its next checkpoint (days already committed stay committed). A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. A value that is not a uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "6a2f0c9e-3b7d-4e18-a5c4-9d1e2f3a4b50",
    "kind": "overview",
    "request_id": "1c7e9a2b-4d3f-4a6e-8b5c-0f2d7e9a1b36",
    "from": "2026-10-22",
    "to": "2026-11-20",
    "tz": "America/New_York",
    "basis": "America/New_York",
    "status": "running",
    "processed": 0,
    "total": 1,
    "succeeded": 0,
    "skipped": 0,
    "failed": 0,
    "cancel_requested": true,
    "error": null,
    "errors": [],
    "snapshot_at": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:02.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T14:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after the request. |
| `job.id` | string (uuid) | Job id. |
| `job.kind` | enum: manual \| daily \| catchup \| overview \| tabs \| invariants | manual = recompute and store the account's daily subscription metrics for a day range; overview / tabs / invariants = build the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring in the background; daily and catchup are the automatic jobs. |
| `job.request_id` | string (uuid) | The requestId sent at creation (system-generated for automatic jobs). |
| `job.from` | string (YYYY-MM-DD) | First day of the range, in the account timezone. |
| `job.to` | string (YYYY-MM-DD) | Last day of the range (never after today). |
| `job.tz` | string | Account timezone frozen at creation. |
| `job.basis` | string | Metric day basis frozen at creation (derived from tz). |
| `job.status` | enum: queued \| running \| success \| failed \| cancelled | Lifecycle status. |
| `job.processed` | integer | Days (manual) or steps committed so far. |
| `job.total` | integer | Steps of the job: the number of days plus one final step (1 for a report job). |
| `job.succeeded` | integer | Same value as processed. |
| `job.skipped` | integer | Always 0. |
| `job.failed` | integer | 1 when status is failed, else 0. |
| `job.cancel_requested` | boolean | True once a cancel was requested; a running job stops at its next checkpoint. |
| `job.error` | string \| null | Failure reason. |
| `job.errors` | object[] | Empty, or one entry {itemId (the day being processed, or "Validation"), reason} when error is set. |
| `job.snapshot_at` | string \| null | When the result was computed. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last progress time. |
| `job.finished_at` | string \| null | End time (success), else null. |
| `job.expires_at` | string (ISO 8601) | When the result stops being readable: 24 hours after creation, reset to 24 hours after the last progress write. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"API key permissions changed"}.
- `404` {"error":"Not found"} when id is not a uuid; {"error":"Calculation not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- No body is read.
- Poll GET /v1/subscription/metrics/jobs/:id: a running job ends as cancelled once the worker notices.
- A job is visible to the caller that created it (the same API key, or the same login) and, for every caller of the account, the automatic daily and catch-up jobs; another key's jobs answer 404.

##### `GET /v1/subscription/metrics/jobs/:id/result`

**Scope** `subscriptions.read` - **Get a subscription metrics job result**

Returns the stored result of a successful job, as is: for overview / tabs / invariants the body of the Overview, the Retention / Approval / Revenue tabs or the invariants check of Subscriptions > Monitoring for the job's range; for manual {days, from, to, tz, invariants}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. A value that is not a uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "days": 30,
  "from": "2026-10-22",
  "to": "2026-11-20",
  "tz": "America/New_York",
  "invariants": {
    "ok": true
  }
}
```

| response field | type | description |
|---|---|---|
| `(overview / tabs / invariants)` | object | The report body of the matching synchronous route, unchanged. |
| `days` | integer | manual: days recomputed. |
| `from` | string | manual: first day. |
| `to` | string | manual: last day. |
| `tz` | string | manual: timezone used. |
| `invariants` | object | manual: the invariants check of the last 30 days of the range (ok is true here; a failed check fails the job with error "Subscription statistic invariants failed; committed days are retained. Inspect the invariants report."). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"API key permissions changed"}.
- `404` {"error":"Not found"} when id is not a uuid; {"error":"Calculation not found"}.
- `409` {"error":"Calculation is not ready"} while the job is not success.
- `410` {"error":"Calculation expired. Refresh the report."}
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- 409 until status is success (also for a failed or cancelled job); 410 after expires_at (24 hours): submit a new job.
- A job is visible to the caller that created it (the same API key, or the same login) and, for every caller of the account, the automatic daily and catch-up jobs; another key's jobs answer 404.

##### `GET /v1/subscription/metrics/jobs/capability`

**Scope** `subscriptions.read` - **Subscription metrics job capability**

Says whether background subscription metric calculations can be submitted with POST /v1/subscription/metrics/jobs. Read-only; the answer is the same for every account.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | False when background jobs are disabled on this deployment (then POST answers 503). True when they run and the job storage exists. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Required storage for subscription metrics is unavailable. Complete the current database migrations.","requestId":"<id>"} when background jobs run but the job storage is missing.

**Gotchas**

- When background jobs run but the job storage is missing, the answer is a 503 {"error":"Required storage for subscription metrics is unavailable. Complete the current database migrations.","requestId":"<id>"} (a missing migration), not enabled:false.

### Customers

The Customers menu: customers, refunds and disputes (the Refund requests page), and the blacklist.

#### Customers

The customers (shoppers): list, summary, timeline, notes, 3-D Secure history, subscriptions, flags, exports and bulk actions.

- CSV: `GET /v1/customers/export` returns the file. PDF: built in the browser from the rows of `GET /v1/customers/export-pdf-v2`.

##### `GET /v1/customers`

**Scope** `customers.read` - **List customers**

Lists customers: the shoppers of the account, one row per lower-cased e-mail with at least one live charge (a customer is a shopper, never an account; clientId in the partner routes names an account). One row per customer of the account (a customer = one lower-cased e-mail with at least one live charge) with its figures over the charges matching the filters, its lifetime facts and its 3DS summary, plus the whole-list total, the totals and the account timezone. Every figure equals the transactions list with the same filters plus customerEmail=<e-mail> and the figure's status or refund kind, from the row's drill_from day to today. Charge-level keys (Transaction, Routing, Card, Customer, Subscription, Schedule and Refund groups, and from / to) narrow the FIGURES: a customer is listed when at least one of its charges matches (or, with a range, a refund event of a matching charge falls in it), and orders ... net count only the matching charges. Customer axes (customerEmail, customerThreeDs, clientBlacklisted, clientLiveSub, clientOrdersMin/Max, clientLtvMin/Max, clientFirstFrom/To, clientLastFrom/To) filter the customer's LIFETIME facts over its live charges, whatever the other filters.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | no | Start of the range (inclusive). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). Charge-level: reads the charge date (the refund event date when `refund` is set). A reversed from/to pair is a 400 "to is before from". |
| `to` | string | no | End of the range (inclusive; a bare day covers its last millisecond). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `tz` | string | no | IANA timezone the bare days and hours are read in, max 64 chars. Default America/New_York. An unknown zone is a 400 "not a known IANA timezone". |
| `hour` | string | no | CSV of hours 0..23 in tz (max 200 chars). Needs a valid tz, otherwise 400 "hour needs a valid tz". |
| `status` | string (CSV enum) | no | Charge status, CSV of approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca. failed = declined + error; completed = every charge with an outcome. |
| `source` | string (CSV enum) | no | CSV of sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell (max 100 chars). straight = sale + recovery, subscription = rebill. |
| `pass` | string (CSV enum) | no | initial\|cascade. |
| `method` | string (CSV enum) | no | card\|wallet\|wire. |
| `population` | string (CSV enum) | no | live\|test\|imported. Absent = live charges; set = the same re-target as the transactions list. |
| `credentialMode` | string (CSV enum) | no | Wire charges: mit\|cit. |
| `threeDs` | string (CSV enum) | no | 3DS outcome, CSV of applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only. |
| `declineCategory` | string | no | Decline-engine category, CSV (max 1000 chars). |
| `declineSeverity` | string (CSV enum) | no | soft\|hard. |
| `amountMin` | string (integer cents) | no | Amount >= this many cents (1 to 12 digits). |
| `amountMax` | string (integer cents) | no | Amount <= this many cents (1 to 12 digits). A max below amountMin is a 400. |
| `pricePoint` | string (CSV enum) | no | Price bucket, CSV of '1. < $25', '2. $25-49', '3. $50-74', '4. $75-99', '5. $100-149', '6. $150-199', '7. $200+'. |
| `product` | string | no | Basket product name, slug or reference, CSV (max 4000 chars). |
| `productSlug` | string | no | Basket product slug, CSV (max 4000 chars). |
| `productKey` | string | no | Product per store, CSV of <host>\|<ref> (max 4000 chars). |
| `currency` | string | no | CSV of 3-letter ISO 4217 codes (max 200 chars). |
| `gatewayTxnId` | string | no | Gateway transaction id, exact, CSV (max 4000 chars). |
| `authCode` | string | no | Auth code of any attempt, exact, CSV (max 1000 chars). |
| `descriptor` | string | no | Descriptor contains this text: the sent statement descriptor, the MID soft descriptor or name (max 128 chars). |
| `accountId` | string | no | Gateway: CSV of MID UUIDs, wallet:<walletProviderId>, wire:<bankAccountId> or none (max 4000 chars). |
| `walletProvider` | string | no | CSV of wallet provider UUIDs (alias of accountId=wallet:<id>). |
| `gatewayType` | string | no | a gateway type (the gatewayType values returned by GET /v1/accounts), CSV (max 100 chars). |
| `category` | string | no | CSV of category UUIDs: any category of the final MID. |
| `primaryCategory` | string | no | CSV of category UUIDs: the primary category of the final MID. |
| `atri` | string | no | CSV of ATRI UUIDs reached. |
| `atriFinal` | string | no | CSV of ATRI UUIDs the order ended on. |
| `processor` | string | no | CSV of processor UUIDs, or none. |
| `acquiringBank` | string | no | CSV of acquiring bank UUIDs, or none. |
| `company` | string | no | CSV of company UUIDs, or none. |
| `gatewayMcc` | string | no | Final MID MCC, CSV (max 1000 chars). |
| `gatewayBin` | string | no | Final MID acquirer BIN, CSV (max 1000 chars). |
| `brand` | string | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other, CSV (max 200 chars). |
| `paysource` | string | no | APPLEPAY / GOOGLEPAY (wallet payload), CSV (max 100 chars). |
| `funding` | string | no | Prepaid / Debit / Credit / Charge card (or a wallet), CSV (max 200 chars). |
| `cardType` | string | no | BIN card type (or a wallet), CSV (max 200 chars). |
| `cardLevel` | string | no | BIN card level (or a wallet), CSV (max 4000 chars). |
| `issuer` | string | no | Issuing bank, RFC 4180 CSV (max 4000 chars). |
| `bin` | string | no | CSV of 6-digit BINs or a wallet label (Apple Pay, Google Pay), max 4000 chars. Another value is a 400 "unknown value". |
| `first6` | string | no | Card prefix, 1 to 6 digits. |
| `last4` | string | no | Card suffix, 1 to 4 digits. |
| `country` | string | no | Billing country (ISO-2), CSV (max 2000 chars). |
| `storefront` | string | no | Store host bucket or (direct), CSV (max 4000 chars). The value __no_store__ selects canonical standalone orders (immutable order context), not a blank URL. |
| `traffic` | string | no | Traffic source or (direct/organic), CSV (max 2000 chars). |
| `utmSource` | string | no | UTM source, case-insensitive, CSV (max 4000 chars). |
| `utmCampaign` | string | no | UTM campaign, case-insensitive, CSV (max 4000 chars). |
| `device` | string | no | Mobile / Tablet / Desktop, CSV (max 200 chars). |
| `os` | string | no | Operating system, CSV (max 200 chars). |
| `browser` | string | no | Browser, CSV (max 200 chars). |
| `ipType` | string (CSV enum) | no | IPv4\|IPv6. |
| `ip` | string | no | CSV of customer IPs (max 2000 chars). |
| `email` | string | no | Charge e-mail contains this text (max 200 chars). |
| `phone` | string | no | Phone contains this text (max 40 chars). |
| `firstName` | string | no | First name contains this text (max 120 chars). |
| `lastName` | string | no | Last name contains this text (max 120 chars). |
| `customerEmail` | string | no | Client axis: CSV of exact e-mails, case-insensitive (max 4000 chars); a value without @ is dropped. |
| `customerThreeDs` | string (CSV enum) | no | Client axis: customer authentication inventory now, CSV of with-ready\|without-ready\|single\|double\|ready-for-rebill (single / double count proofs obtained, used ones included). |
| `clientBlacklisted` | string (enum) | no | Client axis: true\|false. Blacklisted by e-mail or by a card the customer paid with. |
| `clientLiveSub` | string (enum) | no | Client axis: true\|false. Has a live (active or paused) subscription. |
| `clientOrdersMin` | string (integer) | no | Client axis: lifetime distinct orders >= (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Client axis: lifetime distinct orders <= (1 to 12 digits). |
| `clientLtvMin` | string (integer cents) | no | Client axis: lifetime gross >= this many cents (1 to 12 digits). |
| `clientLtvMax` | string (integer cents) | no | Client axis: lifetime gross <= this many cents (1 to 12 digits). |
| `clientFirstFrom` | string | no | Client axis: first seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientFirstTo` | string | no | Client axis: first seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastFrom` | string | no | Client axis: last seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastTo` | string | no | Client axis: last seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `checkout` | string | no | CSV of checkout UUIDs at sale, or none for unattributed / legacy charges. |
| `flow` | string | no | CSV of flow UUIDs of this account (from the immutable checkout session version), or none for direct checkout / legacy. A malformed value is a 400 "Invalid flow filter"; a flow of another account or an unknown one is a 400 "Unknown flow filter". |
| `affiliate` | string | no | CSV of affiliate UUIDs of this account (immutable payment attribution), or none for no affiliate. A malformed value is a 400 "Invalid affiliate filter"; an unknown or foreign id is a 400 "Unknown affiliate filter". Disabled affiliates of the account stay valid. |
| `subscription` | string | no | CSV of subscription product UUIDs. |
| `cycle` | string | no | CSV of charge cycles (1 to 3 digits each; 0 = the straight sale), max 200 chars. |
| `cycleMin` | string (integer) | no | Charge cycle >= (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Charge cycle <= (1 to 6 digits). |
| `engine` | string (CSV enum) | no | subscription\|legacy\|external. |
| `subStatus` | string (CSV enum) | no | Sub status, CSV of active\|paused\|failed\|cancelled\|completed\|expired. |
| `attachedBy` | string (CSV enum) | no | auto\|manual\|legacy\|optin. |
| `due` | string (enum) | no | Next charge: overdue\|24h\|7d (one value). |
| `endCause` | string | no | Sub end cause, CSV (max 1000 chars). |
| `subCreatedFrom` | string | no | Sub created from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subCreatedTo` | string | no | Sub created to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedFrom` | string | no | Sub ended from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedTo` | string | no | Sub ended to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `schedule` | string | no | CSV of schedule (day) UUIDs. |
| `scheduleStatus` | string (CSV enum) | no | Schedule status, CSV of scheduled\|processing\|partial\|paused\|done\|cancelled. |
| `scheduleType` | string (CSV enum) | no | subscription\|auto\|manual. |
| `dayFrom` | string | no | Schedule run day from, YYYY-MM-DD. |
| `dayTo` | string | no | Schedule run day to, YYYY-MM-DD. |
| `entryStatus` | string (CSV enum) | no | Charge state of the schedule entry, CSV of scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed. |
| `entryReason` | string | no | Decline reason of the schedule entry, CSV (max 4000 chars). |
| `refund` | string (CSV enum) | no | Refund event kind, CSV of refund\|chargeback\|rdr\|ethoca. Narrows the refund figures to those events and dates the range on the refund event. |
| `refundBasis` | string (enum) | no | refund (default) \| charge: date the refund events by the refund or by the charge. |
| `refunded` | string (CSV enum) | no | Refunded state flag: true\|false. |
| `refundStatus` | string (CSV enum) | no | Refund row status, CSV of approved\|pending\|declined\|error\|unknown\|cancelled. |
| `refundTest` | string (enum) | no | Test refunds: exclude (same as absent) \| include \| only. |
| `q` | string | no | Search (max 200 chars): e-mail, name or order id contain it; a phone-shaped term (6 or more digits) matches the phone digits; exactly 4 digits match the card's last four. LIKE wildcards are escaped. |
| `sort` | enum: last_seen\|first_seen\|customer\|email\|country\|card\|orders\|charges\|approved\|declined\|approval\|gross\|refunds\|chargebacks\|refunded\|cb\|net\|subs\|tags\|storefront\|latest_order; default `last_seen` | no | Server sort over the whole filtered list: last_seen (default) / first_seen (lifetime live charges), customer / email (the e-mail key), country / card / storefront / latest_order (the customer's latest live charge, the slowest sorts), orders / charges / approved / declined / approval (approved / charges, then charges) / gross / refunds / chargebacks / refunded / cb / net (the filtered figures), subs (live then total), tags (blacklisted then several-subscriptions). The e-mail breaks ties. Anything else is a 400. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |
| `limit` | integer; default `50` | no | Page size 1..10000. |
| `offset` | integer; default `0` | no | Row offset >= 0 (stable: the e-mail breaks ties). |

**Response**

```json
{
  "rows": [
    {
      "email": "jane@example.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "country": "US",
      "phone": "+15555550123",
      "masked_card": "4111111111111111",
      "card_last4": null,
      "card_brand": "visa",
      "wallet_kind": null,
      "crm": "nmi",
      "cards": 1,
      "storefront_url": "https://shop.example.com/p/demo",
      "latest_order_id": "ORD-9",
      "view_order_id": "ORD-9",
      "orders": 3,
      "charges": 4,
      "approved": 3,
      "declined": 1,
      "gross_cents": 8997,
      "refunds": 1,
      "chargebacks": 0,
      "refunded_cents": 2999,
      "cb_cents": 0,
      "net_cents": 5998,
      "live_subs": 1,
      "subs": 2,
      "multi": false,
      "blacklisted": false,
      "first_at": "2026-05-02T14:03:11.000Z",
      "last_at": "2026-11-17T09:12:40.000Z",
      "drill_from": "2026-05-02T14:03:11.000Z",
      "threeDsSummary": {"total": 1, "ready": 0, "used": 1, "expired": 0, "pending": 0, "failed": 0, "readyForRebill": 0, "authenticationMode": "single"}
    }
  ],
  "total": 1250,
  "totals": {
    "clients": 1250,
    "orders": 1610,
    "charges": 2100,
    "approved": 1050,
    "declined": 1050,
    "gross_cents": 4436229,
    "refunds": 31,
    "chargebacks": 11,
    "refunded_cents": 180206,
    "cb_cents": 66349,
    "net_cents": 4189674,
    "live_subs": 31,
    "subs": 214,
    "blacklisted": 42
  },
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows[].email` | string | The customer key: the lower-cased e-mail. The bulk key and the customerEmail of every drill link. |
| `rows[].first_name / last_name / country / phone` | string\|null | Latest non-empty values of the customer's latest live charges (the applied population's rows when one is applied). |
| `rows[].masked_card / card_last4 / card_brand / wallet_kind / crm` | string\|null | The latest carded live charge. |
| `rows[].cards` | number | Distinct cards (first6..last4) over the customer's live charges. |
| `rows[].storefront_url / latest_order_id` | string\|null | The latest live charge's storefront and order. |
| `rows[].view_order_id` | string\|null | The order the customer view opens on: the latest card order, else the latest order. Use it as :key on the customer routes. |
| `rows[].orders` | number | Distinct orders among the charges matching every charge-level filter. |
| `rows[].charges / approved / declined` | number | Matching charges with an outcome / approved / declined + error. |
| `rows[].gross_cents` | number | Sum of the matching approved charges. |
| `rows[].refunds / chargebacks` | number | Distinct matching charges with a successful non-test refund event not marked chargeback / marked chargeback, dated in the range. |
| `rows[].refunded_cents / cb_cents` | number | Sum of those refund events (two partial refunds of one charge add up), narrowed by refund / refundStatus / refundTest. |
| `rows[].net_cents` | number | gross - refunded - charged back, before fees. |
| `rows[].live_subs / subs` | number | The account's subs of the e-mail: active or paused / all. |
| `rows[].multi` | boolean | A sub of the e-mail allows several subscriptions. |
| `rows[].blacklisted` | boolean | An active blacklist row of the account holds the e-mail or a card the customer paid with. |
| `rows[].first_at / last_at` | ISO string\|null | Lifetime first / last live charge. |
| `rows[].drill_from` | ISO string\|null | The first counted charge (or the charge behind a counted refund event). |
| `rows[].threeDsSummary` | object | The customer's 3DS proof inventory {total, ready, used, expired, pending, failed, readyForRebill, authenticationMode none\|single\|double}. |
| `total` | number | Clients matching (= totals.customers). |
| `totals` | object | Whole filtered list: customers, orders, charges, approved, declined, gross_cents, refunds, chargebacks, refunded_cents, cb_cents, net_cents, live_subs, subs, blacklisted. |
| `timezone` | string | The account's display timezone (account settings; UTC when unset or invalid). |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: an unknown query parameter (strict: details.formErrors names it), an unknown value of a closed vocabulary ("unknown value: ..."), a malformed number or date, a sort outside the whitelist, a reversed range pair ("<key> is before <key>"), an unknown tz, or hour without a valid tz.
- `400` {"error":"Invalid affiliate filter"} / {"error":"Unknown affiliate filter"} / {"error":"Invalid flow filter"} / {"error":"Unknown flow filter"}: an affiliate or flow value that is malformed or not of this account (checked before the handler).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `504` The read exceeded its 25-second request budget and was cancelled ("The request took too long and was cancelled ..."); narrow the filters and retry.

**Gotchas**

- E-mail keyed: the customer VIEW merges e-mail and card, so its subscription list may show another e-mail's sub sharing a card; charges without an e-mail are never customers.
- Two kinds of columns: orders ... net follow every charge-level filter and the range; first / last seen, subs, tags, country, card and last storefront are LIFETIME facts of the e-mail's live charges (a storefront filter does not move "last storefront").
- Drill into transactions with customerEmail (exact), never email (contains). Start the range at drill_from, not first_at (first_at is live-only: null under population=test).
- refunds / chargebacks count refunded CHARGES (distinct); refunded_cents / cb_cents sum the refund EVENTS.
- STRICT: an unknown query parameter is a 400.
- masked_card holds the stored card value (full digits on recent charges) for an account administrator; it is masked first6..last4 for other member roles.
- Heavy read: a few seconds on a large account; the request is cancelled with a 504 after 25 seconds.

##### `GET /v1/customers/:key/3ds`

**Scope** `customers.read` - **List customer 3DS authentications**

Recorded 3DS authentications of the customer behind an order or subscription id, including unused, consumed, expired and incomplete attempts, newest first (creation time, then id), within the account and the ATRIs the caller may see. Diagnostic only: it neither claims a proof nor starts a payment.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | URL-encoded order id or subscription id of the account. Never an e-mail. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | Page size 1..200. |
| `offset` | integer; default `0` | no | Rows to skip, 0..1000000. Unknown query parameters are rejected (strict). |

**Response** `200`

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "provider": "paay_3ds",
      "order_id": "ORD-9",
      "amount_cents": 2999,
      "currency": "USD",
      "masked_card": "411111******1111",
      "status": "authenticated",
      "usage_status": "ready",
      "trans_status": "Y",
      "flow": "frictionless",
      "eci": "05",
      "version": "2.2.0",
      "liability_shift": true,
      "reason": null,
      "ds_trans_id": "00000000-0000-4000-8000-000000000002",
      "acs_trans_id": null,
      "three_ds_server_trans_id": "00000000-0000-4000-8000-000000000003",
      "purpose": "rebill",
      "group_id": "00000000-0000-4000-8000-000000000004",
      "rebill_eligible": true,
      "rebill_reserve_ready": true,
      "intended_rebill_amount_cents": 2999,
      "intended_rebill_currency": "USD",
      "consumed_by": null,
      "created_at": "2026-10-25T12:00:00.000Z",
      "updated_at": "2026-10-25T12:00:05.000Z",
      "authenticated_at": "2026-10-25T12:00:05.000Z",
      "expires_at": "2026-11-24T12:00:00.000Z"
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object | Safe authentication metadata: id, provider, order_id, amount_cents, currency, masked_card, status, trans_status, flow, eci, version, liability_shift, reason and provider transaction identifiers. No cryptogram, encrypted cryptogram, raw provider payload, callback state or internal binding hash is returned. |
| `rows[].usage_status` | string | used, ready, expired, pending, failed or unavailable. Used takes precedence over expiry. Ready means an unconsumed, locally unexpired authenticated/attempted/informational result with Y/A/I status and stored proof plus ECI; a grouped proof must also have been admitted to the rebill pool. Pending covers browser method/challenge work and grouped proofs awaiting checkout dispatch. A ready row is not a promise that it matches a future payment. |
| `rows[].purpose` | string \| null | straight or rebill for a paired authentication; null for sessions without an assigned purpose. |
| `rows[].group_id` | uuid \| null | Shared identifier of the checkout authentication pair, if any. |
| `rows[].rebill_eligible` | boolean | Whether this session was admitted to the saved rebill proof pool. Actual consumption still checks card, amount, currency, merchant account and authentication context. |
| `rows[].consumed_by` | uuid \| null | Transaction that consumed the proof. Consumption is single use and does not imply an approved payment. |
| `rows[].created_at / updated_at / authenticated_at` | string \| null | Creation and latest update timestamps; authenticated_at is nullable when no successful/attempted proof has been stored. |
| `rows[].expires_at` | string | Effective local holding deadline: auth_expires_at when present, otherwise the session expiry. This operational deadline does not guarantee issuer or processor acceptance. |
| `total` | number | Total matching rows before pagination when this page contains a row; 0 for an empty result page. |
| `rows[].amount_cents / currency` | integer + string | Amount in minor units and currency actually sent to the authentication provider. This is not necessarily the amount of the later subscription payment. |
| `rows[].intended_rebill_amount_cents / intended_rebill_currency` | integer + string \| null | Separate future-payment amount in minor units and currency, present on newly created PAAY second slots. Legacy null values retain the authentication amount/currency binding. Consumption uses the intended amount and still requires matching currencies. |
| `rows[].rebill_reserve_ready` | boolean | true when this proof is usable now AND bound for a rebill (PAAY, admitted to the rebill pool, unconsumed, not expired, card and gateway context recorded): it counts in readyForRebill. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: an unknown query parameter, or limit / offset not an integer within bounds.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `504` The read exceeded its 25-second request budget and was cancelled ("The request took too long and was cancelled ..."); narrow the filters and retry.

**Gotchas**

- Sent with Cache-Control: no-store. No cryptogram, encrypted cryptogram, raw provider payload, callback state or binding hash is ever returned.
- Sessions are linked through the resolved customer orders, the exact card hash or the e-mail, including historical transactions beyond the 500-order customer window. With a restricted ATRI view, only sessions whose order has a charge in an allowed ATRI are shown; card-only sessions without that link are omitted.
- Saved proofs are claimed atomically by the payment engine and only once: the readiness shown is a snapshot and can change before a rebill runs.

##### `GET /v1/customers/:key/events`

**Scope** `customers.read` - **Customer timeline**

The append-only customer timeline: every customer event of the person (keyed by the e-mail hash, the keyed card hash or any of their order ids) merged with the sale pipeline runs of their orders, shown as the virtual type pipeline.run (a refusal has a run and no transaction, so it shows here too; the run's stages ride in payload.stages). Filtered, server-sorted and server-paged; `facets` lists every type of the whole timeline with its count, `runNames` names the ATRIs and MIDs the run rows cite. Messages never carry an e-mail, a name or a PAN. The same query contract as GET /v1/transactions/:id/events.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | The customer key: a sub id (UUID) or an order id of the account, what GET /v1/subscription/customer returns as customer_ref. URL-encode an order id. Never an e-mail. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `type` | string (CSV enum) | no | CSV of event types to keep (max 4000 chars): charge.approved, charge.declined, charge.error, charge.unknown, charge.rejected, charge.refused, charge.reversed, charge.imported, charge.attempt, retry.requested, threeds.parked, threeds.resumed, threeds.abandoned, threeds.applied, threeds.fallback, threeds.session.started, threeds.session.authenticated, threeds.session.attempted, threeds.session.failed, threeds.session.unavailable, threeds.session.expired, threeds.session.error, bin.decision, wallet.session.started, wallet.session.declined, wallet.session.error, attribution.captured, export.exify, export.platformpay, sub.attached, sub.attach_skipped, sub.charge.planned, sub.charge.replanned, sub.charge.moved, sub.charge.amount_overridden, sub.charge.revived, sub.charge.approved, sub.charge.declined, sub.charge.blocked, sub.charge.rejected, sub.charge.requeued, sub.charge.missed, sub.charge.reverted, sub.cycle_advanced, sub.completed, sub.retry_planned, sub.decline_recorded, sub.ended, sub.repaired, sub.force_billed, sub.edited, sub.product.edited, sub.paused, sub.resumed, sub.cancelled, sub.flag_changed, refund.approved, refund.declined, refund.error, refund.external, refund.test_cancelled, chargeback.marked, chargeback.unmarked, dispute.marked, dispute.unmarked, alert.received, blacklist.added, blacklist.removed, note.added, note.deleted, recovery.cart.captured, recovery.sms.sent, recovery.sms.failed, recovery.sms.skipped, recovery.email.sent, recovery.email.failed, recovery.email.skipped, recovery.delivery, recovery.recovered, recovery.attributed, rebill.routing.constrained, rebill.routing.relaxed, customer.edited, and the virtual pipeline.run. An unknown type is a 400 {"error":"Unknown event type","unknown":[...]}. |
| `q` | string | no | Case-insensitive substring of `message`, trimmed, max 200 chars. |
| `from` | string | no | ISO instant with offset or Z: events at or after it. |
| `to` | string | no | ISO instant with offset or Z: events strictly before it. |
| `actor` | enum: user\|system\|api\|partner\|customer | no | Actor kind. |
| `severity` | enum: info\|warn\|error | no | Severity. |
| `subId` | uuid | no | Only the rows that reference this sub. |
| `sort` | enum: at\|type\|actor\|severity\|message\|order\|charge; default `at` | no | Sort key (charge = the row's transaction id). Anything else is a 400 {"error":"Invalid sort","allowed":[...]}. |
| `dir` | enum: asc\|desc; default `desc` | no | Direction (ties broken by at desc, id desc). |
| `limit` | integer; default `50` | no | 1..10000. |
| `offset` | integer; default `0` | no | >= 0. |

**Response**

```json
{
  "rows": [{"id": "184", "at": "2026-09-26T15:07:05.400Z", "source": "event", "actor_kind": "system", "actor": "dispatch", "acting_as": null, "event_type": "sub.charge.declined", "severity": "warn", "message": "Charge #2 declined on MID US 02: Insufficient funds [nsf/soft] -> retry 1 in 24 h", "payload": {"rebill_number": 2, "amount_cents": 1999, "decline_category": "nsf"}, "order_id": "ORD-118842", "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111", "sub_id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f", "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33", "entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110", "schedule_id": null, "refund_id": null, "mid_id": "9b8a7c6d-1111-4222-8333-444455556666", "trip_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "rejection_id": null, "decision_id": null, "session_id": null, "note_id": null, "blacklist_id": null, "total": 41}, {"id": "5e4d3c2b-1a09-4f8e-8d7c-6b5a49382716", "at": "2026-09-25T09:12:40.000Z", "source": "run", "actor_kind": "system", "actor": "rebill-auto", "acting_as": null, "event_type": "pipeline.run", "severity": "warn", "message": "Sale pipeline run (rebill): refused before any MID  -  velocity_guard", "payload": {"outcome": "rejected", "refused_by": "velocity_guard", "fell_through": false, "flow": "rebill", "channel": "rebill-auto", "run_no": 1, "trip_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "final_trip_id": null, "amount_cents": 1999, "card_brand": "VISA", "total_us": 41200, "stages": [{"name": "refusals", "input": {}, "decision": {"action": "refuse", "applied": true, "reason": "velocity guard"}, "durationUs": 900}]}, "order_id": "ORD-118842", "transaction_id": null, "sub_id": null, "subscription_id": null, "entry_id": null, "schedule_id": null, "refund_id": null, "mid_id": null, "trip_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "rejection_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", "decision_id": null, "session_id": null, "note_id": null, "blacklist_id": null, "total": 41}],
  "total": 41,
  "facets": [{"type": "sub.charge.planned", "n": 12}, {"type": "sub.charge.declined", "n": 6}, {"type": "pipeline.run", "n": 9}],
  "runNames": {"trips": {"1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d": "Main Rebill"}, "mids": {}},
  "customer": {"key": "ORD-118842", "orderIds": ["ORD-118842", "ORD-118801"]},
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | {id, at, source (event \| run), actor_kind, actor, acting_as, event_type, severity, message, payload (max 2 KB, redacted), order_id, transaction_id, sub_id, subscription_id, entry_id, schedule_id, refund_id, mid_id, trip_id, rejection_id, decision_id, session_id, note_id, blacklist_id, total}. A run row's id is the run UUID, an event row's id the numeric event id as text. |
| `total` | integer | Rows matching the filters (every page). |
| `facets` | array | [{type, n}] over the WHOLE timeline (unfiltered), most frequent first. |
| `runNames` | object | {trips: {id: name}, mids: {id: name}} for the run rows of the page. |
| `customer` | object | {key, orderIds}: the resolved customer. |
| `timezone` | string | America/New_York. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a bad instant, limit, offset, actor, severity or subId; {"error":"Unknown event type","unknown":[...]}; {"error":"Invalid sort","allowed":["at","type","actor","severity","message","order","charge"]}. Sent before any database read.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Events are written fire-and-forget by the engine: a row can land a few hundred milliseconds after the action that caused it.
- type=pipeline.run selects the runs alone; the run stages are in payload.stages (bounded to about 4 KB).
- facets are computed on the WHOLE timeline, not on the filtered page.

##### `GET /v1/customers/:key/events/export.csv`

**Scope** `customers.read` - **Customer timeline as CSV**

The same timeline as GET /v1/customers/:key/events as one CSV file: every row matching the filters (max 10000, OLDEST first), UTF-8 with BOM, CRLF line ends. Columns: at, actor_kind, actor, acting_as, event_type, severity, message, order_id, transaction_id, sub_id, subscription_id, entry_id, schedule_id, refund_id, mid_id, trip_id, rejection_id, decision_id, session_id, note_id, blacklist_id, payload (JSON, a run row's stages left out). A cell starting with = + - or @ is prefixed with an apostrophe.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | The customer key: a sub id (UUID) or an order id of the account, what GET /v1/subscription/customer returns as customer_ref. URL-encode an order id. Never an e-mail. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `type` | string (CSV enum) | no | CSV of event types to keep (max 4000 chars): charge.approved, charge.declined, charge.error, charge.unknown, charge.rejected, charge.refused, charge.reversed, charge.imported, charge.attempt, retry.requested, threeds.parked, threeds.resumed, threeds.abandoned, threeds.applied, threeds.fallback, threeds.session.started, threeds.session.authenticated, threeds.session.attempted, threeds.session.failed, threeds.session.unavailable, threeds.session.expired, threeds.session.error, bin.decision, wallet.session.started, wallet.session.declined, wallet.session.error, attribution.captured, export.exify, export.platformpay, sub.attached, sub.attach_skipped, sub.charge.planned, sub.charge.replanned, sub.charge.moved, sub.charge.amount_overridden, sub.charge.revived, sub.charge.approved, sub.charge.declined, sub.charge.blocked, sub.charge.rejected, sub.charge.requeued, sub.charge.missed, sub.charge.reverted, sub.cycle_advanced, sub.completed, sub.retry_planned, sub.decline_recorded, sub.ended, sub.repaired, sub.force_billed, sub.edited, sub.product.edited, sub.paused, sub.resumed, sub.cancelled, sub.flag_changed, refund.approved, refund.declined, refund.error, refund.external, refund.test_cancelled, chargeback.marked, chargeback.unmarked, dispute.marked, dispute.unmarked, alert.received, blacklist.added, blacklist.removed, note.added, note.deleted, recovery.cart.captured, recovery.sms.sent, recovery.sms.failed, recovery.sms.skipped, recovery.email.sent, recovery.email.failed, recovery.email.skipped, recovery.delivery, recovery.recovered, recovery.attributed, rebill.routing.constrained, rebill.routing.relaxed, customer.edited, and the virtual pipeline.run. An unknown type is a 400 {"error":"Unknown event type","unknown":[...]}. |
| `q` | string | no | Case-insensitive substring of `message`, trimmed, max 200 chars. |
| `from` | string | no | ISO instant with offset or Z: events at or after it. |
| `to` | string | no | ISO instant with offset or Z: events strictly before it. |
| `actor` | enum: user\|system\|api\|partner\|customer | no | Actor kind. |
| `severity` | enum: info\|warn\|error | no | Severity. |
| `subId` | uuid | no | Only the rows that reference this sub. |
| `sort` | enum: at\|type\|actor\|severity\|message\|order\|charge; default `at` | no | Validated like the timeline (an unknown value is a 400) but ignored: the file is always oldest first. |
| `dir` | enum: asc\|desc; default `desc` | no | Validated, ignored. |
| `limit` | integer; default `50` | no | Validated (1..10000), ignored: the file holds the whole filtered set up to 10000 rows. |
| `offset` | integer; default `0` | no | Validated (>= 0), ignored. |

**Response**

```json
at,actor_kind,actor,acting_as,event_type,severity,message,order_id,transaction_id,sub_id,subscription_id,entry_id,schedule_id,refund_id,mid_id,trip_id,rejection_id,decision_id,session_id,note_id,blacklist_id,payload
2026-11-14T15:07:44.000Z,system,sale,,sub.attached,info,"Subscribed to VIP ($19.99 every 7 days)",ORD-118842,00000000-0000-4000-8000-000000000061,00000000-0000-4000-8000-000000000062,00000000-0000-4000-8000-000000000063,,,,,,,,,,,"{""amount_cents"":1999}"
```

| response field | type | description |
|---|---|---|
| `(body)` | text/csv | UTF-8 BOM, header row, one row per event, CRLF. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: a bad instant, limit, offset, actor, severity or subId; {"error":"Unknown event type","unknown":[...]}; {"error":"Invalid sort","allowed":["at","type","actor","severity","message","order","charge"]}. Sent before any database read.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- sort, dir, limit and offset are validated like the timeline (an invalid value is a 400) but do not change the file: the whole filtered set, oldest first, capped at 10000 rows.
- Content-Type text/csv; charset=utf-8, Content-Disposition attachment; filename="customer-events-<order id>.csv" (characters outside A-Z a-z 0-9 _ - replaced by _).

##### `POST /v1/customers/:key/flag`

**Scope** `customers.write` - **Allow or forbid several subscriptions for a customer**

Sets or clears the "allow several subscriptions" flag on every key row of the customer (the e-mail hash and the keyed card hash), stamps the customer's live subs so the attach guard and the badge agree, and logs a sub.flag_changed event. While the flag is on, the one-live-sub-per-customer rule, the supersession rules and the resume check are bypassed for that customer.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | The customer key: a sub id (UUID) or an order id of the account, what GET /v1/subscription/customer returns as customer_ref. URL-encode an order id. Never an e-mail. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `multiAllowed` | boolean | **yes** | true = several live subs allowed; false = back to one per customer (subs already live stay live). |
| `note` | string | no | Trimmed, max 200 chars, kept on the flag row and in the event. |

**Request body**

```json
{
  "multiAllowed": true,
  "note": "Two products by choice"
}
```

**Response**

```json
{
  "ok": true,
  "multiAllowed": true,
  "keys": 2,
  "flag": {"multi_allowed": true, "note": "Two products by choice", "set_by": "ops@example.com", "set_at": "2026-11-20T16:00:00.000Z"}
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on success. |
| `multiAllowed` | boolean | The value written. |
| `keys` | integer | Flag rows written (1 or 2: the e-mail hash and / or the card key). |
| `flag` | object\|null | The flag row read back {multi_allowed, note, set_by, set_at}. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>}: multiAllowed missing or not a boolean, note over 200 chars.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `422` {"error":"This customer has no e-mail and no card key to flag"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Clearing the flag never ends a sub: two live subs stay live until one is cancelled.
- Logged on the customer timeline (sub.flag_changed) and in the action log (object type customer).
- Unknown body keys are ignored.

##### `GET /v1/customers/:key/notes`

**Scope** `customers.read` - **List a customer's notes**

Lists one customer's notes (a customer is a shopper, identified here by an order id or a sub id). The transaction notes of the customer behind `:key`: the notes of its e-mail's charges and of the orders the customer view resolved, newest first, max 500, limited to the charges the caller may see.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | An order id or a sub id of the account (never an e-mail). URL-encode an order id. |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000081",
      "transaction_id": "00000000-0000-4000-8000-000000000061",
      "note": "Called the customer",
      "author": "ops@example.com",
      "created_at": "2026-11-02T12:00:00.000Z",
      "order_id": "ORD-9",
      "txn_created_at": "2026-11-01T10:00:00.000Z",
      "amount_cents": 2999,
      "status": "approved"
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object | id, transaction_id, note, author, created_at, and the charge's order_id, txn_created_at, amount_cents, status. |
| `total` | number | Rows returned (max 500). |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `504` The read exceeded its 25-second request budget and was cancelled ("The request took too long and was cancelled ..."); narrow the filters and retry.

**Gotchas**

- Add or delete a note with POST /v1/transactions/:transactionId/note and DELETE /v1/transactions/notes/:noteId.
- total is the number of rows returned (capped at 500), not a count beyond the cap.

##### `GET /v1/customers/:key/subscriptions`

**Scope** `customers.read` - **Every subscription of a customer**

Every subscription of the PERSON behind the key: the order the key lands on, every order of the same e-mail and every order of the same card (the keyed card hash when both sides carry it, else first6..last4), across every product, live subs first then newest first. Each row is the subscription list row plus its display inputs (entry status, product state, end category, multi_allowed, lifecycle instants), its rebill counts, the last decided charge's MID and ATRI and the customer's 3DS summary. The `customer` block carries the "allow several subscriptions" flag when one exists.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | The customer key: a sub id (UUID) or an order id of the account, what GET /v1/subscription/customer returns as customer_ref. URL-encode an order id. Never an e-mail. |

**Response**

```json
{
  "rows": [{"id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f", "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33", "subscription_name": "VIP", "order_id": "ORD-118842", "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001", "email": "jane@example.com", "amount_cents": 1999, "status": "active", "cycle": 1, "retry_step": 1, "next_charge_at": "2026-09-28T15:07:00.000Z", "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110", "last_charge_at": "2026-09-26T15:07:05.210Z", "last_status": "rebill_failed", "last_decline_reason": "Insufficient funds", "source": "auto", "attached_by": "sale", "cancel_reason": null, "cancelled_at": null, "end_cause": null, "end_category": null, "multi_allowed": false, "activated_at": "2026-09-21T15:07:05.210Z", "ended_at": null, "end_reason": null, "created_at": "2026-09-14T15:07:44.000Z", "interval_value": 7, "interval_unit": "days", "entry_status": "scheduled", "entry_amount_cents": 2999, "product_active": true, "product_max_cycles": null, "attach_on": "approved", "success_count": 1, "failed_count": 1, "blocked_count": 0, "last_mid_id": "9b8a7c6d-1111-4222-8333-444455556666", "last_mid_name": "MID US 02", "last_trip_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "last_trip_name": "Main Rebill", "total": 1, "threeDsSummary": {"total": 1, "ready": 1, "used": 0, "expired": 0, "pending": 0, "failed": 0, "readyForRebill": 1, "authenticationMode": "single"}}],
  "customer": {"key": "ORD-118842", "orderIds": ["ORD-118842", "ORD-118801"], "multiAllowed": false, "flag": null},
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | The subs: every rebill_subs column plus subscription_name, product_atri_split (null = the account default ATRI), interval fields, sale facts (first_name, last_name, masked_card, storefront_url, country, sale_at, sale_amount_cents, sale_mid, card_brand), current entry (entry_status, entry_scheduled_at, entry_amount_cents, entry_currency, entry_route_override, day_route_override), product_slug, product_name, last_charge_amount_cents, product_active, product_max_cycles, attach_on, success_count, failed_count, blocked_count, last_mid_id/name, last_trip_id/name, total, threeDsSummary. |
| `rows[].threeDsSummary` | object\|null | The customer's 3DS proof inventory for that sub: {total, ready, used, expired, pending, failed, readyForRebill, authenticationMode none\|single\|double}. |
| `customer.key` | string | The resolved order id (what the other customer routes take). |
| `customer.orderIds` | array | Every order of the account that belongs to the e-mail or the card (max 500, newest first). |
| `customer.multiAllowed` | boolean | Several live subs are allowed for this customer. |
| `customer.flag` | object\|null | {multi_allowed, note, set_by, set_at}: the flag row, when one exists. |
| `timezone` | string | America/New_York, the rebill day's timezone (instants are UTC). |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- The subs of ONE order are GET /v1/subscription/subs/by-order/:orderId; this route spans the person.
- A customer reached through a wallet-only order (no card on file) is keyed by e-mail alone: card-only siblings are not found.
- Rows are limited to the account and, for a restricted member, to the ATRIs the member may see.

##### `GET /v1/customers/:key/summary`

**Scope** `customers.read` - **Get a customer summary**

Gets one customer's summary (a customer is a shopper, identified here by an order id or a sub id). The customer behind `:key` (an order id or a sub id): its lifetime row (the GET /v1/customers row with no filter, plus its 3DS summary), its active blacklist hits, its notes count and the account timezone.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | string | **yes** | An order id or a sub id of the account (never an e-mail). URL-encode an order id. |

**Response**

```json
{
  "email": "jane@example.com",
  "row": {
    "email": "jane@example.com",
    "orders": 3,
    "gross_cents": 8997,
    "blacklisted": true,
    "drill_from": "2026-05-02T14:03:11.000Z"
  },
  "blacklist": [
    {
      "id": "00000000-0000-4000-8000-000000000071",
      "kind": "email",
      "card_last4": null,
      "reason": "fraud",
      "source": "manual",
      "created_by": "ops@example.com",
      "created_at": "2026-11-01T10:00:00.000Z"
    }
  ],
  "notes": 2,
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `email` | string\|null | The resolved customer e-mail (lower-cased); null when the order has none. |
| `row` | object\|null | The customer row of GET /v1/customers, no filter, with threeDsSummary (null: no e-mail, or no live charge in scope). |
| `blacklist` | object[] | Active blacklist rows hitting the customer (its e-mail row, rows of a card it paid with): id, kind email\|card, card_last4 (never the stored card), reason, source, created_by, created_at. |
| `notes` | number | Transaction notes of the customer (max 500). |
| `timezone` | string | The account's display timezone. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: the key matches no sub and no order of the account (another account's order answers the same 404).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `504` The read exceeded its 25-second request budget and was cancelled ("The request took too long and was cancelled ..."); narrow the filters and retry.

**Gotchas**

- A key whose order has no e-mail answers email null, row null and blacklist [] (notes still count the orders of the view).
- blacklist is [] for member roles other than account administrators (the rows are not read); row.blacklisted still tells the state.

##### `POST /v1/customers/bulk`

**Scope** `customers.write` - **Run one action on many customers (preview, then run)**

Runs one action on many customers (shoppers, by e-mail): preview, then run. One action on many customers (e-mails), synchronously: blacklist (the e-mail and up to 10 cards it paid with; its live subs are queued for cleanup), unblacklist (removes every active row hitting the customer), pause_subs / resume_subs / cancel_subs (EVERY sub of the e-mail: active / paused and failed / active, paused and failed), allow_multi / forbid_multi (the "allow several subscriptions" flag). `preview: true` runs the same reads and answers the counts without writing anything; then post the same body without it. For large selections the asynchronous bulk jobs (POST /v1/customers/bulk-jobs) are the durable path.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `emails` | string[] | **yes** | 1..10000 customer keys as GET /v1/customers/ids answers them (trimmed, lower-cased, de-duplicated; 1..254 chars each, not checked as e-mails). A key with no charge of the account in scope is skipped "Not found". |
| `action` | enum: blacklist\|unblacklist\|pause_subs\|resume_subs\|cancel_subs\|allow_multi\|forbid_multi | **yes** | The action. |
| `reason` | string | no | Trimmed, max 200 chars. Blacklist reason (default "Bulk blacklist (Clients)"), cancel reason (default "cancelled in bulk by <caller>"), or flag note. |
| `preview` | boolean; default `false` | no | true = read and count only, nothing written (summary.done = 0). |
| `subscriptionId` | string | no | CSV of subscription product ids (max 4000 chars): the page's applied product filter, used only to COUNT the subs touched outside it (subsOtherProducts). The action still applies to every sub of the customer. |
| `requestId` | uuid | no | Blacklist only: a caller-kept UUID that makes each blacklist activation replay-safe (one request reference per e-mail and card is derived from it). Reuse it with the identical body after an uncertain outcome; the same id with a different input fails for that customer with a "Request ID already used..." error. |

**Request body**

```json
{
  "emails": [
    "jane@example.com",
    "john@example.com"
  ],
  "action": "cancel_subs",
  "preview": true,
  "subscriptionId": "00000000-0000-4000-8000-000000000091"
}
```

**Response**

```json
{
  "results": [
    {
      "id": "jane@example.com",
      "ok": true,
      "changed": 0,
      "subs": 2,
      "subsRefused": 0,
      "subsOtherProducts": 1,
      "pans": 0,
      "subsEnded": 0
    },
    {
      "id": "john@example.com",
      "ok": false,
      "skipped": "No sub to cancel",
      "changed": 0,
      "subs": 0,
      "subsRefused": 0,
      "subsOtherProducts": 0,
      "pans": 0,
      "subsEnded": 0
    }
  ],
  "summary": {
    "clients": 2,
    "eligible": 1,
    "done": 0,
    "skipped": 1,
    "failed": 0,
    "subs": 2,
    "subsOtherProducts": 1,
    "pans": 0,
    "subsEnded": 0,
    "subsRefused": 0
  },
  "preview": true
}
```

| response field | type | description |
|---|---|---|
| `results[]` | object | Per e-mail: id, ok, skipped? ("Not found", "No active sub", "No paused or failed sub", "No sub to cancel", "Holds another live sub - allow several subscriptions first" (the code's text uses an em dash), "Not changed", "Already blacklisted", "Not blacklisted", "Already allowed", "Already forbidden"), error? (a writer failed, or blacklist cleanup pending), changed (rows written), subs (subs the action touches; resume: the resumable ones), subsRefused (resume: subs the one-live-sub rule refuses), subsOtherProducts (of those, outside subscriptionId), pans (blacklist: rows it writes, the e-mail row plus the cards not yet listed; unblacklist: rows it removes), subsEnded (blacklist: on a preview the live subs it would end, by the e-mail or a card charge; on a run the subs confirmed ended, 0 while the cleanup is pending). |
| `summary` | object | customers, eligible, done (0 on a preview), skipped, failed, the sums of subs / subsOtherProducts / pans / subsEnded over the eligible customers, and subsRefused over every customer. |
| `preview` | boolean | Echo of the request. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: empty emails or more than 10000, a key empty or over 254 chars, an unknown action, reason over 200 chars, requestId not a UUID, or an unknown body key (strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Admin role required"}: blacklist / unblacklist by a member who is not an account administrator (checked before any read); {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Client level on purpose: pause / resume / cancel touch EVERY sub of the e-mail, whatever the list filters. Preview first and read subsOtherProducts.
- Resume keeps the one-live-sub rule per sub, oldest first, the preview included: a customer holding another live sub (a paused sibling counts) is refused unless a sub allows several or the customer is flagged. Allow several subscriptions first to resume them all.
- Blacklist: the activation commits at once but ending the subs is a queued cleanup. A customer whose cleanup is still pending answers ok:false with error "Blacklist is active; required subscription cleanup is pending. Check Blacklist progress." (the blacklist IS active); follow it with GET /v1/blacklist/cleanup.
- A writer failure is reported per customer (ok:false, error) and the other customers still run; the call itself answers 200.
- Customer events are written for every change (blacklist.added / removed, sub.paused / resumed / cancelled, sub.charge.planned / replanned, sub.flag_changed) with the caller as actor.
- Runs 4 customers at a time within one request: a large selection can hit the request deadline. Use the bulk jobs for big runs.

##### `GET /v1/customers/bulk-jobs`

**Scope** `customers.read` - **List customer bulk jobs**

Lists the caller's last 20 customer bulk jobs of the account, queued and running first, then newest.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000301",
      "request_id": "00000000-0000-4000-8000-000000000302",
      "action": "pause_subs",
      "preview": false,
      "reason": "Customer asked by e-mail",
      "subscription_filter": null,
      "status": "queued",
      "total": 2,
      "processed": 0,
      "succeeded": 0,
      "failed": 0,
      "skipped": 0,
      "units_processed": 0,
      "cancel_requested": false,
      "cleanup_pending": false,
      "error": null,
      "created_at": "2026-11-24T10:00:00.000Z",
      "updated_at": "2026-11-24T10:00:00.000Z",
      "finished_at": null,
      "errors": [],
      "result": {
        "done": 0,
        "skipped": 0
      }
    }
  ]
}
```

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.

##### `POST /v1/customers/bulk-jobs`

**Scope** `customers.write` - **Start a customer bulk job**

Admits a background job that applies one action to up to 10,000 customers of the account (by e-mail) and answers 202 with the job. Poll GET /v1/customers/bulk-jobs/:id, then read GET /v1/customers/bulk-jobs/:id/result. One customer, subscription or transaction bulk job at a time per account.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `emails` | string[] (1-10000, each 1-254, trimmed and lower-cased) | **yes** | Customer e-mails of the account. Duplicates are merged; an e-mail with no customer in the account is skipped as Not found. |
| `action` | enum: blacklist \| unblacklist \| pause_subs \| resume_subs \| cancel_subs \| allow_multi \| forbid_multi | **yes** | blacklist / unblacklist: add or remove the customer (e-mail and cards) on the blacklist. pause_subs: active subscriptions -> paused. resume_subs: paused or failed -> active. cancel_subs: active, paused or failed -> cancelled. allow_multi / forbid_multi: allow or forbid the customer to hold several live subscriptions. |
| `reason` | string (0-200, trimmed) | no | Reason stored on the blacklist rows, the flag note or the subscription events. |
| `preview` | boolean; default `false` | no | true runs a dry run: the result says what would change and nothing is written. |
| `subscriptionId` | string (comma-separated subscription product UUIDs, max 4000) | no | For the subscription actions: only subscriptions of these products are touched (the others are counted in subsOtherProducts). |
| `requestId` | uuid | **yes** | Idempotency key. Resending the same requestId with the same body returns the same job; with a different body, 409. |
| `previewJobId` | uuid | no | Confirms a finished preview job (success or partial) of the same action and exactly the same e-mails; the preview verdicts of skipped and failed customers are reused. Not allowed together with preview true. |

**Request body**

```json
{
  "emails": [
    "jane@example.com",
    "john@example.com"
  ],
  "action": "pause_subs",
  "reason": "Customer asked by e-mail",
  "requestId": "00000000-0000-4000-8000-000000000302"
}
```

**Response** `202`

```json
{
  "jobId": "00000000-0000-4000-8000-000000000301",
  "job": {
    "id": "00000000-0000-4000-8000-000000000301",
    "request_id": "00000000-0000-4000-8000-000000000302",
    "action": "pause_subs",
    "preview": false,
    "reason": "Customer asked by e-mail",
    "subscription_filter": null,
    "status": "queued",
    "total": 2,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when the body fails the schema (strict: unknown fields refused; emails empty or over 10,000; action unknown; requestId missing or not a UUID; subscriptionId not a list of UUIDs).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `409` `{"error":"Request ID already used with different input or permissions"}`; `{"error":"Another transaction bulk operation is active on this account","jobId":"..."}`; `{"error":"Another customer or subscription bulk operation is active on this account","jobId":"..."}`; `{"error":"The confirmed client preview is unavailable"}` (previewJobId unknown, not a finished preview, another action, or preview also true); `{"error":"The confirmed preview has a different client selection"}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"Customer background jobs are disabled"}` when background jobs are switched off on the server.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- Run a preview first (preview true), read its result, then confirm with previewJobId and a new requestId.
- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.
- If the answer is lost, resend the same body and requestId: you get the same job, never a second one.

##### `GET /v1/customers/bulk-jobs/:id`

**Scope** `customers.read` - **Read a customer bulk job**

Reads the status and counters of one customer bulk job (queued, running, success, partial, failed or cancelled).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000301",
    "request_id": "00000000-0000-4000-8000-000000000302",
    "action": "pause_subs",
    "preview": false,
    "reason": "Customer asked by e-mail",
    "subscription_filter": null,
    "status": "success",
    "total": 2,
    "processed": 2,
    "succeeded": 2,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": "2026-11-24T10:00:09.000Z",
    "errors": [],
    "result": {
      "done": 2,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- job.errors is always [] here: read the failures with GET /v1/customers/bulk-jobs/:id/errors.
- A job is visible only to the caller that created it (the same API key) and only while the account scope is unchanged: adding or removing an API key, gateway, wallet provider or member changes the scope, earlier jobs then answer 404 and replaying their requestId answers 409.

##### `POST /v1/customers/bulk-jobs/:id/cancel`

**Scope** `customers.write` - **Cancel a customer bulk job**

Requests cancellation of a queued or running customer bulk job and returns the job. Customers already processed stay changed; the rest are left as skipped `Cancelled before completion`.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000301",
    "request_id": "00000000-0000-4000-8000-000000000302",
    "action": "pause_subs",
    "preview": false,
    "reason": "Customer asked by e-mail",
    "subscription_filter": null,
    "status": "running",
    "total": 2,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "units_processed": 0,
    "cancel_requested": true,
    "cleanup_pending": false,
    "error": null,
    "created_at": "2026-11-24T10:00:00.000Z",
    "updated_at": "2026-11-24T10:00:00.000Z",
    "finished_at": null,
    "errors": [],
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- Idempotent; on a finished job it changes nothing and returns the job as it is. The job reaches cancelled once the worker sees the request.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `GET /v1/customers/bulk-jobs/:id/errors`

**Scope** `customers.read` - **List a customer bulk job failures**

Pages the finished customers of a job that were skipped or failed, in the order sent.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |
| `limit` | integer (1-100); default `100` | no | Page size. |

**Response**

```json
{
  "errors": [
    {
      "itemId": "john@example.com",
      "reason": "No active sub"
    }
  ]
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `400` `{"error":"Invalid pagination"}` when offset or limit is out of bounds.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- itemId is the customer e-mail. Only finished customers appear; pending ones are not listed.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `GET /v1/customers/bulk-jobs/:id/result`

**Scope** `customers.read` - **Read a customer bulk job result**

Returns the per-customer results in the order sent and a summary. Customers not processed yet (or left by a cancel) are reported as skipped `Not completed` or `Cancelled before completion`.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Job id returned by the create call. |

**Response**

```json
{
  "results": [
    {
      "id": "jane@example.com",
      "ok": true,
      "changed": 1,
      "subs": 1,
      "subsRefused": 0,
      "subsOtherProducts": 0,
      "pans": 0,
      "subsEnded": 0
    },
    {
      "id": "john@example.com",
      "ok": false,
      "skipped": "No active sub",
      "changed": 0,
      "subs": 0,
      "subsRefused": 0,
      "subsOtherProducts": 0,
      "pans": 0,
      "subsEnded": 0
    }
  ],
  "summary": {
    "clients": 2,
    "eligible": 1,
    "done": 1,
    "skipped": 1,
    "failed": 0,
    "subs": 1,
    "subsOtherProducts": 0,
    "subsRefused": 0,
    "pans": 0,
    "subsEnded": 0
  },
  "preview": false
}
```

**Errors**

- `400` `{"error":"Invalid job ID"}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Job not found"}` when the job does not exist, belongs to another account, or was created by another caller or under a different account scope.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the control transaction passes its 15-second budget (for a create, resend the same requestId to learn whether the job was admitted).

**Gotchas**

- results[].id is the customer e-mail. skipped / error carry the reason (for example Not found, No active sub, Already allowed, No customer identity).
- summary.done is 0 for a preview (nothing was written); eligible is what a confirmation would change.
- pans counts blacklisted cards; subsEnded counts subscriptions ended by a blacklist.
- A job is visible only to the caller that created it (the same API key or login): a job started in the dashboard, or by another key, answers 404.

##### `GET /v1/customers/export`

**Scope** `customers.read` - **Export customers as CSV**

Exports customers (shoppers) as a CSV file built on the server. Every customer matching the filters as CSV (max 150000 rows, list order). Columns: Customer, Email, Phone, Country, Card, Cards, 3DS obtained, 3DS ready, 3DS rebill reserve, 3DS used, 3DS expired, Orders, Charges, Approved, Declined, Approval %, Gross, Refunds, Chargebacks, Refunded, Charged back, Net, Live subs, Subs, Blacklisted, Several subscriptions allowed, First seen (<tz>), Last seen (<tz>), Last storefront, Latest order. Charge-level keys (Transaction, Routing, Card, Customer, Subscription, Schedule and Refund groups, and from / to) narrow the FIGURES: a customer is listed when at least one of its charges matches (or, with a range, a refund event of a matching charge falls in it), and orders ... net count only the matching charges. Customer axes (customerEmail, customerThreeDs, clientBlacklisted, clientLiveSub, clientOrdersMin/Max, clientLtvMin/Max, clientFirstFrom/To, clientLastFrom/To) filter the customer's LIFETIME facts over its live charges, whatever the other filters.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | no | Start of the range (inclusive). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). Charge-level: reads the charge date (the refund event date when `refund` is set). A reversed from/to pair is a 400 "to is before from". |
| `to` | string | no | End of the range (inclusive; a bare day covers its last millisecond). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `tz` | string | no | IANA timezone the bare days and hours are read in, max 64 chars. Default America/New_York. An unknown zone is a 400 "not a known IANA timezone". |
| `hour` | string | no | CSV of hours 0..23 in tz (max 200 chars). Needs a valid tz, otherwise 400 "hour needs a valid tz". |
| `status` | string (CSV enum) | no | Charge status, CSV of approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca. failed = declined + error; completed = every charge with an outcome. |
| `source` | string (CSV enum) | no | CSV of sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell (max 100 chars). straight = sale + recovery, subscription = rebill. |
| `pass` | string (CSV enum) | no | initial\|cascade. |
| `method` | string (CSV enum) | no | card\|wallet\|wire. |
| `population` | string (CSV enum) | no | live\|test\|imported. Absent = live charges; set = the same re-target as the transactions list. |
| `credentialMode` | string (CSV enum) | no | Wire charges: mit\|cit. |
| `threeDs` | string (CSV enum) | no | 3DS outcome, CSV of applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only. |
| `declineCategory` | string | no | Decline-engine category, CSV (max 1000 chars). |
| `declineSeverity` | string (CSV enum) | no | soft\|hard. |
| `amountMin` | string (integer cents) | no | Amount >= this many cents (1 to 12 digits). |
| `amountMax` | string (integer cents) | no | Amount <= this many cents (1 to 12 digits). A max below amountMin is a 400. |
| `pricePoint` | string (CSV enum) | no | Price bucket, CSV of '1. < $25', '2. $25-49', '3. $50-74', '4. $75-99', '5. $100-149', '6. $150-199', '7. $200+'. |
| `product` | string | no | Basket product name, slug or reference, CSV (max 4000 chars). |
| `productSlug` | string | no | Basket product slug, CSV (max 4000 chars). |
| `productKey` | string | no | Product per store, CSV of <host>\|<ref> (max 4000 chars). |
| `currency` | string | no | CSV of 3-letter ISO 4217 codes (max 200 chars). |
| `gatewayTxnId` | string | no | Gateway transaction id, exact, CSV (max 4000 chars). |
| `authCode` | string | no | Auth code of any attempt, exact, CSV (max 1000 chars). |
| `descriptor` | string | no | Descriptor contains this text: the sent statement descriptor, the MID soft descriptor or name (max 128 chars). |
| `accountId` | string | no | Gateway: CSV of MID UUIDs, wallet:<walletProviderId>, wire:<bankAccountId> or none (max 4000 chars). |
| `walletProvider` | string | no | CSV of wallet provider UUIDs (alias of accountId=wallet:<id>). |
| `gatewayType` | string | no | a gateway type (the gatewayType values returned by GET /v1/accounts), CSV (max 100 chars). |
| `category` | string | no | CSV of category UUIDs: any category of the final MID. |
| `primaryCategory` | string | no | CSV of category UUIDs: the primary category of the final MID. |
| `atri` | string | no | CSV of ATRI UUIDs reached. |
| `atriFinal` | string | no | CSV of ATRI UUIDs the order ended on. |
| `processor` | string | no | CSV of processor UUIDs, or none. |
| `acquiringBank` | string | no | CSV of acquiring bank UUIDs, or none. |
| `company` | string | no | CSV of company UUIDs, or none. |
| `gatewayMcc` | string | no | Final MID MCC, CSV (max 1000 chars). |
| `gatewayBin` | string | no | Final MID acquirer BIN, CSV (max 1000 chars). |
| `brand` | string | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other, CSV (max 200 chars). |
| `paysource` | string | no | APPLEPAY / GOOGLEPAY (wallet payload), CSV (max 100 chars). |
| `funding` | string | no | Prepaid / Debit / Credit / Charge card (or a wallet), CSV (max 200 chars). |
| `cardType` | string | no | BIN card type (or a wallet), CSV (max 200 chars). |
| `cardLevel` | string | no | BIN card level (or a wallet), CSV (max 4000 chars). |
| `issuer` | string | no | Issuing bank, RFC 4180 CSV (max 4000 chars). |
| `bin` | string | no | CSV of 6-digit BINs or a wallet label (Apple Pay, Google Pay), max 4000 chars. Another value is a 400 "unknown value". |
| `first6` | string | no | Card prefix, 1 to 6 digits. |
| `last4` | string | no | Card suffix, 1 to 4 digits. |
| `country` | string | no | Billing country (ISO-2), CSV (max 2000 chars). |
| `storefront` | string | no | Store host bucket or (direct), CSV (max 4000 chars). The value __no_store__ selects canonical standalone orders (immutable order context), not a blank URL. |
| `traffic` | string | no | Traffic source or (direct/organic), CSV (max 2000 chars). |
| `utmSource` | string | no | UTM source, case-insensitive, CSV (max 4000 chars). |
| `utmCampaign` | string | no | UTM campaign, case-insensitive, CSV (max 4000 chars). |
| `device` | string | no | Mobile / Tablet / Desktop, CSV (max 200 chars). |
| `os` | string | no | Operating system, CSV (max 200 chars). |
| `browser` | string | no | Browser, CSV (max 200 chars). |
| `ipType` | string (CSV enum) | no | IPv4\|IPv6. |
| `ip` | string | no | CSV of customer IPs (max 2000 chars). |
| `email` | string | no | Charge e-mail contains this text (max 200 chars). |
| `phone` | string | no | Phone contains this text (max 40 chars). |
| `firstName` | string | no | First name contains this text (max 120 chars). |
| `lastName` | string | no | Last name contains this text (max 120 chars). |
| `customerEmail` | string | no | Client axis: CSV of exact e-mails, case-insensitive (max 4000 chars); a value without @ is dropped. |
| `customerThreeDs` | string (CSV enum) | no | Client axis: customer authentication inventory now, CSV of with-ready\|without-ready\|single\|double\|ready-for-rebill (single / double count proofs obtained, used ones included). |
| `clientBlacklisted` | string (enum) | no | Client axis: true\|false. Blacklisted by e-mail or by a card the customer paid with. |
| `clientLiveSub` | string (enum) | no | Client axis: true\|false. Has a live (active or paused) subscription. |
| `clientOrdersMin` | string (integer) | no | Client axis: lifetime distinct orders >= (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Client axis: lifetime distinct orders <= (1 to 12 digits). |
| `clientLtvMin` | string (integer cents) | no | Client axis: lifetime gross >= this many cents (1 to 12 digits). |
| `clientLtvMax` | string (integer cents) | no | Client axis: lifetime gross <= this many cents (1 to 12 digits). |
| `clientFirstFrom` | string | no | Client axis: first seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientFirstTo` | string | no | Client axis: first seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastFrom` | string | no | Client axis: last seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastTo` | string | no | Client axis: last seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `checkout` | string | no | CSV of checkout UUIDs at sale, or none for unattributed / legacy charges. |
| `flow` | string | no | CSV of flow UUIDs of this account (from the immutable checkout session version), or none for direct checkout / legacy. A malformed value is a 400 "Invalid flow filter"; a flow of another account or an unknown one is a 400 "Unknown flow filter". |
| `affiliate` | string | no | CSV of affiliate UUIDs of this account (immutable payment attribution), or none for no affiliate. A malformed value is a 400 "Invalid affiliate filter"; an unknown or foreign id is a 400 "Unknown affiliate filter". Disabled affiliates of the account stay valid. |
| `subscription` | string | no | CSV of subscription product UUIDs. |
| `cycle` | string | no | CSV of charge cycles (1 to 3 digits each; 0 = the straight sale), max 200 chars. |
| `cycleMin` | string (integer) | no | Charge cycle >= (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Charge cycle <= (1 to 6 digits). |
| `engine` | string (CSV enum) | no | subscription\|legacy\|external. |
| `subStatus` | string (CSV enum) | no | Sub status, CSV of active\|paused\|failed\|cancelled\|completed\|expired. |
| `attachedBy` | string (CSV enum) | no | auto\|manual\|legacy\|optin. |
| `due` | string (enum) | no | Next charge: overdue\|24h\|7d (one value). |
| `endCause` | string | no | Sub end cause, CSV (max 1000 chars). |
| `subCreatedFrom` | string | no | Sub created from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subCreatedTo` | string | no | Sub created to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedFrom` | string | no | Sub ended from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedTo` | string | no | Sub ended to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `schedule` | string | no | CSV of schedule (day) UUIDs. |
| `scheduleStatus` | string (CSV enum) | no | Schedule status, CSV of scheduled\|processing\|partial\|paused\|done\|cancelled. |
| `scheduleType` | string (CSV enum) | no | subscription\|auto\|manual. |
| `dayFrom` | string | no | Schedule run day from, YYYY-MM-DD. |
| `dayTo` | string | no | Schedule run day to, YYYY-MM-DD. |
| `entryStatus` | string (CSV enum) | no | Charge state of the schedule entry, CSV of scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed. |
| `entryReason` | string | no | Decline reason of the schedule entry, CSV (max 4000 chars). |
| `refund` | string (CSV enum) | no | Refund event kind, CSV of refund\|chargeback\|rdr\|ethoca. Narrows the refund figures to those events and dates the range on the refund event. |
| `refundBasis` | string (enum) | no | refund (default) \| charge: date the refund events by the refund or by the charge. |
| `refunded` | string (CSV enum) | no | Refunded state flag: true\|false. |
| `refundStatus` | string (CSV enum) | no | Refund row status, CSV of approved\|pending\|declined\|error\|unknown\|cancelled. |
| `refundTest` | string (enum) | no | Test refunds: exclude (same as absent) \| include \| only. |
| `q` | string | no | Search (max 200 chars): e-mail, name or order id contain it; a phone-shaped term (6 or more digits) matches the phone digits; exactly 4 digits match the card's last four. LIKE wildcards are escaped. |
| `sort` | enum: last_seen\|first_seen\|customer\|email\|country\|card\|orders\|charges\|approved\|declined\|approval\|gross\|refunds\|chargebacks\|refunded\|cb\|net\|subs\|tags\|storefront\|latest_order; default `last_seen` | no | Server sort over the whole filtered list: last_seen (default) / first_seen (lifetime live charges), customer / email (the e-mail key), country / card / storefront / latest_order (the customer's latest live charge, the slowest sorts), orders / charges / approved / declined / approval (approved / charges, then charges) / gross / refunds / chargebacks / refunded / cb / net (the filtered figures), subs (live then total), tags (blacklisted then several-subscriptions). The e-mail breaks ties. Anything else is a 400. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |

**Response**

```json
(UTF-8 BOM)Customer,Email,Phone,Country,Card,Cards,3DS obtained,3DS ready,3DS rebill reserve,3DS used,3DS expired,Orders,Charges,Approved,Declined,Approval %,Gross,Refunds,Chargebacks,Refunded,Charged back,Net,Live subs,Subs,Blacklisted,Several subscriptions allowed,First seen (America/New_York),Last seen (America/New_York),Last storefront,Latest order
Jane Doe,jane@example.com,+15555550123,US,4111111111111111,1,single,0,0,1,0,3,4,3,1,75.0,89.97,1,0,29.99,0.00,59.98,1,2,no,no,2026-05-02 10:03:11,2026-11-17 04:12:40,https://shop.example.com/p/demo,ORD-9
```

| response field | type | description |
|---|---|---|
| `(body)` | text/csv; charset=utf-8 | UTF-8 BOM, header row, one row per customer, CRLF (RFC 4180 quoting). |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: an unknown query parameter (strict: details.formErrors names it), an unknown value of a closed vocabulary ("unknown value: ..."), a malformed number or date, a sort outside the whitelist, a reversed range pair ("<key> is before <key>"), an unknown tz, or hour without a valid tz.
- `400` {"error":"Invalid affiliate filter"} / {"error":"Unknown affiliate filter"} / {"error":"Invalid flow filter"} / {"error":"Unknown flow filter"}: an affiliate or flow value that is malformed or not of this account (checked before the handler).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `503` {"error":"Two exports are already running. Retry when one finishes.","requestId":"<id>"} (Retry-After: 1) when two exports are already streaming on this API process.

**Gotchas**

- Card: the stored value for an account administrator, first6..last4 for other member roles; a wallet charge shows its reported last four.
- Money as x.xx, booleans yes / no, dates YYYY-MM-DD HH:mm:ss in the ACCOUNT timezone named in the two date headers. A text cell starting with = + - @ (tab or CR) is prefixed with an apostrophe; numbers are left alone.
- Content-Disposition attachment; filename="clients-YYYY-MM-DD.csv"; header X-Export-Row-Limit: 150000. The download is cancelled after ten minutes.
- A whole large account takes several seconds: treat it as a download.

##### `GET /v1/customers/export-pdf-v2`

**Scope** `customers.read` - **Stream customers for a PDF export**

Streams customers (shoppers) as NDJSON rows for a PDF the caller renders itself. Streams every customer matching the filters, in the list order, as versioned NDJSON for a client-side PDF: a start frame, one row frame per customer (the GET /v1/customers row with its 3DS summary), then an end frame written only after the read completed. Charge-level keys (Transaction, Routing, Card, Customer, Subscription, Schedule and Refund groups, and from / to) narrow the FIGURES: a customer is listed when at least one of its charges matches (or, with a range, a refund event of a matching charge falls in it), and orders ... net count only the matching charges. Customer axes (customerEmail, customerThreeDs, clientBlacklisted, clientLiveSub, clientOrdersMin/Max, clientLtvMin/Max, clientFirstFrom/To, clientLastFrom/To) filter the customer's LIFETIME facts over its live charges, whatever the other filters.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | no | Start of the range (inclusive). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). Charge-level: reads the charge date (the refund event date when `refund` is set). A reversed from/to pair is a 400 "to is before from". |
| `to` | string | no | End of the range (inclusive; a bare day covers its last millisecond). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `tz` | string | no | IANA timezone the bare days and hours are read in, max 64 chars. Default America/New_York. An unknown zone is a 400 "not a known IANA timezone". |
| `hour` | string | no | CSV of hours 0..23 in tz (max 200 chars). Needs a valid tz, otherwise 400 "hour needs a valid tz". |
| `status` | string (CSV enum) | no | Charge status, CSV of approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca. failed = declined + error; completed = every charge with an outcome. |
| `source` | string (CSV enum) | no | CSV of sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell (max 100 chars). straight = sale + recovery, subscription = rebill. |
| `pass` | string (CSV enum) | no | initial\|cascade. |
| `method` | string (CSV enum) | no | card\|wallet\|wire. |
| `population` | string (CSV enum) | no | live\|test\|imported. Absent = live charges; set = the same re-target as the transactions list. |
| `credentialMode` | string (CSV enum) | no | Wire charges: mit\|cit. |
| `threeDs` | string (CSV enum) | no | 3DS outcome, CSV of applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only. |
| `declineCategory` | string | no | Decline-engine category, CSV (max 1000 chars). |
| `declineSeverity` | string (CSV enum) | no | soft\|hard. |
| `amountMin` | string (integer cents) | no | Amount >= this many cents (1 to 12 digits). |
| `amountMax` | string (integer cents) | no | Amount <= this many cents (1 to 12 digits). A max below amountMin is a 400. |
| `pricePoint` | string (CSV enum) | no | Price bucket, CSV of '1. < $25', '2. $25-49', '3. $50-74', '4. $75-99', '5. $100-149', '6. $150-199', '7. $200+'. |
| `product` | string | no | Basket product name, slug or reference, CSV (max 4000 chars). |
| `productSlug` | string | no | Basket product slug, CSV (max 4000 chars). |
| `productKey` | string | no | Product per store, CSV of <host>\|<ref> (max 4000 chars). |
| `currency` | string | no | CSV of 3-letter ISO 4217 codes (max 200 chars). |
| `gatewayTxnId` | string | no | Gateway transaction id, exact, CSV (max 4000 chars). |
| `authCode` | string | no | Auth code of any attempt, exact, CSV (max 1000 chars). |
| `descriptor` | string | no | Descriptor contains this text: the sent statement descriptor, the MID soft descriptor or name (max 128 chars). |
| `accountId` | string | no | Gateway: CSV of MID UUIDs, wallet:<walletProviderId>, wire:<bankAccountId> or none (max 4000 chars). |
| `walletProvider` | string | no | CSV of wallet provider UUIDs (alias of accountId=wallet:<id>). |
| `gatewayType` | string | no | a gateway type (the gatewayType values returned by GET /v1/accounts), CSV (max 100 chars). |
| `category` | string | no | CSV of category UUIDs: any category of the final MID. |
| `primaryCategory` | string | no | CSV of category UUIDs: the primary category of the final MID. |
| `atri` | string | no | CSV of ATRI UUIDs reached. |
| `atriFinal` | string | no | CSV of ATRI UUIDs the order ended on. |
| `processor` | string | no | CSV of processor UUIDs, or none. |
| `acquiringBank` | string | no | CSV of acquiring bank UUIDs, or none. |
| `company` | string | no | CSV of company UUIDs, or none. |
| `gatewayMcc` | string | no | Final MID MCC, CSV (max 1000 chars). |
| `gatewayBin` | string | no | Final MID acquirer BIN, CSV (max 1000 chars). |
| `brand` | string | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other, CSV (max 200 chars). |
| `paysource` | string | no | APPLEPAY / GOOGLEPAY (wallet payload), CSV (max 100 chars). |
| `funding` | string | no | Prepaid / Debit / Credit / Charge card (or a wallet), CSV (max 200 chars). |
| `cardType` | string | no | BIN card type (or a wallet), CSV (max 200 chars). |
| `cardLevel` | string | no | BIN card level (or a wallet), CSV (max 4000 chars). |
| `issuer` | string | no | Issuing bank, RFC 4180 CSV (max 4000 chars). |
| `bin` | string | no | CSV of 6-digit BINs or a wallet label (Apple Pay, Google Pay), max 4000 chars. Another value is a 400 "unknown value". |
| `first6` | string | no | Card prefix, 1 to 6 digits. |
| `last4` | string | no | Card suffix, 1 to 4 digits. |
| `country` | string | no | Billing country (ISO-2), CSV (max 2000 chars). |
| `storefront` | string | no | Store host bucket or (direct), CSV (max 4000 chars). The value __no_store__ selects canonical standalone orders (immutable order context), not a blank URL. |
| `traffic` | string | no | Traffic source or (direct/organic), CSV (max 2000 chars). |
| `utmSource` | string | no | UTM source, case-insensitive, CSV (max 4000 chars). |
| `utmCampaign` | string | no | UTM campaign, case-insensitive, CSV (max 4000 chars). |
| `device` | string | no | Mobile / Tablet / Desktop, CSV (max 200 chars). |
| `os` | string | no | Operating system, CSV (max 200 chars). |
| `browser` | string | no | Browser, CSV (max 200 chars). |
| `ipType` | string (CSV enum) | no | IPv4\|IPv6. |
| `ip` | string | no | CSV of customer IPs (max 2000 chars). |
| `email` | string | no | Charge e-mail contains this text (max 200 chars). |
| `phone` | string | no | Phone contains this text (max 40 chars). |
| `firstName` | string | no | First name contains this text (max 120 chars). |
| `lastName` | string | no | Last name contains this text (max 120 chars). |
| `customerEmail` | string | no | Client axis: CSV of exact e-mails, case-insensitive (max 4000 chars); a value without @ is dropped. |
| `customerThreeDs` | string (CSV enum) | no | Client axis: customer authentication inventory now, CSV of with-ready\|without-ready\|single\|double\|ready-for-rebill (single / double count proofs obtained, used ones included). |
| `clientBlacklisted` | string (enum) | no | Client axis: true\|false. Blacklisted by e-mail or by a card the customer paid with. |
| `clientLiveSub` | string (enum) | no | Client axis: true\|false. Has a live (active or paused) subscription. |
| `clientOrdersMin` | string (integer) | no | Client axis: lifetime distinct orders >= (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Client axis: lifetime distinct orders <= (1 to 12 digits). |
| `clientLtvMin` | string (integer cents) | no | Client axis: lifetime gross >= this many cents (1 to 12 digits). |
| `clientLtvMax` | string (integer cents) | no | Client axis: lifetime gross <= this many cents (1 to 12 digits). |
| `clientFirstFrom` | string | no | Client axis: first seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientFirstTo` | string | no | Client axis: first seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastFrom` | string | no | Client axis: last seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastTo` | string | no | Client axis: last seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `checkout` | string | no | CSV of checkout UUIDs at sale, or none for unattributed / legacy charges. |
| `flow` | string | no | CSV of flow UUIDs of this account (from the immutable checkout session version), or none for direct checkout / legacy. A malformed value is a 400 "Invalid flow filter"; a flow of another account or an unknown one is a 400 "Unknown flow filter". |
| `affiliate` | string | no | CSV of affiliate UUIDs of this account (immutable payment attribution), or none for no affiliate. A malformed value is a 400 "Invalid affiliate filter"; an unknown or foreign id is a 400 "Unknown affiliate filter". Disabled affiliates of the account stay valid. |
| `subscription` | string | no | CSV of subscription product UUIDs. |
| `cycle` | string | no | CSV of charge cycles (1 to 3 digits each; 0 = the straight sale), max 200 chars. |
| `cycleMin` | string (integer) | no | Charge cycle >= (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Charge cycle <= (1 to 6 digits). |
| `engine` | string (CSV enum) | no | subscription\|legacy\|external. |
| `subStatus` | string (CSV enum) | no | Sub status, CSV of active\|paused\|failed\|cancelled\|completed\|expired. |
| `attachedBy` | string (CSV enum) | no | auto\|manual\|legacy\|optin. |
| `due` | string (enum) | no | Next charge: overdue\|24h\|7d (one value). |
| `endCause` | string | no | Sub end cause, CSV (max 1000 chars). |
| `subCreatedFrom` | string | no | Sub created from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subCreatedTo` | string | no | Sub created to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedFrom` | string | no | Sub ended from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedTo` | string | no | Sub ended to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `schedule` | string | no | CSV of schedule (day) UUIDs. |
| `scheduleStatus` | string (CSV enum) | no | Schedule status, CSV of scheduled\|processing\|partial\|paused\|done\|cancelled. |
| `scheduleType` | string (CSV enum) | no | subscription\|auto\|manual. |
| `dayFrom` | string | no | Schedule run day from, YYYY-MM-DD. |
| `dayTo` | string | no | Schedule run day to, YYYY-MM-DD. |
| `entryStatus` | string (CSV enum) | no | Charge state of the schedule entry, CSV of scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed. |
| `entryReason` | string | no | Decline reason of the schedule entry, CSV (max 4000 chars). |
| `refund` | string (CSV enum) | no | Refund event kind, CSV of refund\|chargeback\|rdr\|ethoca. Narrows the refund figures to those events and dates the range on the refund event. |
| `refundBasis` | string (enum) | no | refund (default) \| charge: date the refund events by the refund or by the charge. |
| `refunded` | string (CSV enum) | no | Refunded state flag: true\|false. |
| `refundStatus` | string (CSV enum) | no | Refund row status, CSV of approved\|pending\|declined\|error\|unknown\|cancelled. |
| `refundTest` | string (enum) | no | Test refunds: exclude (same as absent) \| include \| only. |
| `q` | string | no | Search (max 200 chars): e-mail, name or order id contain it; a phone-shaped term (6 or more digits) matches the phone digits; exactly 4 digits match the card's last four. LIKE wildcards are escaped. |
| `sort` | enum: last_seen\|first_seen\|customer\|email\|country\|card\|orders\|charges\|approved\|declined\|approval\|gross\|refunds\|chargebacks\|refunded\|cb\|net\|subs\|tags\|storefront\|latest_order; default `last_seen` | no | Server sort over the whole filtered list: last_seen (default) / first_seen (lifetime live charges), customer / email (the e-mail key), country / card / storefront / latest_order (the customer's latest live charge, the slowest sorts), orders / charges / approved / declined / approval (approved / charges, then charges) / gross / refunds / chargebacks / refunded / cb / net (the filtered figures), subs (live then total), tags (blacklisted then several-subscriptions). The e-mail breaks ties. Anything else is a 400. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |

**Response**

```json
{"type":"start","version":2}
{"type":"row","row":{"email":"jane@example.com","first_name":"Jane","last_name":"Doe","orders":3,"gross_cents":8997,"net_cents":5998,"threeDsSummary":{"total":1,"ready":0,"used":1,"expired":0,"pending":0,"failed":0,"readyForRebill":0,"authenticationMode":"single"}}}
{"type":"end","version":2,"count":1}
```

| response field | type | description |
|---|---|---|
| `{"type":"start","version":2}` | frame | First line. |
| `{"type":"row","row":{...}}` | frame | One per customer, list order: the customer row fields of GET /v1/customers. |
| `{"type":"end","version":2,"count":n}` | frame | Last line, written only after the read committed; count = row frames sent. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: an unknown query parameter (strict: details.formErrors names it), an unknown value of a closed vocabulary ("unknown value: ..."), a malformed number or date, a sort outside the whitelist, a reversed range pair ("<key> is before <key>"), an unknown tz, or hour without a valid tz.
- `400` {"error":"Invalid affiliate filter"} / {"error":"Unknown affiliate filter"} / {"error":"Invalid flow filter"} / {"error":"Unknown flow filter"}: an affiliate or flow value that is malformed or not of this account (checked before the handler).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Two exports are already running. Retry when one finishes.","requestId":"<id>"} (Retry-After: 1) when two exports are already streaming on this API process.

**Gotchas**

- Complete or error: a stream without the final {"type":"end"} frame is incomplete and must be discarded.
- Limits: 250000 rows, 128 MiB of source, 1 MiB per row, ten minutes. Exceeding one aborts the stream without the end frame (the HTTP status is already 200).
- Content-Type application/x-ndjson, Cache-Control no-store.
- masked_card is masked first6..last4 for member roles other than account administrators.

##### `GET /v1/customers/ids`

**Scope** `customers.read` - **List customer ids (select all matching)**

Lists the e-mails of every customer (shopper) matching the filters, to select all of them for a bulk action. The e-mails of every customer matching the same filters as GET /v1/customers, in the list order, capped at 10000: the input of a bulk action on "all matching". Charge-level keys (Transaction, Routing, Card, Customer, Subscription, Schedule and Refund groups, and from / to) narrow the FIGURES: a customer is listed when at least one of its charges matches (or, with a range, a refund event of a matching charge falls in it), and orders ... net count only the matching charges. Customer axes (customerEmail, customerThreeDs, clientBlacklisted, clientLiveSub, clientOrdersMin/Max, clientLtvMin/Max, clientFirstFrom/To, clientLastFrom/To) filter the customer's LIFETIME facts over its live charges, whatever the other filters.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | no | Start of the range (inclusive). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). Charge-level: reads the charge date (the refund event date when `refund` is set). A reversed from/to pair is a 400 "to is before from". |
| `to` | string | no | End of the range (inclusive; a bare day covers its last millisecond). An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `tz` | string | no | IANA timezone the bare days and hours are read in, max 64 chars. Default America/New_York. An unknown zone is a 400 "not a known IANA timezone". |
| `hour` | string | no | CSV of hours 0..23 in tz (max 200 chars). Needs a valid tz, otherwise 400 "hour needs a valid tz". |
| `status` | string (CSV enum) | no | Charge status, CSV of approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca. failed = declined + error; completed = every charge with an outcome. |
| `source` | string (CSV enum) | no | CSV of sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell (max 100 chars). straight = sale + recovery, subscription = rebill. |
| `pass` | string (CSV enum) | no | initial\|cascade. |
| `method` | string (CSV enum) | no | card\|wallet\|wire. |
| `population` | string (CSV enum) | no | live\|test\|imported. Absent = live charges; set = the same re-target as the transactions list. |
| `credentialMode` | string (CSV enum) | no | Wire charges: mit\|cit. |
| `threeDs` | string (CSV enum) | no | 3DS outcome, CSV of applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only. |
| `declineCategory` | string | no | Decline-engine category, CSV (max 1000 chars). |
| `declineSeverity` | string (CSV enum) | no | soft\|hard. |
| `amountMin` | string (integer cents) | no | Amount >= this many cents (1 to 12 digits). |
| `amountMax` | string (integer cents) | no | Amount <= this many cents (1 to 12 digits). A max below amountMin is a 400. |
| `pricePoint` | string (CSV enum) | no | Price bucket, CSV of '1. < $25', '2. $25-49', '3. $50-74', '4. $75-99', '5. $100-149', '6. $150-199', '7. $200+'. |
| `product` | string | no | Basket product name, slug or reference, CSV (max 4000 chars). |
| `productSlug` | string | no | Basket product slug, CSV (max 4000 chars). |
| `productKey` | string | no | Product per store, CSV of <host>\|<ref> (max 4000 chars). |
| `currency` | string | no | CSV of 3-letter ISO 4217 codes (max 200 chars). |
| `gatewayTxnId` | string | no | Gateway transaction id, exact, CSV (max 4000 chars). |
| `authCode` | string | no | Auth code of any attempt, exact, CSV (max 1000 chars). |
| `descriptor` | string | no | Descriptor contains this text: the sent statement descriptor, the MID soft descriptor or name (max 128 chars). |
| `accountId` | string | no | Gateway: CSV of MID UUIDs, wallet:<walletProviderId>, wire:<bankAccountId> or none (max 4000 chars). |
| `walletProvider` | string | no | CSV of wallet provider UUIDs (alias of accountId=wallet:<id>). |
| `gatewayType` | string | no | a gateway type (the gatewayType values returned by GET /v1/accounts), CSV (max 100 chars). |
| `category` | string | no | CSV of category UUIDs: any category of the final MID. |
| `primaryCategory` | string | no | CSV of category UUIDs: the primary category of the final MID. |
| `atri` | string | no | CSV of ATRI UUIDs reached. |
| `atriFinal` | string | no | CSV of ATRI UUIDs the order ended on. |
| `processor` | string | no | CSV of processor UUIDs, or none. |
| `acquiringBank` | string | no | CSV of acquiring bank UUIDs, or none. |
| `company` | string | no | CSV of company UUIDs, or none. |
| `gatewayMcc` | string | no | Final MID MCC, CSV (max 1000 chars). |
| `gatewayBin` | string | no | Final MID acquirer BIN, CSV (max 1000 chars). |
| `brand` | string | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other, CSV (max 200 chars). |
| `paysource` | string | no | APPLEPAY / GOOGLEPAY (wallet payload), CSV (max 100 chars). |
| `funding` | string | no | Prepaid / Debit / Credit / Charge card (or a wallet), CSV (max 200 chars). |
| `cardType` | string | no | BIN card type (or a wallet), CSV (max 200 chars). |
| `cardLevel` | string | no | BIN card level (or a wallet), CSV (max 4000 chars). |
| `issuer` | string | no | Issuing bank, RFC 4180 CSV (max 4000 chars). |
| `bin` | string | no | CSV of 6-digit BINs or a wallet label (Apple Pay, Google Pay), max 4000 chars. Another value is a 400 "unknown value". |
| `first6` | string | no | Card prefix, 1 to 6 digits. |
| `last4` | string | no | Card suffix, 1 to 4 digits. |
| `country` | string | no | Billing country (ISO-2), CSV (max 2000 chars). |
| `storefront` | string | no | Store host bucket or (direct), CSV (max 4000 chars). The value __no_store__ selects canonical standalone orders (immutable order context), not a blank URL. |
| `traffic` | string | no | Traffic source or (direct/organic), CSV (max 2000 chars). |
| `utmSource` | string | no | UTM source, case-insensitive, CSV (max 4000 chars). |
| `utmCampaign` | string | no | UTM campaign, case-insensitive, CSV (max 4000 chars). |
| `device` | string | no | Mobile / Tablet / Desktop, CSV (max 200 chars). |
| `os` | string | no | Operating system, CSV (max 200 chars). |
| `browser` | string | no | Browser, CSV (max 200 chars). |
| `ipType` | string (CSV enum) | no | IPv4\|IPv6. |
| `ip` | string | no | CSV of customer IPs (max 2000 chars). |
| `email` | string | no | Charge e-mail contains this text (max 200 chars). |
| `phone` | string | no | Phone contains this text (max 40 chars). |
| `firstName` | string | no | First name contains this text (max 120 chars). |
| `lastName` | string | no | Last name contains this text (max 120 chars). |
| `customerEmail` | string | no | Client axis: CSV of exact e-mails, case-insensitive (max 4000 chars); a value without @ is dropped. |
| `customerThreeDs` | string (CSV enum) | no | Client axis: customer authentication inventory now, CSV of with-ready\|without-ready\|single\|double\|ready-for-rebill (single / double count proofs obtained, used ones included). |
| `clientBlacklisted` | string (enum) | no | Client axis: true\|false. Blacklisted by e-mail or by a card the customer paid with. |
| `clientLiveSub` | string (enum) | no | Client axis: true\|false. Has a live (active or paused) subscription. |
| `clientOrdersMin` | string (integer) | no | Client axis: lifetime distinct orders >= (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Client axis: lifetime distinct orders <= (1 to 12 digits). |
| `clientLtvMin` | string (integer cents) | no | Client axis: lifetime gross >= this many cents (1 to 12 digits). |
| `clientLtvMax` | string (integer cents) | no | Client axis: lifetime gross <= this many cents (1 to 12 digits). |
| `clientFirstFrom` | string | no | Client axis: first seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientFirstTo` | string | no | Client axis: first seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastFrom` | string | no | Client axis: last seen from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `clientLastTo` | string | no | Client axis: last seen to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `checkout` | string | no | CSV of checkout UUIDs at sale, or none for unattributed / legacy charges. |
| `flow` | string | no | CSV of flow UUIDs of this account (from the immutable checkout session version), or none for direct checkout / legacy. A malformed value is a 400 "Invalid flow filter"; a flow of another account or an unknown one is a 400 "Unknown flow filter". |
| `affiliate` | string | no | CSV of affiliate UUIDs of this account (immutable payment attribution), or none for no affiliate. A malformed value is a 400 "Invalid affiliate filter"; an unknown or foreign id is a 400 "Unknown affiliate filter". Disabled affiliates of the account stay valid. |
| `subscription` | string | no | CSV of subscription product UUIDs. |
| `cycle` | string | no | CSV of charge cycles (1 to 3 digits each; 0 = the straight sale), max 200 chars. |
| `cycleMin` | string (integer) | no | Charge cycle >= (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Charge cycle <= (1 to 6 digits). |
| `engine` | string (CSV enum) | no | subscription\|legacy\|external. |
| `subStatus` | string (CSV enum) | no | Sub status, CSV of active\|paused\|failed\|cancelled\|completed\|expired. |
| `attachedBy` | string (CSV enum) | no | auto\|manual\|legacy\|optin. |
| `due` | string (enum) | no | Next charge: overdue\|24h\|7d (one value). |
| `endCause` | string | no | Sub end cause, CSV (max 1000 chars). |
| `subCreatedFrom` | string | no | Sub created from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subCreatedTo` | string | no | Sub created to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedFrom` | string | no | Sub ended from. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `subEndedTo` | string | no | Sub ended to. An ISO instant with offset or Z, or a bare day YYYY-MM-DD read in tz (max 40 chars). |
| `schedule` | string | no | CSV of schedule (day) UUIDs. |
| `scheduleStatus` | string (CSV enum) | no | Schedule status, CSV of scheduled\|processing\|partial\|paused\|done\|cancelled. |
| `scheduleType` | string (CSV enum) | no | subscription\|auto\|manual. |
| `dayFrom` | string | no | Schedule run day from, YYYY-MM-DD. |
| `dayTo` | string | no | Schedule run day to, YYYY-MM-DD. |
| `entryStatus` | string (CSV enum) | no | Charge state of the schedule entry, CSV of scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed. |
| `entryReason` | string | no | Decline reason of the schedule entry, CSV (max 4000 chars). |
| `refund` | string (CSV enum) | no | Refund event kind, CSV of refund\|chargeback\|rdr\|ethoca. Narrows the refund figures to those events and dates the range on the refund event. |
| `refundBasis` | string (enum) | no | refund (default) \| charge: date the refund events by the refund or by the charge. |
| `refunded` | string (CSV enum) | no | Refunded state flag: true\|false. |
| `refundStatus` | string (CSV enum) | no | Refund row status, CSV of approved\|pending\|declined\|error\|unknown\|cancelled. |
| `refundTest` | string (enum) | no | Test refunds: exclude (same as absent) \| include \| only. |
| `q` | string | no | Search (max 200 chars): e-mail, name or order id contain it; a phone-shaped term (6 or more digits) matches the phone digits; exactly 4 digits match the card's last four. LIKE wildcards are escaped. |
| `sort` | enum: last_seen\|first_seen\|customer\|email\|country\|card\|orders\|charges\|approved\|declined\|approval\|gross\|refunds\|chargebacks\|refunded\|cb\|net\|subs\|tags\|storefront\|latest_order; default `last_seen` | no | Server sort over the whole filtered list: last_seen (default) / first_seen (lifetime live charges), customer / email (the e-mail key), country / card / storefront / latest_order (the customer's latest live charge, the slowest sorts), orders / charges / approved / declined / approval (approved / charges, then charges) / gross / refunds / chargebacks / refunded / cb / net (the filtered figures), subs (live then total), tags (blacklisted then several-subscriptions). The e-mail breaks ties. Anything else is a 400. |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |

**Response**

```json
{
  "ids": [
    "jane@example.com",
    "john@example.com"
  ],
  "capped": false
}
```

| response field | type | description |
|---|---|---|
| `ids` | string[] | Client e-mails (lower-cased), list order, max 10000. |
| `capped` | boolean | True when 10000 were returned (more may match). |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: an unknown query parameter (strict: details.formErrors names it), an unknown value of a closed vocabulary ("unknown value: ..."), a malformed number or date, a sort outside the whitelist, a reversed range pair ("<key> is before <key>"), an unknown tz, or hour without a valid tz.
- `400` {"error":"Invalid affiliate filter"} / {"error":"Unknown affiliate filter"} / {"error":"Invalid flow filter"} / {"error":"Unknown flow filter"}: an affiliate or flow value that is malformed or not of this account (checked before the handler).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Customer reads are busy. Please retry shortly.","requestId":"<id>"} (Retry-After: 1) when the customer read queue is full or a queued read waited past its budget; retry shortly.
- `504` The read exceeded its 25-second request budget and was cancelled ("The request took too long and was cancelled ..."); narrow the filters and retry.

**Gotchas**

- No limit / offset: sending them is a 400 (strict).
- E-mails travel only in this JSON body, never in a path.

##### `GET /v1/subscription/customer`

**Scope** `subscriptions.read` - **Customer view by order id or e-mail**

Same customer view as /subs/:id/customer, addressed by an order id or an e-mail (the shared customer modal of any page). With an e-mail only, the most recent NMI order of that e-mail in the account is used; the order must belong to the account. v3.9.2 section 1: `runs` - the sale pipeline runs of every order the history lists (+ the sub's own order), newest first, <= 200, REFUSALS INCLUDED (a charge refused before any MID - cooldown, scrub, the duplicate-card guard - has a run and no transaction, so it shows here for the first time) - and `runNames`, the ATRI / MID names the runs cite. v3.9.2 section 3: `subs` lists EVERY sub of the CUSTOMER (order  union  e-mail  union  card, every product, live first - docs/SUBSCRIPTIONS.md section 3.6), no longer the subs of one order, and `customer_ref` is the key of the /v1/customers/:key/* routes (the resolved order id). v3.9.15: `history_capped` - the history lists the latest 300 charges; true when more exist.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `orderId` | string | no | Trimmed 1..120 chars. One of orderId / email is required. |
| `email` | string | no | A syntactically valid e-mail, <= 200 chars (case-insensitive lookup). v3.9.8 item 1 - resolves to the customer's latest CARD order, else (a customer who only paid with Apple Pay / Google Pay) their latest order of any kind; it answered 404 for such a customer. |

**Response**

```json
{
  "customer": {
    "email": "jane@example.com",
    "first_name": "Jane",
    "last_name": "Doe",
    "phone": "+15555550123",
    "address1": "1 Main St",
    "city": "Austin",
    "state": "TX",
    "zip": "78701",
    "country": "US",
    "ip": "203.0.113.7",
    "masked_card": "411111******1111",
    "ccexp": "0928",
    "card_brand": "VISA"
  },
  "sale": {
    "id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
    "order_id": "ORD-118842",
    "created_at": "2026-08-19T15:07:44.000Z",
    "amount_cents": 4999,
    "currency": "USD",
    "status": "approved",
    "is_success": true,
    "decline_reason": null,
    "final_account_name": "MID US 01",
    "masked_card": "411111******1111",
    "storefront_url": "https://shop.example.com/checkout",
    "refunded": false,
    "charged_back": false,
    "kind": "sale",
    "cycle": null,
    "subscription_name": null,
    "crm": "nmi",
    "dispute_kind": null,
    "wallet_provider_id": null,
    "pre_gateway": false,
    "paysource": null
  },
  "subs": [
    {
      "id": "2d3e4f50-6a7b-4c8d-9e0f-1a2b3c4d5e6f",
      "owner_email": "ops@example.com",
      "subscription_id": "a1d2c3b4-0000-4e11-9c4d-2b7f8e9a1c33",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00000001",
      "email": "jane@example.com",
      "amount_cents": 6999,
      "status": "active",
      "cycle": 2,
      "retry_step": 0,
      "next_charge_at": "2026-10-19T15:07:00.000Z",
      "current_entry_id": "0f1e2d3c-4b5a-4968-8776-655443322110",
      "last_charge_at": "2026-09-19T15:07:05.210Z",
      "last_status": "rebill_success",
      "last_decline_reason": null,
      "source": "auto",
      "attached_by": "sale",
      "cancel_reason": null,
      "cancelled_at": null,
      "end_cause": null,
      "created_at": "2026-08-19T15:07:44.000Z",
      "updated_at": "2026-09-19T15:07:05.400Z",
      "subscription_name": "VIP Monthly",
      "interval_days": 30,
      "first_after_days": 3,
      "interval_value": 1,
      "interval_unit": "months",
      "first_after_value": 3,
      "first_after_unit": "days",
      "first_name": "Jane",
      "last_name": "Doe",
      "masked_card": "411111******1111",
      "storefront_url": "https://shop.example.com/checkout",
      "country": "US",
      "sale_at": "2026-08-19T15:07:44.000Z",
      "sale_amount_cents": 4999,
      "sale_mid": "MID US 01",
      "card_brand": "VISA",
      "entry_status": "scheduled",
      "entry_scheduled_at": "2026-10-19T15:07:00.000Z",
      "entry_amount_cents": 6999,
      "product_slug": "vip-bundle",
      "product_name": "VIP Bundle",
      "last_charge_amount_cents": 6999,
      "total": 1
    }
  ],
  "history": [
    {
      "id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "order_id": "ORD-118842",
      "created_at": "2026-09-19T15:07:05.210Z",
      "amount_cents": 6999,
      "currency": "USD",
      "status": "approved",
      "is_success": true,
      "decline_reason": null,
      "final_account_name": "MID US 02",
      "masked_card": "411111******1111",
      "storefront_url": null,
      "refunded": false,
      "charged_back": false,
      "kind": "subscription",
      "cycle": 2,
      "subscription_name": "VIP Monthly",
      "crm": "nmi",
      "dispute_kind": null,
      "wallet_provider_id": null,
      "pre_gateway": false,
      "paysource": null
    }
  ],
  "history_capped": false,
  "products": [
    {
      "slug": "vip-bundle",
      "name": "VIP Bundle",
      "quantity": 1,
      "amount_cents": 4999
    }
  ],
  "runs": [
    {
      "id": "5e4d3c2b-1a09-4f8e-8d7c-6b5a49382716",
      "created_at": "2026-09-25T09:12:40.000Z",
      "order_id": "ORD-118842",
      "transaction_id": null,
      "rejection_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
      "run_no": 1,
      "resumed_from": null,
      "flow": "rebill",
      "channel": "rebill-auto",
      "trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "final_trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "bin": "411111",
      "issuer_key": "JPMORGAN CHASE",
      "card_brand": "Visa",
      "card_funding": "Debit",
      "country": "US",
      "amount_cents": 6999,
      "outcome": "rejected",
      "refused_by": "card_cooldown",
      "fell_through": false,
      "stages": [
        {
          "name": "context",
          "input": {
            "orderId": "ORD-118842",
            "flow": "rebill",
            "channel": "rebill-auto",
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "brand": "visa",
            "country": "US",
            "binSource": "warm",
            "reads": 0
          },
          "decision": {
            "action": "resolve",
            "applied": true
          },
          "durationUs": 880
        },
        {
          "name": "refusals",
          "input": {
            "flow": "rebill",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "rules": "blacklist,precheck,duplicate_card",
            "scrubbing": null
          },
          "decision": {
            "action": "refuse",
            "applied": true,
            "reason": "duplicate_card: Duplicate card: order ORD-118840 already declined today in this..."
          },
          "durationUs": 2900
        },
        {
          "name": "rebill_rules",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "mapping",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "route",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "threeds",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        },
        {
          "name": "send",
          "skipped": "short_circuit",
          "input": {},
          "decision": {
            "action": "skipped",
            "applied": false,
            "reason": "refused: card_cooldown"
          },
          "durationUs": 0
        }
      ],
      "total_us": 4100,
      "t_claim_us": null,
      "t_first_send_us": null,
      "t_completed_us": null
    },
    {
      "id": "0a9b8c7d-6e5f-4a4b-8c3d-2e1f0a9b8c7d",
      "created_at": "2026-09-19T15:07:05.210Z",
      "order_id": "ORD-118842",
      "transaction_id": "c0ffee00-aaaa-4bbb-8ccc-dddd00001111",
      "rejection_id": null,
      "run_no": 1,
      "resumed_from": null,
      "flow": "rebill",
      "channel": "rebill-auto",
      "trip_id": "0e7bce71-1111-4222-8333-444455556666",
      "final_trip_id": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
      "bin": "411111",
      "issuer_key": "JPMORGAN CHASE",
      "card_brand": "Visa",
      "card_funding": "Debit",
      "country": "US",
      "amount_cents": 6999,
      "outcome": "approved",
      "refused_by": null,
      "fell_through": true,
      "stages": [
        {
          "name": "context",
          "input": {
            "orderId": "ORD-118842",
            "flow": "rebill",
            "channel": "rebill-auto",
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "bin": "411111",
            "issuerKey": "JPMORGAN CHASE",
            "brand": "visa",
            "country": "US",
            "binSource": "warm",
            "reads": 0
          },
          "decision": {
            "action": "resolve",
            "applied": true
          },
          "durationUs": 910
        },
        {
          "name": "route",
          "input": {
            "tripId": "0e7bce71-1111-4222-8333-444455556666",
            "defaultTripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
            "brand": "visa",
            "pinOnly": false,
            "pin": null,
            "mappingPool": 0,
            "mappingSingle": null,
            "strategy": "random",
            "candidates": 4,
            "eligible": 0,
            "level": "default"
          },
          "decision": {
            "action": "fallthrough",
            "applied": true,
            "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
            "pool": [
              "c1d2e3f4-a5b6-4788-9900-aabbccddeeff"
            ],
            "pool_n": 1,
            "reason": "fallthrough: no MID supports visa -> default ATRI"
          },
          "durationUs": 402000
        },
        {
          "name": "send",
          "input": {
            "tripId": "481c0a6e-4107-4128-99bd-6d52ac4362e5",
            "strategy": "random",
            "ordered": 1,
            "pinned": null,
            "cascadeTripId": null,
            "retryWithoutThreeDs": false,
            "threeDs": null
          },
          "decision": {
            "action": "charge",
            "applied": true,
            "chosen": "c1d2e3f4-a5b6-4788-9900-aabbccddeeff",
            "pool_n": 1,
            "reason": "approved on MID-EU-03 (1 attempt)"
          },
          "durationUs": 1977000
        }
      ],
      "total_us": 2610000,
      "t_claim_us": 6200,
      "t_first_send_us": 421000,
      "t_completed_us": 2610000
    }
  ],
  "runNames": {
    "trips": {
      "0e7bce71-1111-4222-8333-444455556666": "US Rebill",
      "481c0a6e-4107-4128-99bd-6d52ac4362e5": "US Straight Sale"
    },
    "mids": {
      "c1d2e3f4-a5b6-4788-9900-aabbccddeeff": "MID-EU-03"
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `customer` | object | {email, first_name, last_name, phone, address1, city, state, zip, country, ip, masked_card, ccexp, card_brand} from the original card-on-file sale. |
| `sale` | object\|null | The original sale as a CustomerTxnRow: {id, order_id, created_at, amount_cents, currency, status, is_success, decline_reason, final_account_name, masked_card, storefront_url, refunded, charged_back, crm, dispute_kind, wallet_provider_id, paysource, kind:'sale'\|'subscription', cycle, subscription_name} (the example's `pre_gateway` is a column still selected until it is dropped - always false on a listed row, read by nothing). |
| `subs` | array | Every sub of the order (live and ended), as SubDetailRow (see GET /v1/subscription/subs). v3.9.12: each row carries product_atri_split (what a Force bill's "Use original" takes). |
| `history` | array | Up to 300 transactions of the account for this order OR the same e-mail, newest first (sales and subscription charges, kind tells which). Each row is a CustomerTxnRow plus the facts the row's ... menu gates on: crm, dispute_kind (rdr \| ethoca \| null), wallet_provider_id, paysource - the same actions as the transaction modal (refund, external refund, RDR / Ethoca, retry, blacklist, chargeback). v3.9 section 1: `pre_gateway` no longer gates anything (a refusal before any MID is not a transaction); the column still appears in the payload, always false, until it is dropped. v3.9.8 item 1 - plus wallet_kind, card_brand, card_last4: a wallet charge's Card cell names its wallet (Apple Pay / Google Pay) with the card it reported, never ' - '. |
| `history_capped` | boolean | True when the customer has more than the 300 charges `history` lists (the view says so and links to /transactions with customerEmail). |
| `products` | array | [{slug, name, quantity, amount_cents}] the sale's basket. |
| `runs` | array | v3.9.2 section 1 - the sale pipeline runs (sale_pipeline_runs, 30 days kept) of the customer's orders: owner-scoped, newest first, at most 200. Each is a PIPELINE_RUN (fields below). Empty on a database without the table. |
| `PIPELINE_RUN.id / created_at / order_id / transaction_id / rejection_id` | uuid / string / string / uuid \| null / uuid \| null | One sale pipeline run (sale_pipeline_runs, migration 148). transaction_id is null for a refusal (no transactions row, v3.9 section 1) and for a discarded 3DS-policy row; rejection_id is the charge_rejections row when refused. |
| `PIPELINE_RUN.run_no / resumed_from` | integer / uuid \| null | A 3DS challenge re-submit RESUMES the run that parked: run_no 2, resumed_from = run 1 (its stages 2-4 copied as skipped: "resumed", never re-evaluated). |
| `PIPELINE_RUN.flow / channel / trip_id / final_trip_id` | string \| null ... | flow initial \| rebill; trip_id = the ATRI resolved at the start, final_trip_id = after a mapping redirect / the fall-through to the account's default ATRI (an ATRI with no eligible MID for the card never ends the charge any more). |
| `PIPELINE_RUN.bin / issuer_key / card_brand / card_funding / country / amount_cents` | scalars | The context the rules matched on: first 6 digits only, the canonical issuer key, the brand, funding and country from the bin_info preload / the payload. Never a PAN. |
| `PIPELINE_RUN.outcome / refused_by / fell_through` | enum / string \| null / boolean | outcome in approved \| declined \| error \| rejected \| parked \| replayed \| unknown; refused_by = the rejection family when rejected; fell_through = at least one stage ended in a fall-through (a technical problem routed around - the "never refused for a technical reason" counter). |
| `PIPELINE_RUN.stages[]` | array | The ordered stages - context, refusals, rebill_rules, mapping, route, threeds, send (9 entries when a cascade route/send pair was appended): { name, skipped? (not_applicable \| short_circuit \| resumed), input (ids and scalars, <= 256 B), decision: { action, applied, reason (<= 80 chars), profileId?, ruleId?, matchType?, pool (<= 5 ids), pool_n, chosen?, redirectTripId? } \| null, durationUs, error? ("timeout" \| "error" = the stage failed open) }. The whole array is <= 4 096 bytes. Every stage's vocabulary: docs/SALE_FLOW.md section 5. |
| `PIPELINE_RUN.total_us / t_claim_us / t_first_send_us / t_completed_us` | integer \| null | Microseconds from the request's receipt (the scheduler's claim instant for a Subscription charge): the result, the claim (start of stage 5), the first gateway send, the finalize. total_us is always set (a refusal has a real total: the cost of the gates); t_claim_us / t_first_send_us / t_completed_us are null for a refusal (no claim); all four are null for a swept "abandoned claim" run. |
| `runNames` | object | { trips: { <atri id>: name }, mids: { <mid id>: name } } - every ATRI / MID the runs' stages cite, resolved for display. |
| `customer_ref` | string | v3.9.2 section 3 - the order the view landed on; the key of GET /v1/customers/:key/subscriptions, /events, /events/export.csv and POST /v1/customers/:key/flag. |

**Errors**

- `400` {"error":"orderId or email required"} - neither given, OR any validation failure (e.g. a malformed e-mail) - the message is the same.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"subscriptions"} when the account's plan does not include that module.
- `404` {"error":"Not found"} - no NMI order for that e-mail in the account, or the order belongs to another account.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- A malformed e-mail does not say "invalid email" - it returns the generic 400 "orderId or email required".
- With both parameters, orderId wins for the order and email is used as the history e-mail.
- subs is empty (not 404) for an order that never had a sub - the endpoint works for any card-on-file order of the account.
- `history` is the latest 300 charges (order  union  e-mail, account-wide); `history_capped` says when there are more. The Clients KPI strip reads GET /v1/customers/:key/summary instead (the list's own figures).

#### Refunds and disputes

Search transactions, refund (money moves), mark as refunded (no money moves), chargebacks, RDR and Ethoca, test refunds and the refund log.

- The refund log and search exports are built in the browser from `GET /v1/refunds` and `POST /v1/refund/search`.

##### `POST /v1/refund`

**Scope** `refunds.write` - **Refund a transaction**

Refunds a card (NMI, ConvesioPay S2S, Stripe) or wallet (ConvesioPay) charge on its original gateway: the whole refundable balance, or a partial amount. The intent is committed before the provider is called, keyed by idempotencyKey, so a lost answer can be read back with GET /v1/refund/status without risking a second refund. An unsettled same-day NMI charge refunded in full is voided instead.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | string (uuid) | **yes** | REQUIRED. The `transactionId` from /v1/refund/search or /v1/transactions. Must be a valid UUID or you get 400. |
| `amount` | number (major units) | no | Amount to refund in major units (49.99). Omitted = the whole refundable balance. Must not exceed the balance left once pending and unresolved refunds are counted (422). Partial refunds are honoured. |
| `idempotencyKey` | string | **yes** | Required, 8-128 characters, unique across ALL refunds (not per transaction). Resending the same key returns the stored outcome (replayed true) and never refunds twice. The same key on another transaction, or with a different amount, answers 409. |
| `requestedBy` | string | no | Optional actor label, max 128 chars. Stored on the refund audit row and used as the blacklist actor. Defaults to null on the refund row and to the literal `system` for the blacklist entry. |
| `reason` | string | no | Optional free text, max 512 chars. Stored on the refund audit row and used as the blacklist reason (defaults to the literal `Refund` there). |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "idempotencyKey": "crm-refund-100482-a91f",
 "requestedBy": "agent:lisa.m",
 "reason": "Customer requested cancellation"
}
```

**Response**

```json
{
  "refundId": "00000000-0000-4000-8000-000000000801",
  "status": "approved",
  "success": true,
  "method": "refund",
  "amount": 49.99,
  "nmiRefundId": "10344120557",
  "message": "Refund confirmed by provider",
  "replayed": false,
  "investigationRequired": false,
  "cleanupPending": true
}
```

| response field | type | description |
|---|---|---|
| `status` | string | approved, declined, or unknown (HTTP 202: the provider outcome is not confirmed). Failures before dispatch use not_dispatched with an error field. |
| `success` | boolean | true only for an approved refund. |
| `method` | string | refund or void (unsettled same-day NMI charge refunded in full). |
| `amount` | number | Refunded amount in major units. |
| `replayed` | boolean | true when the answer is the stored outcome of an earlier call with the same idempotencyKey. |
| `investigationRequired` | boolean | true while the outcome is unknown: do not submit another refund; read GET /v1/refund/status later. |
| `cleanupPending` | boolean | true after an approval while the follow-up steps (customer blacklist when the account's refund auto-add setting is on) are still queued. |

**Errors**

- `202` Not an error: `{"status":"unknown","success":false,"investigationRequired":true,"message":"Refund outcome unconfirmed. Do not submit another refund; investigate the original provider operation."}` when the provider answer could not be confirmed.
- `400` `{"error":"Invalid request","details":{...}}` when transactionId is not a UUID, idempotencyKey is missing or outside 8-128 characters, amount is not positive, or requestedBy / reason is too long.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `403` `{"success":false,"status":"not_dispatched","error":"Refund authorization changed; reload the original account"}` when the key or its owner changed while the refund was being admitted.
- `404` `{"error":"Transaction not found"}`.
- `409` Body `{"success":false,"status":"not_dispatched","error":...}` with `Idempotency key belongs to another transaction`, `Idempotency key has a different refund amount`, `Idempotency key belongs to a test refund`, or (test secret) `Live guarded refund cannot be replayed in test mode`.
- `422` Body `{"success":false,"status":"not_dispatched","error":...}` with `Transaction is not eligible for a gateway refund` (not approved, no gateway id, unsupported gateway), `Verification reversals use the pre-auth workflow`, `Refund owner unavailable`, `Nothing left to refund`, `Amount exceeds refundable balance`, `Unresolved refund reserves this balance; investigate its original operation` (or `... part of this balance ...`), or `Refund credentials unavailable; no request was dispatched`.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"success":false,"status":"unknown","investigationRequired":true,"error":"Refund admission unconfirmed"}` when the intent could not be confirmed as committed (resend the SAME idempotencyKey to learn the outcome); `{"error":"Refund endpoint not configured"}` on the shared-secret path without configured secrets.

**Gotchas**

- A provider decline answers HTTP 200 with success false and status declined (not 422). Always branch on success / status, not on the HTTP code alone.
- HTTP 202 status unknown means the money may or may not have moved. Never retry with a new idempotencyKey; read GET /v1/refund/status?transactionId=...&idempotencyKey=... until it resolves.
- Idempotency keys are global: build them from the transaction id and the amount (for example refund:<transactionId>:<cents>).
- An earlier call that ended in error is not re-sent: it is converted to unknown and needs investigation.
- After an approval, the customer e-mail and card are blacklisted by a follow-up step when the account setting blacklistRefundAutoAdd is on (cleanupPending true until done).
- Imported orders have no gateway id (422); record a partner-side refund on them with POST /v1/refund/mark.
- All money in and out is in major units.
- Test secret calls (X-Refund-Key test) run the simulated engine: an approved TEST refund is stored and visible but no provider is called and nothing is blacklisted; undo with POST /v1/refund/cancel-test.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.

##### `POST /v1/refund/cancel-test`

**Scope** `refunds.write` - **Cancel TEST refunds (one refund, or every test refund of a transaction)**

Cancels TEST refunds: one refund by refundId, or every test refund of a transaction by transactionId; live refunds are never touched. Undo refunds / chargebacks created with the TEST key: by `refundId` (one) or by `transactionId` (EVERY test refund of that transaction, test chargebacks included). Reverts the transaction (refunded totals, charged_back / dispute labels recomputed) and marks the refund row(s) `cancelled`. Only is_test rows. No payment provider is called.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `refundId` | string (uuid) | no | Cancel this one TEST refund. Send this OR `transactionId`. |
| `transactionId` | string (uuid) | no | Cancel every TEST refund of this transaction (test chargebacks included). Send this OR `refundId`. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884"
}
```

**Response**

```json
{
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "cancelled": ["3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884"],
 "reverted": true
}
```

| response field | type | description |
|---|---|---|
| `refundId` | string (uuid) | Echo. |
| `status` | string | `cancelled`. |
| `reverted` | boolean | true when the transaction was un-refunded by this call; false when the refund was already cancelled (idempotent). |
| `transactionId` | string (uuid) - by-transaction form | Echo. |
| `cancelled` | string[] - by-transaction form | The test refund ids that were cancelled (empty = nothing to cancel, still 200). |

**Errors**

- `400` Neither `refundId` nor `transactionId` sent (or not uuids).
- `400` `refundId` not a UUID.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{ "error": "Refund not found" }`.
- `422` Not a TEST refund - real refunds cannot be cancelled here.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- Only TEST-tagged refunds. A LIVE refund (or an external mark) returns 422 - there is no partner-side undo for real refunds.
- Idempotent: cancelling twice returns 200 with `reverted: false`.
- The dashboard shows the same TEST badge and a 'Cancel test' button; either side can cancel.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.

##### `POST /v1/refund/chargeback`

**Scope** `refunds.write` - **Mark or unmark a refund as a chargeback**

Marks or unmarks one REFUND (by refundId) as a chargeback, bookkeeping only; to mark a transaction that was never refunded, use POST /v1/transactions/:transactionId/chargeback. Reclassify an EXISTING successful refund as a chargeback (or revert it). Bookkeeping only - no money moves and no gateway is called. Moves the refund's amount and fee from the refund buckets to the chargeback buckets in finance reporting, and keeps `transactions.charged_back` in sync so orders can be labelled/filtered.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `refundId` | string (uuid) | **yes** | REQUIRED. The id of the REFUND row (the `refundId` returned by POST /v1/refund), not a transaction id. Must be a syntactically valid UUID or you get 400. |
| `chargeback` | boolean | **yes** | REQUIRED. `true` marks the refund as a chargeback; `false` unmarks it. There is no default - omitting it is a 400. Must be a real JSON boolean; `"true"` as a string is rejected. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884",
 "chargeback": true
}
```

**Response**

```json
{
 "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884",
 "isChargeback": true,
 "fee": 15.0
}
```

| response field | type | description |
|---|---|---|
| `refundId` | string (uuid) | Echo of the refund that was reclassified. |
| `isChargeback` | boolean | The state now in effect - echoes the `chargeback` you sent. |
| `fee` | number (major units) | The chargeback/refund fee now recorded on the refund row, in DOLLARS (the engine's internal `feeCents` converted with fromCents). 0 when the card brand is amex/discover/unknown or the MID has no fee configured. |

**Errors**

- `400` `{ "error": "Invalid request", "details": <zod flatten()> }` - `refundId` is not a UUID, or `chargeback` is missing / not a boolean.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{ "error": "Refund not found" }` - no refund row with that id. This is also what you get if you (very plausibly) passed a TRANSACTION uuid.
- `422` `{ "error": "Only successful refunds can be marked as chargebacks" }` - the refund exists but `is_success` is false (declined/errored refund).
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `500` `{ "error": "Internal Server Error", "requestId": "..." }`.
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- `refundId` is a REFUND id, not a transaction id. Passing a transaction UUID is a well-formed UUID, so it passes validation and comes back as a bare 404 with no hint about the mix-up.
- MARKING BLACKLISTS THE CUSTOMER (when the refund auto-add setting is on): the transaction's email and card are added to the blacklist with reason 'Chargeback' - the strongest abuse signal. UNMARKING (`chargeback: false`) does NOT remove that blacklist entry. A mark/unmark round trip leaves the customer blocked.
- Marking as a chargeback CLEARS any RDR/Ethoca dispute label on the refund (`dispute_kind`, and its marked_at/by) - the two classifications are mutually exclusive. Unmarking does not restore the old dispute label.
- The returned `fee` is in DOLLARS, but the underlying engine field is `feeCents`. This route is the converter; don't multiply by 100 again.
- Fee backfill: if the refund carried a 0 fee (MID fees weren't configured when it was refunded), marking recomputes a per-brand fee from the MID's Mastercard/Visa refund-fee columns. Amex/Discover/unknown brands always get 0. Unmarking restores the original 0 - a mark/unmark round trip does not leave a phantom fee.
- `transactions.charged_back` is RECOMPUTED, not just cleared: unmarking one refund leaves the order flagged if another chargeback-marked successful refund remains on it.
- No money moves and no gateway call is made. This never issues or reverses a refund; use POST /v1/refund for that.
- Idempotent-ish but not idempotency-keyed: re-sending the same `chargeback: true` succeeds again and re-triggers the blacklist call (which is itself idempotent).
- Prefer POST /v1/transactions/:transactionId/chargeback when you hold a transaction id rather than a refund id - it books the external refund itself when the transaction was never refunded.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.

##### `POST /v1/refund/mark`

**Scope** `refunds.write` - **Mark as refunded (no gateway call) + blacklist**

Record a refund, void or chargeback that the PARTNER already handled themselves (directly at the MID / bank, or a lost chargeback) WITHOUT calling any payment provider, and blacklist the customer. Books a full-remaining EXTERNAL refund (refund row `method: external`, `refundStatus`/`refunded`/`refundedAt` on the transaction, finance buckets, dashboard visibility), auto-blacklists the transaction's email + card, and with `chargeback: true` immediately reclassifies it as a chargeback exactly like POST /v1/refund/chargeback. Same engine as the dashboard's "Mark external refund" button. Works on ANY approved order, including `actionType: imported` ones that POST /v1/refund cannot reach.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | string (uuid) | **yes** | REQUIRED. The transaction to mark - `transactionId` from /v1/refund/search or /v1/transactions. Must be an approved charge with something left to refund. |
| `idempotencyKey` | string (8-128 chars) | **yes** | REQUIRED. Your unique id per mark. Re-sending the same key replays the first result (`replayed: true`) instead of booking a second refund. Keys are global across ALL refunds (engine + mark) - include the transaction id in it. |
| `chargeback` | boolean | no | Optional, default `false`. `true` = after booking the external refund, mark it as a CHARGEBACK (amount + fee move to the chargeback buckets; blacklist reason upgraded to 'Chargeback'). Must be a real JSON boolean. |
| `requestedBy` | string (<=128) | no | Optional free text: who/what initiated it (agent email, ticket ref, system name). Stored on the refund row and used as the blacklist author and the chargeback `marked_by`. Defaults to `partner-api`. |
| `reason` | string (<=512) | no | Optional free text: why. Stored on the refund row and used as the blacklist reason. Defaults to `Refunded by partner`, or `Chargeback (partner)` when `chargeback` is true. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "idempotencyKey": "crm-cb-48291-9b1f4c2e",
 "chargeback": true,
 "requestedBy": "agent@partner.com",
 "reason": "chargeback received"
}
```

**Response**

```json
{
 "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884",
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "status": "approved",
 "success": true,
 "method": "external",
 "amount": 49.99,
 "fee": 15.0,
 "isChargeback": true,
 "blacklisted": true,
 "nmiRefundId": null,
 "message": "Marked as refunded externally - no gateway call made"
}
```

| response field | type | description |
|---|---|---|
| `refundId` | string (uuid) | The refund row that was booked (method `external`). This is the id POST /v1/refund/chargeback takes. |
| `transactionId` | string (uuid) | Echo of the transaction marked. |
| `status` | string | Always `approved` - an external refund never fails at a gateway. |
| `success` | boolean | Always true on 200. |
| `method` | string | Always `external` (no provider call) - also under the TEST key (then `testMode: true`). |
| `amount` | number (major units) | The full remaining balance that was booked, in dollars. |
| `fee` | number (major units) | Per-brand Ethoca/RDR fee recorded on the refund, in dollars; recomputed from the MID's fee columns when `chargeback` is true. 0 on an idempotent replay. |
| `isChargeback` | boolean | true when `chargeback: true` was sent and the reclassification succeeded. |
| `blacklisted` | boolean | true when the refund auto-blacklist setting is on (email + card were added, best-effort). false under the TEST key. |
| `replayed` | boolean (only on replay) | Present and true when the `idempotencyKey` was already used - the original result is returned and nothing new is written. |
| `testMode` | boolean (TEST key only) | true when called with the TEST key: the refund row is a TEST row (cancellable), no blacklist. |

**Errors**

- `400` `{ "error": "Invalid request", "details": <zod flatten()> }` - `transactionId` not a UUID, `idempotencyKey` missing / outside 8-128 chars, `chargeback` not a boolean, over-long `requestedBy`/`reason`.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{ "error": "Transaction not found" }`.
- `409` `{ "error": "A refund with this idempotencyKey is already in progress" }` - retry the SAME key shortly.
- `422` `{ "error": "Transaction was not an approved charge" }` - declines/errors cannot be marked.
- `422` `{ "error": "Nothing left to refund (already refunded 49.99)" }` - already fully refunded (by /v1/refund, a dashboard refund, or an earlier mark).
- `422` The external refund was booked but the chargeback reclassification failed: the refund body plus `chargebackError` (e.g. 'Only successful refunds can be marked as chargebacks'). Retry with POST /v1/refund/chargeback using the returned `refundId`.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- NO MONEY MOVES. This records what the partner already did. Use POST /v1/refund when you want US to refund the customer.
- NEVER call both /v1/refund and /v1/refund/mark for the same transaction: whichever comes second gets 422 'Nothing left to refund'.
- Blacklisting is automatic (email + card of the transaction) when the refund auto-add setting is on - the same behaviour as a real refund. A separate POST /v1/blacklist is NOT needed, and this is the only way for the partner to blacklist a CARD, since /v1/blacklist needs the full PAN which the partner never receives.
- Full remaining amount only - there is no `amount` parameter. A partially refunded order gets the remainder marked.
- `chargeback: true` is two writes: the external refund, then the reclassification. If the second fails you get a 422 carrying the booked `refundId` - do not re-send the mark (it would replay); finish with POST /v1/refund/chargeback.
- Idempotent replays return the ORIGINAL body with `replayed: true` and `fee: 0`, and `chargeback: true` on a replay re-runs the (idempotent) reclassification on the original refund.
- Marking a chargeback clears any RDR/Ethoca dispute label on that refund, as with POST /v1/refund/chargeback.
- TEST key: the mark IS persisted (as a TEST refund, plus the chargeback flag when `chargeback: true`) so GET /v1/transactions/:id and search reflect it; nothing is blacklisted. Cancel it with POST /v1/refund/cancel-test (`refundId` or `transactionId`).
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.

##### `POST /v1/refund/search`

**Scope** `refunds.read` - **Search transactions by dispute identifiers (card, amount, auth code, descriptor, e-mail, order)**

Searches transactions by dispute identifiers (card digits, amount, auth code, descriptor, e-mail, order id) and returns the partner shape: the public way to find a charge to refund, label or match against a dispute. Find charges to refund or to match against a dispute/chargeback. Searches card (NMI) and wallet (Convesio) transactions by date window, amount, card digits, auth code, descriptor, gateway transaction id, email or order id, and returns the PCI-safe partner transaction shape (first6......last4 only, never PAN/CVV).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 datetime) | no | Lower bound on `created_at`, INCLUSIVE (`created_at >= from`). Zod `.datetime()` strictness: must be UTC with a trailing `Z` (e.g. `2026-08-01T00:00:00Z` or `...T00:00:00.000Z`). A date-only string (`2026-08-01`) or a numeric offset (`+02:00`) is rejected with 400. |
| `to` | string (ISO 8601 datetime) | no | Upper bound on `created_at`, INCLUSIVE (`created_at <= to`). Same UTC-with-`Z` strictness as `from`. Not validated against `from` on this route - an inverted window just returns 0 rows. |
| `amount` | number (major units, e.g. 49.99) | no | Charge amount in MAJOR UNITS (dollars), not cents. Must be positive and finite. Converted server-side with toCents() and matched EXACTLY against `amount_cents` - 49.99 matches only 4999 cents, never a partial or nearby amount. |
| `first6` | string | no | Card BIN, exactly 6 digits (`^\d{6}$`). Matched against `left(masked_card, 6)`. On its own it does NOT satisfy the at-least-one-filter rule (see gotchas) - pair it with `last4` or another filter. |
| `last4` | string | no | Card last 4, exactly 4 digits (`^\d{4}$`). Matched against `right(masked_card, 4)`. On its own it does NOT satisfy the at-least-one-filter rule. |
| `currency` | string | no | Currency code, EXACTLY 3 characters (length is the only check - `USD`, `EUR`, and also `ZZZ` all pass). Compared case-insensitively (`upper(currency) = upper(?)`). Does NOT satisfy the at-least-one-filter rule on its own. |
| `authCode` | string | no | Gateway auth code, trimmed, 1-32 chars. EXACT match against the approved attempt's NMI `authcode`. NMI card charges only - wallet/ConvesioPay charges never carry one, so filtering by authCode silently excludes all wallet transactions. |
| `descriptor` | string | no | Statement descriptor fragment, trimmed, 2-128 chars. Case-insensitive CONTAINS (`ILIKE %value%`) matched against any of three columns: the descriptor actually sent on the approved attempt, the MID's `soft_descriptor`, or the MID's `name`. `%` and `_` in your value are treated as SQL LIKE wildcards. |
| `gatewayTxnId` | string | no | The gateway's own transaction id (`order_id_supplier`), trimmed, 4-128 chars. EXACT match. This is the practical substitute for an ARN - no gateway returns an ARN to this system, so there is no ARN parameter. |
| `email` | string (email) | no | Customer email, trimmed, max 256 chars, must parse as an email. Case-insensitive EXACT match (`lower(email) = lower(?)`) - not a substring search. |
| `orderId` | string | no | Merchant order id, trimmed, 1-128 chars. EXACT match on `order_id`. Note an order id can map to MULTIPLE transaction rows (the initial sale plus its rebills all share it), so expect more than one result. |
| `limit` | integer; default `50` | no | Max rows returned, 1-200. The default is applied in the handler (`v.limit ?? 50`), NOT in the zod schema - omitting it yields 50, and 50 is what you get if you forget it while scanning a wide window. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "from": "2026-08-01T00:00:00Z",
 "to": "2026-08-15T23:59:59Z",
 "last4": "1111",
 "first6": "411111",
 "limit": 25
}
```

**Response**

```json
{
 "count": 1,
 "transactions": [
  {
   "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
   "orderId": "ORD-100482",
   "amount": 49.99,
   "currency": "USD",
   "status": "approved",
   "approved": true,
   "refundStatus": "none",
   "createdAt": "2026-08-14T18:22:07.412Z",
   "mid": "Aurora LLC - NMI 3",
   "midNumber": "9412887",
   "gatewayTxnId": "10342998871",
   "actionType": "straight_sale",
   "operation": "SALE",
   "customerId": "cus_3f9c1e7a2b6d4081",
   "card": "411111......1111",
   "cardExpiration": "0829",
   "refunded": 0,
   "refundable": 49.99,
   "refundedAt": null,
   "chargedBack": false,
   "disputeKind": null,
   "descriptor": "AURORA*SKINCARE 8885551212",
   "email": "dana.reyes@example.com",
   "customerName": "Dana Reyes",
   "gatewayType": "nmi",
   "walletKind": null,
   "storefrontUrl": "https://shop.example.com",
   "trafficSource": "fb-ads",
   "productId": "SKU-COLL-30",
   "orderDescription": "Collagen Renew 30ct",
   "paymentGatewayId": "5c9a0f31-2d84-4b17-9a6e-0c7f3b118e42",
   "authCode": "049213",
   "avsResponse": "Y",
   "cscResponse": "M",
   "responseText": "SUCCESS",
   "ipAddress": "198.51.100.24",
   "billing": {
    "address1": "411 Beacon St",
    "city": "Boston",
    "state": "MA",
    "postalCode": "02115",
    "country": "US",
    "phone": "+16175550142"
   },
   "shipping": {
    "firstName": "Dana",
    "lastName": "Reyes",
    "address1": "411 Beacon St",
    "city": "Boston",
    "state": "MA",
    "postalCode": "02115",
    "country": "US"
   }
  }
 ]
}
```

| response field | type | description |
|---|---|---|
| `count` | integer | Number of transactions in this response. NOT a total - it is capped by `limit` and there is no total or pagination on this route. |
| `transactions[].transactionId` | string (uuid) | This system's transaction id. THIS is what POST /v1/refund takes as `transactionId`. |
| `transactions[].orderId` | string | Merchant order id. Shared by the initial sale and its rebills. |
| `transactions[].amount` | number (major units) | Charge amount in dollars (cents / 100). Not cents. |
| `transactions[].currency` | string | ISO currency code as stored on the transaction. |
| `transactions[].status` | string | Transaction status: approved \| declined \| error \| unknown \| pending \| duplicate. |
| `transactions[].approved` | boolean | `is_success`. Only rows with approved=true are refundable. |
| `transactions[].refundStatus` | string | none \| partial \| refunded. |
| `transactions[].createdAt` | string (ISO 8601) | Charge timestamp - the field `from`/`to` filter on. |
| `transactions[].mid` | string \| null | Human name of the MID that won the charge (`final_account_name`). |
| `transactions[].midNumber` | string \| null | The MID's merchant number. |
| `transactions[].gatewayTxnId` | string \| null | Gateway-side transaction id (`order_id_supplier`) - the ARN substitute, and what the refund is executed against. |
| `transactions[].actionType` | string | Where the SALE came from - NOT the operation type. Every row is one auth+capture SALE; refunds/voids/chargebacks are dimensions of the row (`refundStatus`, `refunded`, `refundedAt`, `chargedBack`, `disputeKind`), never rows. Values: `straight_sale` (initial checkout) \| `rebill` (card-on-file recharge) \| `rebill_legacy` (legacy subscription-charge path) \| `imported` (card-on-file order backfilled from a CSV - the original sale ran on another platform, so NO charge happened here: mid/midNumber/gatewayTxnId/authCode/AVS/CSC/descriptor/store are null and POST /v1/refund rejects it; use POST /v1/refund/mark). |
| `transactions[].operation` | string | ONE predefined value in the partner's vocabulary - the record's current type: `SALE` (never refunded; also for declined attempts) \| `REFUND` \| `VOID` \| `CHARGEBACK` (type of the LATEST successful refund: method void -> VOID, chargeback-marked -> CHARGEBACK). Store it as the Action Type - nothing to derive client-side. AUTHORIZE/CAPTURE never occur. |
| `transactions[].customerId` | string \| null | Stable opaque customer id: `cus_` + 16 hex of sha256(lower-cased email). Same shopper => same id across orders/sales/rebills. null when no email. There is no customer entity in this system. |
| `transactions[].card` | string \| null | Masked card as `first6......last4` joined by TWO U+2026 HORIZONTAL ELLIPSIS characters (not ASCII dots). null when no masked card was captured. Never a PAN. |
| `transactions[].cardExpiration` | string \| null | Card expiry as stored on the raw payload (typically MMYY). |
| `transactions[].refunded` | number (major units) | Amount already refunded, in dollars. |
| `transactions[].refundable` | number (major units) | Remaining refundable balance in dollars (amount - refunded). This is exactly what POST /v1/refund will refund. |
| `transactions[].refundedAt` | string (ISO 8601) \| null | Set only when the transaction became FULLY refunded; stays null after a partial. |
| `transactions[].chargedBack` | boolean | True when any successful refund on this transaction is marked as a chargeback. |
| `transactions[].disputeKind` | string \| null | `rdr` \| `ethoca` \| null - the RDR/Ethoca alert label. Mutually exclusive with chargedBack. |
| `transactions[].descriptor` | string \| null | Descriptor actually sent on the approved attempt (on a decline: the LAST attempt), falling back to the MID's soft descriptor. null on wallet rows and on imported rows. |
| `transactions[].gatewayType` | string | `wallet` when the charge came through Convesio (Apple/Google Pay), otherwise the MID's gateway type (defaults to `nmi`). |
| `transactions[].walletKind` | string \| null | Wallet flavour (e.g. apple/google) for wallet charges; null for card charges. |
| `transactions[].paymentGatewayId` | string \| null | UUID of the MID/account row that processed the charge (`final_account_id` as text). |
| `transactions[].clientId` | string \| null | The account that charged it - its API key's owner email (CSV imports: the importer's account). This is the ClientId of GET /v1/blacklist/client/{clientId}; every MID that account charges through sits under it. |
| `transactions[].authCode` | string \| null | NMI auth code from the approved attempt. Always null for wallet/Convesio charges, for every decline (gateways only issue one on approval), and for imported rows. |
| `transactions[].avsResponse` | string \| null | NMI AVS response code from the approved attempt; null for wallet charges and declines. On a decline: taken from the LAST attempt when one was made (null on an imported row). |
| `transactions[].cscResponse` | string \| null | NMI CVV response code from the approved attempt; null for wallet charges and declines. On a decline: taken from the LAST attempt when one was made (null on an imported row). |
| `transactions[].responseText` | string \| null | Approved attempt's gateway response text, falling back to the transaction's decline reason. |
| `transactions[].billing` | object | address1, city, state, postalCode, country, phone. Backfilled from the ORIGINAL order sharing this order_id when the row itself carries none (rebills). |
| `transactions[].shipping` | object | firstName, lastName, address1, city, state, postalCode, country. The ADDRESS fields are copies of billing by design - see gotchas. |

**Errors**

- `400` `{ "error": "Invalid request", "details": <zod flatten()> }` - a field failed its schema, or the at-least-one-filter refine failed (`details.formErrors` carries the message 'Provide at least one of: date range, amount, first6+last4, authCode, gatewayTxnId, email, orderId, descriptor').
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `500` `{ "error": "Internal Server Error", "requestId": "..." }` on an unhandled DB/query failure.
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- AT LEAST ONE of these must be present or you get 400: `from`, `to`, `amount`, `first6` AND `last4` together, `authCode`, `gatewayTxnId`, `email`, `orderId`, `descriptor`. `currency` alone, `limit` alone, `first6` alone, or `last4` alone do NOT satisfy it.
- But the refine only gates the REQUEST - a lone `first6` (or `currency`) sent alongside a qualifying filter is still applied as a real AND-ed filter. All supplied filters are AND-ed; there is no OR mode.
- `amount` is MAJOR UNITS on input, and every money field on output (`amount`, `refunded`, `refundable`) is MAJOR UNITS too. Storage is integer cents; the API surface is dollars. Do not send cents.
- No pagination and no total: results are ordered `created_at DESC` and hard-truncated at `limit` (default 50, max 200). A wide window silently drops the oldest matches with no indication. Use POST /v1/transactions to walk a window exhaustively.
- Only rows whose CRM is `nmi` or `convesio` are ever returned. Transactions from any other source are invisible to this endpoint.
- `card` uses two U+2026 ellipsis characters (`411111......1111`), not the `..` produced by the internal maskCard helper. Don't regex for dots.
- The `shipping` block's address fields (address1/city/state/postalCode/country) are the BILLING values, always - the code deliberately returns billing as shipping because checkout sends shipping = billing. Only `shipping.firstName`/`lastName` come from real shipping data (falling back to the customer's first/last name). The gateway's actual ship_city/ship_state/ship_zip are queried but never returned.
- Nulls are meaningful, not errors: declines have no approved attempt (so authCode/avsResponse/cscResponse/descriptor are null) and wallet/Convesio charges never carry NMI auth/AVS/CSC.
- `descriptor` goes into a LIKE pattern unescaped - `%` or `_` in your value act as wildcards.
- This route returns the identical per-transaction object as POST /v1/transactions (both map through the same `toPartnerTxn`), so one parser handles both.
- The transaction row internally carries a `note_count`, but it is NOT included in the response.
- `actionType` is the sale's ORIGIN, not an operation type: there are no AUTHORIZE/CAPTURE/REFUND/VOID rows. Derive REFUND/VOID from `refundStatus`/`refunded`/`refundedAt` and chargebacks from `chargedBack`. `imported` rows (CSV card-on-file backfills) carry no gateway data at all and cannot go through POST /v1/refund - use POST /v1/refund/mark.
- Nulls are honest, not bugs: imported rows never touched a gateway; wallet rows are tokenised (no card/expiry/authCode/AVS/CSC); declines never have an authCode. : a charge cocoapi refused before any MID is not a transaction at all - the former `preGateway` field is gone and every listed decline is a MID verdict or a technical error. ARN, CAVV/3DS, customer/affiliate ids and card fingerprint do not exist in this system.
- To fetch ONE transaction you already know, use GET /v1/transactions/:transactionId (same shape + `refunds[]`) instead of a search - no optional-parameter ambiguity.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.

##### `GET /v1/refund/status`

**Scope** `refunds.read` - **Read refund outcomes of a transaction**

Reads up to 20 refunds of one transaction of the account (or only the one created with idempotencyKey), unresolved ones first, without any provider call. Use it to resolve a 202 / 503 answer of POST /v1/refund or POST /v1/transactions/:transactionId/alert.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | Original transaction UUID |
| `idempotencyKey` | string | no | Exact original refund request key, maximum 256 characters |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Response**

```json
{
  "refunds": [
    {
      "refundId": "00000000-0000-4000-8000-000000000801",
      "status": "unknown",
      "success": false,
      "method": null,
      "amount": 49.99,
      "nmiRefundId": null,
      "message": "Refund outcome unconfirmed. Do not submit another refund; investigate the original provider operation.",
      "replayed": true,
      "investigationRequired": true,
      "cleanupPending": false
    }
  ]
}
```

**Errors**

- `400` `{"error":"Invalid refund reference"}` when transactionId is missing or not a UUID, idempotencyKey is empty or over 256 characters, or an unknown query field is sent.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.read`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{"error":"Transaction not found"}` when the transaction is not in the account.
- `503` `{"error":"Refund endpoint not configured"}` (shared-secret path without secrets); a read that passes its 5-second budget answers 504.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}`.

**Gotchas**

- Sent with Cache-Control: no-store. Not rate limited like the other partner refund routes.
- status unknown stays unknown until the provider operation is reconciled: it never authorizes another refund.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.

##### `GET /v1/refunds`

**Scope** `refunds.read` - **List refunds**

The account's refund log: every refund row (dashboard, API, external marks, test refunds when asked) with its charge context, newest first and paged, card data first6 / last4 only. Every key of the unified filter catalog applies: from / to read the refund date, the refund keys (refund, refundStatus, refundTest, refunded) read the refund row, every other key reads the refunded charge.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Start of the page range (inclusive): the grain's own date. A bare day is read in tz (its first millisecond). |
| `to` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | End of the page range (inclusive). A bare day is read in tz (its last millisecond). |
| `tz` | string (IANA timezone, max 64) | no | IANA timezone the days and hours are read in. Defaults to the account timezone. Must be a known zone. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `storefront` | CSV string (max 4000) | no | Store host bucket, (direct). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `checkout` | CSV of UUIDs or none | no | Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of UUIDs or none | no | Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. |
| `affiliate` | CSV of UUIDs or none | no | Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |
| `limit` | integer (1-10000); default `50` | no | Page size. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |

**Response**

```json
{
  "refunds": [
    {
      "id": "00000000-0000-4000-8000-000000000801",
      "transaction_id": "00000000-0000-4000-8000-000000000501",
      "amount_cents": 4999,
      "fee_cents": 35,
      "status": "approved",
      "is_success": true,
      "method": "refund",
      "nmi_refund_id": "10344120557",
      "requested_by": "owner@example.com",
      "reason": "Customer request",
      "created_at": "2026-11-24T10:00:00.000Z",
      "completed_at": "2026-11-24T10:00:02.000Z",
      "response_text": "Refund confirmed by provider",
      "is_test": false,
      "is_chargeback": false,
      "chargeback_marked_at": null,
      "chargeback_marked_by": null,
      "dispute_kind": null,
      "dispute_marked_at": null,
      "dispute_marked_by": null,
      "order_id": "ORDER-1001",
      "currency": "USD",
      "txn_amount_cents": 4999,
      "final_account_name": "Example MID 1",
      "first6": "411111",
      "last4": "1111",
      "wallet_method": null,
      "card_brand": "visa",
      "card_last4": "1111",
      "credential_mode": null,
      "note_count": 1,
      "v5_affiliate": null,
      "threeDsSummary": null
    }
  ],
  "total": 1
}
```

| response field | type | description |
|---|---|---|
| `refunds` | object[] | One row per refund, ordered refunds.created_at DESC. |
| `refunds[].id` | uuid | Refund id - pass it as refundId to POST /v1/refund/chargeback, or in the path of POST /v1/refunds/:id/dispute. |
| `refunds[].transaction_id` | uuid | The charge this refund belongs to. Use this for the notes endpoints. |
| `refunds[].amount_cents` | string | Refunded amount in INTEGER CENTS. Postgres bigint, so node-postgres serializes it as a JSON STRING, not a number. |
| `refunds[].fee_cents` | string | Per-brand flat refund/chargeback fee in INTEGER CENTS, bigint -> JSON string. v3.9.6 live fees: DERIVED PER READ from the charge's gateway CURRENT settings (the MID's, else the wallet provider's mc_refund_fee_cents / visa_refund_fee_cents by card network; other networks 0) - never the deprecated refunds.fee_cents snapshot. 0 when the refund failed or the gateway has no fee configured today; a fee edit changes the figure on every past refund. |
| `refunds[].status` | string | pending \| approved \| declined \| error. |
| `refunds[].is_success` | boolean | True for approved refunds. NOTE: an 'external' refund booked after a credentials failure is is_success = true even though no money moved at the gateway. |
| `refunds[].method` | string\|null | 'refund' (normal gateway refund), 'void' (NMI unsettled full-amount fallback), or 'external' (booked in the ledger, no gateway call). Null while pending. |
| `refunds[].nmi_refund_id` | string\|null | Gateway transaction id of the refund. Always null for method 'external'. |
| `refunds[].requested_by` | string\|null | Email of the operator, or 'refund-team'/'system' for automated bookings. |
| `refunds[].response_text` | string\|null | Gateway response text. For a credentials failure this is the long 'NOT refunded on the MID - bad credentials ... refund manually' warning. |
| `refunds[].is_chargeback` | boolean | Reclassified as a chargeback - its money moved to the chargeback buckets in every finance view. |
| `refunds[].dispute_kind` | string\|null | 'rdr' \| 'ethoca' \| null. Mutually exclusive with is_chargeback: marking CB nulls this. |
| `refunds[].txn_amount_cents` | string | The ORIGINAL charge amount in INTEGER CENTS (transactions.amount_cents). bigint -> JSON string. |
| `refunds[].currency` | string | ISO-4217 code of the original charge. |
| `refunds[].final_account_name` | string\|null | Name of the MID that processed the charge. Null for wallet charges with no MID. |
| `refunds[].first6` | string\|null | First 6 of the PAN, taken from the stored mask. Full PAN and CVV are never exposed here. |
| `refunds[].last4` | string\|null | Last 4 of the PAN, taken from the stored mask. |
| `refunds[].wallet_method` | 'Apple Pay' \| 'Google Pay' \| null | v3.9.8 item 1 - the wallet of the refunded charge (db/txFilters walletMethodSql); null for a card. A wallet charge has no masked card, so first6 / last4 are null: this is what the Card column shows. |
| `refunds[].card_brand / card_last4` | string \| null | v3.9.8 item 1 - the card the wallet reported for the refunded charge (network, last four digits; '' = asked, none), for the Card chip's tooltip. |
| `refunds[].note_count` | integer | Number of transaction_notes on the parent transaction. Cast ::int, so a real JSON number. |
| `total` | integer | Total rows matching the filters + scope, ignoring limit/offset. Cast ::int, a real JSON number. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when a parameter is unknown (strict), a value is outside its vocabulary, a range pair is reversed or limit / offset is out of bounds; `{"error":"Unknown flow filter"}` / `{"error":"Unknown affiliate filter"}` for a flow or affiliate id that is not the account's.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Filters use the one unified catalog shared by the transactions list, the reports and the bulk tools: the query is strict (an unknown parameter is a 400 that names it), a closed vocabulary rejects unknown values, CSV values are OR-ed inside a key and keys are AND-ed, range pairs (from/to, amountMin/amountMax, cycleMin/cycleMax, clientOrdersMin/Max, clientLtvMin/Max, the sub and client date pairs, dayFrom/dayTo) must be ordered, and hour needs a valid tz.
- refundTest absent = exclude test refunds; send refundTest=include or only to see them.
- fee_cents is the live per-brand refund fee of the charge gateway as configured today, not a stored snapshot.
- v5_affiliate is the originating affiliate of the charge ({id, name, publicId} or null); threeDsSummary the customer authentication summary or null.

##### `POST /v1/refunds/:id/dispute`

**Scope** `refunds.write` - **Label a refund as an RDR or Ethoca alert**

Labels a successful refund as a Visa RDR or Mastercard Ethoca dispute alert, or clears the label (kind null). The money stays in the refund buckets (unlike a chargeback); the order gets an RDR / Ethoca badge and filter, and labelling a live refund queues the customer blacklist when the account's refund auto-add setting is on.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Refund id (refunds[].id of GET /v1/refunds). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: rdr \| ethoca, or null | **yes** | Alert kind; null clears the label. |

**Request body**

```json
{
  "kind": "rdr"
}
```

**Response**

```json
{
  "refundId": "00000000-0000-4000-8000-000000000801",
  "disputeKind": "rdr"
}
```

| response field | type | description |
|---|---|---|
| `refundId` | uuid | Echo of the refund id acted on. |
| `disputeKind` | string\|null | The new label: 'rdr', 'ethoca', or null when cleared. Echoes what you sent. |

**Errors**

- `400` `{"error":"Invalid refund id"}` when :id is not a UUID; `{"error":"Invalid","details":{...}}` when kind is missing or not rdr / ethoca / null.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the id is unknown or its transaction is not the account's.
- `422` `{"error":"Only successful refunds can be marked"}`, or `This refund is marked as a chargeback ... unmark CB first` (unmark the chargeback first).
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- A chargeback and an alert label are mutually exclusive.

##### `POST /v1/transactions/:id/action`

**Scope** `refunds.write` - **Run a refund or dispute action on a transaction**

One action on a charge of the account: refund (gateway refund of the whole balance), refund-rdr / refund-ethoca (gateway refund then RDR / Ethoca label), external (book a refund made elsewhere, no gateway call), chargeback (mark charged back, booking an external refund first if needed), rdr / ethoca (dispute label, booking an external refund first if needed). blacklist chooses whether the customer is blacklisted.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Transaction id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `action` | enum: refund \| refund-rdr \| refund-ethoca \| external \| chargeback \| rdr \| ethoca | **yes** | Action to run. |
| `blacklist` | boolean; default `true` | no | Blacklist the customer e-mail and card as part of the action (subject to the account refund auto-add setting for refunds). |

**Request body**

```json
{
  "action": "refund-rdr",
  "blacklist": true
}
```

**Response**

```json
{"refundId":"uuid","success":true,"method":"gateway"}
```

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when action is not one of the seven values or blacklist is not a boolean.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the transaction does not exist or is not the account's.
- `409` Idempotency conflicts of the refund engine (see POST /v1/refund).
- `422` The refund was refused (body of the refund engine with success false, including a provider decline), the charge is not approved, nothing is left to refund, or the refund is already marked as a chargeback for rdr / ethoca.
- `500` `{"error":"Refund succeeded but no refund id was returned","refunded":true}`.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `Refund admission unconfirmed` (resend the same action: the fixed key admin:<id>:full replays).

**Gotchas**

- Gateway actions use the fixed idempotency key admin:<id>:full (whole balance only); external, chargeback, rdr and ethoca use external:<id>. A repeated action replays instead of refunding twice.
- Unlike POST /v1/refund, a provider decline answers 422 here (the body still carries the engine outcome).
- For refund-rdr / refund-ethoca, a refund that succeeded but could not be labelled answers the label error with refunded true and refundId.

##### `POST /v1/transactions/:id/chargeback-refund`

**Scope** `refunds.write` - **Refund a transaction and mark it as a chargeback (money moves unless external: true)**

Refunds the transaction at its gateway and then marks that refund as a chargeback (with external: true it books an external refund instead and no money moves); POST /v1/transactions/:transactionId/chargeback never moves money and can also unmark. One-click chargeback: book a refund and immediately reclassify it as a chargeback (moves the amount + fee from the refund buckets to the chargeback buckets, sets transactions.charged_back, applies the 'Chargeback' blacklist). Two modes selected by `external`.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | transactions.id. Not zod-validated; a malformed uuid reaches Postgres and answers 400 `A value has an invalid format.`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `external` | boolean; default `false / undefined` | no | true = 'Mark as CB': book the refund with NO gateway call (the bank already pulled the money via the dispute). false/omitted = 'Mark as CB + refund': run a REAL gateway refund first, then mark CB. |
| `amount` | number (MAJOR UNITS) | no | Amount to refund in major units; omitted = the whole refundable balance (ignored when external is true). |
| `idempotencyKey` | string; default `admin:<id>:<amountInCents\|'full'>` | no | Idempotency key, unique across all refunds. Default admin:<id>:<amount in cents or full> (external true always uses external:<id>). |

**Request body**

```json
{
 "external": true
}
```

**Response**

```json
{
 "refundId": "3f7a9c11-22bb-4d33-8e44-55ff66aa7788",
 "status": "approved",
 "success": true,
 "method": "external",
 "amount": 49.99,
 "fee": 0.35,
 "nmiRefundId": null,
 "message": "Marked as refunded externally - no gateway call made",
 "chargeback": true
}
```

| response field | type | description |
|---|---|---|
| `(refund body)` | object | On success the response is the underlying refund body (refundId, status, success, method, amount, fee, nmiRefundId, message - or the replay shape with `replayed`) with `chargeback: true` merged in. |
| `chargeback` | boolean | Always true on a 200 - the refund was booked AND reclassified. |
| `amount / fee` | number | MAJOR UNITS (dollars). The chargeback fee is the same per-brand flat MID fee as a refund, backfilled if it was 0 at refund time. |
| `refunded` | boolean (partial-failure body only) | Present with `refundId` when the refund succeeded but the CB reclassification failed - the money HAS moved. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when amount is not positive; `{"error":"A value has an invalid format."}` when :id is not a UUID.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` `{"error":"Not found"}` when the transaction does not exist or is not the account's.
- `409` `Idempotency key belongs to another transaction`, `Idempotency key has a different refund amount`, `Idempotency key belongs to a test refund` (body `{"success":false,"status":"not_dispatched","error":...}`).
- `422` `Transaction is not eligible for a gateway refund`, `Nothing left to refund`, `Amount exceeds refundable balance`, `Unresolved refund reserves this balance; investigate its original operation`, `Refund credentials unavailable; no request was dispatched`, `Verification reversals use the pre-auth workflow`, `Refund owner unavailable`.
- `500` {"error":"Refund succeeded but no refund id was returned"} - the refund went through but cannot be reclassified; also unhandled DB errors.
- `503` `{"success":false,"status":"unknown","investigationRequired":true,"error":"Refund admission unconfirmed"}`.

**Gotchas**

- Runs the guarded refund engine of POST /v1/refund: the amount is honoured (omitted = the whole refundable balance), a provider decline is HTTP 200 with success false, an unconfirmed outcome is HTTP 202 status unknown (resolve it with GET /v1/refund/status?transactionId=<id>, never with a new key), 503 `Refund admission unconfirmed` means resend the same key.
- The default idempotency key is admin:<id>:<amount in cents or full>: the same call twice replays; a different amount is a different refund.
- external:true still books a refunds row and sets transactions.refunded/refunded_cents - it just skips the gateway call. Use it ONLY when the bank already pulled the money, otherwise your books say refunded while the customer was never paid.
- PARTIAL FAILURE IS NOT ATOMIC: if the refund succeeds but setRefundChargeback fails, you get the CB step's non-200 status with a body of {...cbError, refundId, refunded: true} - the customer HAS been refunded but the row is NOT marked as a chargeback. Retry the mark via the refund-logs surface, not this endpoint.
- If the refund does not succeed, NO chargeback is marked and the raw refund error is returned unchanged - you cannot distinguish a refund failure from a CB failure by status code alone; look for `refunded: true` in the body.
- Marking CB CLEARS any existing RDR/Ethoca dispute label on that refund (the two classifications are mutually exclusive).
- external:true reuses the fixed idempotency key `external:<id>`, which is the SAME key POST .../external-refund and POST .../dispute use. Calling any two of those on one transaction replays the first booking rather than creating a second refund.
- A chargeback triggers the strongest blacklist entry (email + card, reason 'Chargeback'), best-effort and not reported in the response.

##### `POST /v1/transactions/:id/dispute`

**Scope** `refunds.write` - **Label a transaction RDR or Ethoca without a gateway refund (books an external refund)**

Labels a transaction RDR or Ethoca without a gateway refund (an external refund is booked first when it is not refunded yet); POST /v1/transactions/:transactionId/alert instead refunds at the gateway, and for rdr this route equals POST /v1/transactions/:transactionId/rdr. One-click dispute-alert labelling. The alert already moved the money back, so this books an EXTERNAL refund if the charge is not yet refunded (no gateway call) and then labels that refund 'rdr' or 'ethoca'. Label only - the amount stays in the REFUND buckets, not the chargeback buckets.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | transactions.id. Not zod-validated; a malformed uuid reaches Postgres and answers 400 `A value has an invalid format.`. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string enum | **yes** | REQUIRED. Exactly 'rdr' (Visa) or 'ethoca' (Mastercard). Any other value, or an empty body, is a 400. This route accepts NO amount, NO reason and NO idempotencyKey. |

**Request body**

```json
{
 "kind": "ethoca"
}
```

**Response**

```json
{
 "refundId": "3f7a9c11-22bb-4d33-8e44-55ff66aa7788",
 "status": "approved",
 "success": true,
 "method": "external",
 "amount": 49.99,
 "fee": 0.35,
 "nmiRefundId": null,
 "message": "Marked as refunded externally - no gateway call made",
 "disputeKind": "ethoca"
}
```

| response field | type | description |
|---|---|---|
| `refundId` | string (uuid) | The refunds.id that now carries the label - either the newly booked external refund or, when the charge was already refunded, the most recent successful refund on the order. |
| `disputeKind` | string | Echo of the applied label: 'rdr' or 'ethoca'. Also mirrored onto transactions.dispute_kind. |
| `(external refund body)` | object | When a NEW external refund was booked, its whole body (status, success, method:'external', amount, fee, nmiRefundId, message) is merged in. When the label was applied to a pre-existing refund, ONLY refundId and disputeKind are returned. |
| `amount / fee` | number | MAJOR UNITS (dollars) - present only when a refund was booked by this call. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} - kind missing or not 'rdr'/'ethoca'. {"error":"A value has an invalid format."} when :id is not a UUID (checked before the body).
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `404` {"error":"Transaction not found"} (or 'Refund not found' from the labelling step).
- `409` {"error":"A refund with this idempotencyKey is already in progress"} - another external booking on key `external:<id>` is pending.
- `422` 'Transaction was not an approved charge'; 'Nothing left to refund (already refunded <dollars>)' surfaced when there is also no successful refund to label; 'Only successful refunds can be marked'; or 'This refund is marked as a chargeback - unmark CB first' (returned with refundId added to the body).
- `500` {"error":"Refund booked but no refund id returned"} or a DB error.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- This endpoint MOVES MONEY ON YOUR BOOKS even though its name says 'dispute': on a not-yet-refunded charge it books a full external refund (refunds row, transactions.refunded/refunded_cents, finance buckets, blacklist) before labelling. Only use it when the alert really did reverse the funds.
- The response SHAPE varies: a newly booked refund returns the full external-refund body plus disputeKind; an already-refunded charge returns only {refundId, disputeKind}. Do not depend on `amount`/`method` being present.
- It uses the fixed idempotency key `external:<id>` - shared with POST .../external-refund and with POST .../chargeback when external:true. A second dispute call replays the first booking instead of double-refunding, which is intentional.
- Labelling is REJECTED with 422 if the refund is already marked as a chargeback; unmark the CB first (via the refund-logs surface).
- There is no unlabel/clear here - `kind` cannot be null on this route. Clearing a label requires the refunds surface (setRefundDispute with null).
- Marking a dispute alert applies the same blacklist severity as a chargeback (email + card, reason 'Dispute alert (RDR)' / '(Ethoca)').
- The label lives on the refund; transactions.dispute_kind is RECOMPUTED as the most recent labelled successful refund on the order, so labelling one refund can change what the transaction shows.

##### `POST /v1/transactions/:transactionId/alert`

**Scope** `refunds.write` - **Settle an Ethoca alert by refunding (money MOVES)**

Records an Ethoca dispute alert and settles it by actually refunding the customer. An Ethoca alert is a warning, not a debit: refunding is the operator's decision to pay now and avoid the chargeback that would otherwise land. So the full refund engine runs - the refundable balance is reserved under a lock on the charge, the idempotency key is honoured, an unsettled NMI charge falls back to a void - and the resulting refund is then labelled `ethoca`, so it sits in the dispute buckets exactly like a hand-marked one. A refund that DECLINES is returned as it is and nothing is labelled: there is no dispute outcome to record yet. A charge with nothing left to refund is not an error - the newest successful refund is labelled instead, and `moneyMoved` says which of the two happened. For a Visa RDR, where the money is already gone, use /v1/transactions/:transactionId/rdr.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | The transaction to act on. Must belong to the key's account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |
| `cardLast4` | string (4 digits) | no | Optional identifier check. Any mismatch answers 422 and nothing is written. |
| `cardBin` | string (6 digits) | no | Optional identifier check. |
| `amount` | number (major units) | no | Refund this much (major units) instead of the whole refundable balance. The same field is also compared to the charge amount by the identifier check, so it must equal the charge amount when sent (a partial amount answers 422 mismatched amount). |
| `email` | string | no | Optional identifier check. |
| `orderId` | string | no | Optional identifier check. |
| `idempotencyKey` | string (8-128) | **yes** | REQUIRED to mark: this endpoint moves money. Replaying the same key returns the stored result instead of refunding twice. Not needed with `marked: false`, which refunds nothing. |
| `marked` | boolean; default `true` | no | false = THE UNDO: every dispute label on the charge's refunds is cleared, the refund rows and the money are left exactly as they are, and no idempotency key is needed. 422 when the charge carries no alert. |
| `requestedBy` | string; default `partner-api` | no | Who asked for it. Defaults to 'partner-api'. |
| `reason` | string; default `dispute alert (ethoca) - refunded` | no | Free text kept on the refund row. |

**Response** `200`

```json
{
 "refundId": "00000000-0000-4000-8000-000000000001",
 "disputeKind": "ethoca",
 "refunded": true,
 "moneyMoved": true,
 "refundStatus": "refunded"
}
```

**Errors**

- `400` `idempotencyKey` missing while marking (it is only optional for `marked: false`).
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `transactions.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` No such transaction in this key's scope.
- `409` A refund with this idempotencyKey is already in progress.
- `422` `{ error: 'Transaction identifiers do not match', mismatched: [...] }` - one of the optional identifiers disagreed with the row. Nothing was written.
- `422` The charge was never approved, has no gateway id, its MID is unavailable, the requested amount exceeds the refundable balance, or the refund is already marked as a chargeback.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.
- The scope this route needs is transactions.write although it refunds money.
- The refund runs through the same engine as POST /v1/refund: a 202 status unknown answer must be resolved with GET /v1/refund/status, never retried with a new key.

##### `POST /v1/transactions/:transactionId/chargeback`

**Scope** `refunds.write` - **Mark or unmark a transaction as charged back (no money moves)**

Marks or unmarks a transaction as charged back without moving money; POST /v1/transactions/:id/chargeback-refund instead refunds at the gateway and then marks the chargeback. Chargeback keyed by the TRANSACTION, not by a refund. `chargedBack: true` -> the transaction becomes charged back: its latest successful refund is reclassified, or - if it was never refunded - an EXTERNAL refund is booked first (the dispute already moved the money; no provider call) and then marked; the customer is blacklisted. `chargedBack: false` -> unmarks every chargeback-marked refund of the transaction. Optional identifiers are validated BEFORE any write. The response echoes the resulting `chargedBack` / `refundStatus`.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | string (uuid) | **yes** | REQUIRED. Our transaction id (from search / sync / GET by id). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `chargedBack` | boolean | **yes** | REQUIRED. `true` = mark as chargeback, `false` = unmark. Must be a real JSON boolean. |
| `cardLast4` | string (4 digits) | no | Optional validation against the card's last 4 - mismatch -> 422, nothing written. |
| `cardBin` | string (6 digits) | no | Optional validation against the card's first 6. |
| `amount` | number (major units) | no | Optional validation: exact amount match. |
| `email` | string | no | Optional validation: case-insensitive equality. |
| `orderId` | string | no | Optional validation: exact orderId match. |
| `requestedBy` | string (<=128) | no | Free text: who/what initiated it. Stored as the chargeback marker and (when a refund is booked) the refund's requester + blacklist author. Default `partner-api`. |
| `reason` | string (<=512) | no | Free text; stored on the booked refund and used as the blacklist reason. Default `Chargeback`. |
| `idempotencyKey` | string (8-128) | no | Only used when the call has to BOOK the external refund (transaction never refunded). Default `chargeback:<transactionId>` (`:test` suffix under the TEST key) - so repeating the mark is naturally idempotent. |
| `clientId` | string (owner email, 3-256) | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |

**Request body**

```json
{
 "chargedBack": true,
 "cardLast4": "1111",
 "cardBin": "411111",
 "requestedBy": "agent@partner.com",
 "reason": "chargeback received"
}
```

**Response**

```json
{
 "transactionId": "9b1f4c2e-7a3d-4e58-8b0c-2f6a11d4e903",
 "refundId": "3f8c1de7-9b40-4c2a-a7d1-51e0c9b3a884",
 "isChargeback": true,
 "refundBooked": true,
 "fee": 13.0,
 "chargedBack": true,
 "refundStatus": "refunded"
}
```

| response field | type | description |
|---|---|---|
| `transactionId` | string (uuid) | Echo. |
| `refundId` | string (uuid) - mark only | The refund now classified as the chargeback (existing, or booked by this call). |
| `refundIds` | string[] - unmark only | Every refund that was un-marked. |
| `isChargeback` | boolean | The state now in effect. |
| `refundBooked` | boolean - mark only | true = the transaction had no successful refund, so this call booked an EXTERNAL one (no provider call) before marking. |
| `fee` | number (major units) - mark only | Chargeback fee recorded on the refund, in dollars (per-brand Ethoca/RDR; 0 for amex/discover/unknown or unconfigured MID fees). |
| `reverted` | boolean - unmark only | true (TEST key) = the test refund was cancelled too, transaction fully restored; false (LIVE) = the refund stays a plain refund. |
| `chargedBack` | boolean | The transaction's `chargedBack` AFTER the call (re-read) - assert on this. |
| `refundStatus` | string | The transaction's `refundStatus` AFTER the call: `refunded` after a mark; `none` after a TEST unmark; unchanged after a LIVE unmark. |
| `testMode` | boolean (TEST key only) | true = TEST rows were created/changed; nothing blacklisted. |

**Errors**

- `400` `transactionId` not a uuid, `chargedBack` missing / not a boolean, bad identifier format, `idempotencyKey` outside 8-128.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` `{ "error": "Transaction not found" }`.
- `422` `{ "error": "Transaction identifiers do not match", "mismatched": [...] }` - nothing was written.
- `422` `{ "error": "Transaction was not an approved charge" }` - declines cannot be charged back.
- `422` `{ "error": "Transaction is not marked as a chargeback" }` (LIVE) / `No TEST chargeback on this transaction` (TEST) - `chargedBack: false` with nothing to unmark.
- `422` `Nothing left to refund (...)` - the transaction is fully refunded by rows this key cannot touch (e.g. TEST key on a LIVE-refunded transaction).
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- NO REFUND IS PERFORMED OR TRIGGERED AT THE PAYMENT PROVIDER - ever. This is bookkeeping only: it reclassifies (or first records as EXTERNAL) a refund row and flags the transaction; the money was moved by the dispute on the card-network side. Use POST /v1/refund to actually refund a customer.
- MARKING A NEVER-REFUNDED TRANSACTION BOOKS AN EXTERNAL REFUND (`refundBooked: true`): the money is assumed to have already moved via the dispute. No gateway is called. If you want US to refund AND mark, call POST /v1/refund first, then this.
- Identifiers are validated first: a 422 mismatch means nothing was written - safe to retry with the right transaction.
- LIVE key never touches TEST rows and the TEST key never touches LIVE rows: each key only sees its own kind of refund. If a transaction already carries a LIVE refund, a TEST mark answers 422 'Nothing left to refund'.
- Unmark (LIVE) leaves the refund in place as a plain refund - it does not un-refund. Unmark (TEST) cancels the test refund entirely (`reverted: true`, `refundStatus` back to `none`).
- Marking blacklists the customer (LIVE key, when the refund auto-add setting is on); unmarking does NOT remove the blacklist entry.
- Marking is idempotent: a second `chargedBack: true` finds the existing chargeback refund and re-affirms it (`refundBooked: false`).
- Marking a chargeback clears any RDR/Ethoca dispute label on that refund.
- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.

##### `POST /v1/transactions/:transactionId/rdr`

**Scope** `refunds.write` - **Mark an RDR dispute (books an external refund - NO money moves)**

Records a Visa RDR (Rapid Dispute Resolution) alert on a charge. RDR has ALREADY taken the money back, so nothing is sent to the gateway: an EXTERNAL refund is booked for the remaining balance (method 'external', the refunded flags, the finance buckets, the customer auto-blacklisted) and that refund is labelled `rdr`, so it stays in the dispute buckets and out of the chargeback ones. On a charge that is already fully refunded, the newest successful refund is labelled instead. Mutually exclusive with the chargeback mark: a refund already flagged as a chargeback answers 422 - unmark the CB first. The sibling endpoint for an Ethoca alert is /v1/transactions/:transactionId/alert, which DOES move money.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `transactionId` | uuid | **yes** | The transaction to act on. Must belong to the key's account. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string | no | Account owner e-mail the call is for, used only with X-Refund-Key (omitted = the platform owner's account). With an account key the account is always the key owner's; a clientId naming another account answers 403. |
| `cardLast4` | string (4 digits) | no | Optional identifier check. Any mismatch answers 422 and nothing is written. |
| `cardBin` | string (6 digits) | no | Optional identifier check. |
| `amount` | number (major units) | no | Optional identifier check against the charge's amount. |
| `email` | string | no | Optional identifier check. |
| `orderId` | string | no | Optional identifier check. |
| `marked` | boolean; default `true` | no | false = THE UNDO: every dispute label on the charge's refunds is cleared and nothing else happens. The money is NOT returned - an RDR debit really happened and a label typed by mistake is not a reason to pretend otherwise (the mirror of `chargedBack: false`). 422 when the charge carries no alert. |
| `requestedBy` | string; default `partner-api` | no | Who asked for it, for the audit trail and the customer timeline. Defaults to 'partner-api'. |
| `reason` | string; default `dispute alert (rdr)` | no | Free text kept on the refund row. |

**Response** `200`

```json
{
 "refundId": "00000000-0000-4000-8000-000000000001",
 "disputeKind": "rdr",
 "moneyMoved": false,
 "refundStatus": "refunded"
}
```

**Errors**

- `400` `{"error":"Invalid request","details":{"transactionId":"must be a uuid"}}` when :transactionId is not a UUID; `{"error":"Invalid request","details":{...}}` when a field fails its schema.
- `401` `{"error":"Missing X-Refund-Key or a scoped account API key"}` (no credential, or only a key without an owner and no X-Refund-Key); `{"error":"Invalid refund key"}` (X-Refund-Key matches neither secret); `{"error":"Invalid API key"}` (unknown or revoked key; no fallback to X-Refund-Key).
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}` when the account the call resolves to has no paid or granted platform subscription.
- `403` `{"error":"Account suspended"}` when the key owner is banned; `{"error":"API key scope denied","code":"insufficient_scope"}` when a scoped key lacks `refunds.write`; `{"error":"clientId does not match the account this key belongs to"}` when a key is sent with a clientId naming another account.
- `404` No such transaction in this key's scope.
- `422` `{ error: 'Transaction identifiers do not match', mismatched: [...] }` - one of the optional identifiers disagreed with the row. Nothing was written.
- `422` The charge was never approved, or its refund is already marked as a chargeback.
- `429` Per-IP rate limit of the partner refund routes (RATE_LIMIT_REFUND, default 20 requests per minute).
- `503` `{"error":"Refund endpoint not configured"}`: shared-secret path only, when no account key was accepted and the server has no refund secret configured.

**Gotchas**

- With an account key every lookup and mutation is confined to the key owner's account; another account's transaction answers 404.
- Test mode exists only with the shared test secret; a call authenticated by an account key always acts in live mode.

#### Blacklist

Blacklist entries: add, check, list, remove, imports and the cleanup of subscriptions that a blacklisting cancels.

- CSV import: the page parses, deduplicates and validates the pasted list in the browser, then sends `emails[]` (`POST /v1/blacklist/import` or `POST /v1/blacklist/import-jobs`). There is no file upload and no card number in bulk.
- The export holds only the page on screen of `GET /v1/blacklist`.

##### `GET /v1/blacklist`

**Scope** `customers.read` - **List blacklist entries (search, counts by source)**

Lists the account's active blacklist entries with search, paging and counts by source; GET /v1/blacklist/client/:clientId is the partner view of blacklisted customers with their matched orders. A paginated, searchable page of the account's ACTIVE blacklist entries (e-mails and cards that every ATRI refuses before any MID attempt), each with the customer's 3DS summary, plus the account's blacklist counters. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | Page size 1..10000 (coerced from string). A larger value is a 400, not clamped. |
| `offset` | integer; default `0` | no | Rows to skip, >= 0. |
| `search` | string | no | Max 254 chars, trimmed and lower-cased. Contains-match on the e-mail and on card_masked. % and _ are not escaped: they act as wildcards. |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000101",
      "email": "repeat.refunder@example.com",
      "card_masked": null,
      "reason": "Refunded order",
      "source": "refund",
      "created_by": "system",
      "created_at": "2026-11-04T18:42:11.203Z",
      "active": true,
      "threeDsSummary": {"total": 0, "ready": 0, "used": 0, "expired": 0, "pending": 0, "failed": 0, "readyForRebill": 0, "authenticationMode": "none"}
    },
    {
      "id": "00000000-0000-4000-8000-000000000102",
      "email": null,
      "card_masked": "4111111111111111",
      "reason": "Manual",
      "source": "manual",
      "created_by": "ops@example.com",
      "created_at": "2026-11-03T09:15:02.881Z",
      "active": true,
      "threeDsSummary": null
    }
  ],
  "total": 2841,
  "stats": {
    "total": 2841,
    "manual": 37,
    "csv": 1200,
    "auto": 96
  }
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | The requested page of ACTIVE entries of the account, newest first. |
| `rows[].id` | uuid | The entry id: the only value DELETE /v1/blacklist/:id accepts. |
| `rows[].email` | string\|null | Lower-cased e-mail; null on a card row. |
| `rows[].card_masked` | string\|null | The card as stored (see gotchas); null on an e-mail row. The card hash itself is never returned. |
| `rows[].reason` | string\|null | Free-text reason (Manual, CSV import, Refunded order...). |
| `rows[].source` | enum: manual\|csv\|refund\|chargeback | How the entry got there; refund / chargeback are written by the refund and alert engines. |
| `rows[].created_by` | string\|null | The caller's e-mail for manual / csv entries, system for automatic ones. |
| `rows[].created_at` | string (ISO 8601) | Insertion time; never updated by a re-add. |
| `rows[].active` | boolean | Always true here. |
| `rows[].threeDsSummary` | object\|null | The customer's 3DS proof inventory for an e-mail row {total, ready, used, expired, pending, failed, readyForRebill, authenticationMode}; null for a card row. |
| `total` | integer | Rows matching the search, ignoring limit / offset (0 on an empty page, see gotchas). |
| `stats.total` | integer | All-time count of the account's ACTIVE rows. |
| `stats.manual / csv / auto` | integer | Rows with source manual / csv / refund created in the last 30 days (active or not). |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: limit outside 1..10000, negative or non-numeric offset, search over 254 chars.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Only active entries are listed; there is no parameter for inactive ones.
- `total` is read from the first returned row: on a page past the end (rows []) it reads 0 even though matching rows exist. Never paginate by trusting total from an empty page.
- card_masked holds the card as stored: the full card digits for a card added through POST /v1/blacklist, the transaction's stored card for an automatic or bulk entry. Account administrators read it in clear (other member roles get it masked first6..last4), so `search` can match a full card number.
- stats.manual + stats.csv + stats.auto do NOT add up to stats.total: total is all-time and active-only, the three others cover the last 30 days, count inactive rows too, and no counter covers source chargeback.
- stats ignores `search`.

##### `POST /v1/blacklist`

**Scope** `customers.write` - **Blacklist a customer**

Add an e-mail and/or a card (full PAN) to the account's blacklist: every later charge matching either is refused. Up to two entries are upserted (an existing one is re-activated). In the same transaction a cleanup job is frozen that ends the customer's live subscriptions (active, paused or failed) found by that e-mail or card; it runs in the background (cleanupId, see GET /v1/blacklist/cleanup/:id).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 256) | no | Customer e-mail, trimmed and lowercased. At least one of email or cardNumber is required. |
| `cardNumber` | string (12..23 chars of digits, spaces, hyphens) | no | The FULL card number (at least 12 digits); hashed for matching. A first6/last4 is useless here. |
| `reason` | string (max 256); default `Partner API` | no | Note stored on the entry; replaces the reason of a re-activated entry. |
| `requestId` | uuid | no | Idempotency id: reuse it with the same input after an uncertain answer to get the same result; the same id with different input answers 409. Generated when omitted. |
| `clientId` | string (owner e-mail, 3..256) | no | Account owner e-mail. With a key: optional, and if sent it must be the key's own account (else 403). With X-Refund-Key: names the account (omitted = the platform owner's account). |

**Request body**

```json
{
  "email": "jane.doe@example.com",
  "cardNumber": "4111 1111 1111 1111",
  "reason": "Chargeback threat, ticket 88213",
  "requestId": "44444444-4444-4444-8444-444444444444"
}
```

**Response**

```json
{
  "added": {
    "email": true,
    "card": true,
    "subsEnded": null,
    "cleanupPending": true,
    "cleanupId": "11111111-1111-4111-8111-111111111111"
  }
}
```

| response field | type | description |
|---|---|---|
| `added.email` | boolean | An e-mail entry was upserted (true also when it already existed). |
| `added.card` | boolean | A card entry was upserted (true also when it already existed). |
| `added.subsEnded` | integer \| null | Subscriptions ended so far: 0 when there was nothing to end, null while the cleanup is pending. |
| `added.cleanupPending` | boolean | true until the subscription cleanup has finished. |
| `added.cleanupId` | uuid | Cleanup job id for GET /v1/blacklist/cleanup/:id (not the blacklist entry id). |
| `testMode` | boolean | Only with the X-Refund-Key test secret: the answer is {"added":[],"testMode":true} and nothing is written. |

**Errors**

- `400` Invalid request (details: zod flatten; bad e-mail or cardNumber format, reason too long, neither email nor cardNumber: "Provide email and/or cardNumber"); or cardNumber must contain at least 12 digits (full PAN).
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.write missing); or clientId does not match the account this key belongs to.
- `409` Request ID already used with different blacklist input or permissions.
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret). Blacklist cleanup worker is unavailable; nothing was activated (background jobs disabled); Blacklist cleanup migration is unavailable; or Blacklist import controls are busy. Retry shortly.
- `504` The request took too long and was cancelled (10 s control budget); retry with the same requestId.

**Gotchas**

- Blacklisting ENDS the customer's live subscriptions of this account (the cleanup job); processing charges are not touched.
- Re-adding an existing entry re-activates it and overwrites its reason (the default reason is "Partner API").
- Send the full card number in the body only, never in a URL.

##### `DELETE /v1/blacklist`

**Scope** `customers.write` - **Remove a customer from the blacklist by e-mail or card number**

Removes a customer from the blacklist by value (e-mail and/or card number); DELETE /v1/blacklist/:id removes one entry by its id. Remove an e-mail and/or a card from the account's blacklist by value. Hard delete of the matching entries (the history of why is gone); subscriptions ended by the blacklisting are not restored.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 256) | no | E-mail to remove (lowercased). At least one of email or cardNumber is required. |
| `cardNumber` | string (12..23 chars of digits, spaces, hyphens) | no | Full card number to remove, matched by hash; fewer than 12 digits is ignored. |
| `clientId` | string (owner e-mail, 3..256) | no | Account owner e-mail. With a key: optional, and if sent it must be the key's own account (else 403). With X-Refund-Key: names the account (omitted = the platform owner's account). |

**Request body**

```json
{
  "email": "jane.doe@example.com"
}
```

**Response**

```json
{
  "removed": {
    "email": true,
    "card": false
  }
}
```

| response field | type | description |
|---|---|---|
| `removed.email` | boolean | An e-mail entry was deleted (false when none existed or no e-mail was sent). |
| `removed.card` | boolean | A card entry was deleted. |
| `testMode` | boolean | Only with the X-Refund-Key test secret: the answer is {"removed":0,"testMode":true} and nothing is deleted. |

**Errors**

- `400` Invalid request (details: zod flatten; bad format, or neither email nor cardNumber). A client that drops DELETE bodies gets this.
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.write missing); or clientId does not match the account this key belongs to.
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret).

**Gotchas**

- A DELETE with a JSON body: send Content-Type: application/json and make sure the client keeps the body.
- Removing something that was not blacklisted answers 200 with both flags false, not 404.

##### `DELETE /v1/blacklist/:id`

**Scope** `customers.write` - **Remove one blacklist entry by id**

Removes one blacklist entry by its id; DELETE /v1/blacklist removes by e-mail or card number. Permanently deletes one blacklist row of the account by its id, unblocking that e-mail or that card, and logs a blacklist.removed customer event. A hard delete, not a deactivation.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | The entry id from GET /v1/blacklist rows[].id. Not pre-validated: a non-UUID is a 400 from the database cast, not a 404. |

**Response** `204`

No example body: see the purpose above for what the response carries.

| response field | type | description |
|---|---|---|
| `(none)` | empty | 204 No Content with an empty body. |

**Errors**

- `400` {"error":"A value has an invalid format."}: :id is not a UUID (database cast error, mapped to 400 before any lookup).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Not found"}: a valid UUID that matches no row of the account (already deleted, never existed, or another account's).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Success is 204 with an EMPTY body: do not parse JSON.
- Deletes exactly ONE row: a customer added with both e-mail and card has two rows.
- Not a permanent allow: the refund engine re-adds the e-mail and card (source refund) when a later order of that customer is refunded, if the account auto-blacklists on refund.
- No delete-by-value here: list first to get the id.
- Retry trap: a second DELETE of the same id answers 404, so a retry after a timeout can report failure although the first call succeeded.

##### `POST /v1/blacklist/check`

**Scope** `customers.read` - **Check whether a customer is blacklisted**

Read-only lookup: is this e-mail and/or card on the account's ACTIVE blacklist? POST so the card number never lands in a URL. Uses the read scope.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 256) | no | E-mail, compared exactly after lowercasing. At least one of email or cardNumber is required. |
| `cardNumber` | string (12..23 chars of digits, spaces, hyphens) | no | Full card number, compared by hash. A value with fewer than 12 digits is ignored (no 400 here). |
| `clientId` | string (owner e-mail, 3..256) | no | Account owner e-mail. With a key: optional, and if sent it must be the key's own account (else 403). With X-Refund-Key: names the account (omitted = the platform owner's account). |

**Request body**

```json
{
  "email": "jane.doe@example.com",
  "cardNumber": "4111111111111111"
}
```

**Response**

```json
{
  "blacklisted": true,
  "matched": "card",
  "reason": "Chargeback threat, ticket 88213"
}
```

| response field | type | description |
|---|---|---|
| `blacklisted` | boolean | An active entry matched the e-mail or the card. |
| `matched` | string \| null | card or email: which side matched on the one entry read; null when not blacklisted. When both are blacklisted either may be reported. |
| `reason` | string \| null | Reason stored on the matched entry (may be null even when blacklisted). |

**Errors**

- `400` Invalid request (details: zod flatten; bad format, or neither email nor cardNumber).
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.read missing); or clientId does not match the account this key belongs to.
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret).

**Gotchas**

- The per-IP limit (default 20 per minute) applies to lookups too: this is not a bulk scanning endpoint.

##### `GET /v1/blacklist/cleanup`

**Scope** `customers.read` - **List required blacklist cleanup**

List the account's required subscription cleanups: after a blacklist activation (manual, CSV, or automatic after a refund or chargeback) commits, the account's live subscriptions of that customer are ended by a background cleanup job. This page shows those jobs, unfinished ones first then newest first, 20 per page. Read-only; no payment provider call.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer; default `0` | no | Zero-based row offset, 0..100000. Page size is 20 (hasMore tells whether a next page exists). Anything else answers 400 {"error":"Invalid cleanup page"}. |
| `requestId` | uuid | no | Return only the cleanup of this blacklist admission request (jobs has 0 or 1 item), whatever its age; offset is then ignored. A non-uuid answers 400 {"error":"Invalid request reference"}. |

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "request_id": "00000000-0000-4000-8000-000000000002",
      "status": "running",
      "total": 55,
      "processed": 50,
      "ended": 48,
      "diagnostic": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:05.000Z",
      "finished_at": null,
      "next_attempt_at": null,
      "succeeded": 48,
      "skipped": 2,
      "failed": 0,
      "errors": [],
      "cleanupPending": true
    }
  ],
  "hasMore": false,
  "offset": 0,
  "available": true,
  "configured": true,
  "enabled": true,
  "workerAvailable": true
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | Up to 20 cleanup jobs. |
| `jobs[].id` | uuid | Cleanup job id (use it with the retry endpoint). |
| `jobs[].request_id` | uuid | The blacklist admission request this cleanup belongs to (filter with requestId). |
| `jobs[].status` | string | queued, running, success or failed. Only failed can be retried. |
| `jobs[].total` | integer | Subscriptions frozen into the cleanup snapshot at activation. |
| `jobs[].processed` | integer | Subscriptions examined so far. |
| `jobs[].ended` | integer | Subscriptions actually ended (also returned as succeeded). |
| `jobs[].succeeded` | integer | Equal to ended. |
| `jobs[].skipped` | integer | processed minus ended (already ended, or a charge in flight). |
| `jobs[].failed` | integer | 1 when status is failed, else 0. |
| `jobs[].errors` | array | Always empty (no per-row diagnostics are exposed). |
| `jobs[].cleanupPending` | boolean | true until status is success. |
| `jobs[].diagnostic` | object\|null | Last failure diagnostic (references only, no card data); cleared by a retry. |
| `jobs[].created_at / updated_at / finished_at` | timestamp | Lifecycle timestamps; finished_at null while not finished. Other storage columns such as next_attempt_at may appear. |
| `hasMore` | boolean | true when another page exists at offset + 20. |
| `offset` | integer | The offset served. |
| `available / configured` | boolean | Always true. |
| `enabled / workerAvailable` | boolean | Whether background workers run on this deployment; when false, queued cleanups wait. |

**Errors**

- `400` {"error":"Invalid cleanup page"} (offset not an integer 0..100000) or {"error":"Invalid request reference"} (requestId not a uuid).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Account access changed"} or {"error":"Account access or permissions changed"}: the account, the key or its blacklist permission changed while the request was being authorized.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Required storage for blacklist cleanup is unavailable. Complete the current database migrations.","requestId":"<id>"} when the cleanup storage is not migrated yet, or {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} when the blacklist controls are saturated (32 concurrent requests); Retry-After: 1, retry shortly.

**Gotchas**

- The cleanup snapshot is frozen at activation: subscriptions created later are not added, and entries already processing or paid are not cancelled.
- Cleanup jobs run on the background workers; when enabled is false they stay queued (automatic refund or chargeback activations may stay pending).
- Job rows hold references only, never card numbers or raw transaction payloads. Successful history is kept 30 days; unresolved obligations are kept.

##### `GET /v1/blacklist/cleanup/:id`

**Scope** `customers.read` - **Read a blacklist cleanup job**

Read the status of the subscription cleanup started by a blacklisting (cleanupId from POST /v1/blacklist). Read only: no payment call, no replay.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Cleanup job id (added.cleanupId). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string (owner e-mail, 3..256) | no | With a key: optional, must be the key's own account if sent (else 403). With X-Refund-Key: the account (omitted = the platform owner's account). |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "request_id": "44444444-4444-4444-8444-444444444444",
    "compacted_at": null,
    "total": 2,
    "processed": 2,
    "ended": 2,
    "status": "success",
    "next_attempt_at": "2026-11-20T10:00:00.000Z",
    "diagnostic": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:04.000Z",
    "finished_at": "2026-11-20T10:00:04.000Z",
    "succeeded": 2,
    "skipped": 0,
    "failed": 0,
    "errors": [],
    "cleanupPending": false
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id / request_id` | string | Cleanup id and the blacklisting requestId. |
| `job.status` | string | queued \| running \| success \| failed. |
| `job.total / processed / ended` | integer | Subscriptions frozen at activation, processed, and actually ended. |
| `job.succeeded / skipped / failed` | integer | succeeded = ended; skipped = processed - ended; failed = 1 when status is failed. |
| `job.diagnostic` | object \| null | Short failure diagnostic. |
| `job.next_attempt_at / created_at / updated_at / finished_at / compacted_at` | string (ISO 8601) \| null | Worker and lifecycle timestamps. |
| `job.errors / cleanupPending` | array / boolean | errors is always []; cleanupPending is true until status is success. |

**Errors**

- `400` Invalid cleanup reference (id not a uuid, or clientId out of bounds).
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.read missing); or clientId does not match the account this key belongs to.
- `404` Cleanup reference not found for this account.
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret). Blacklist import controls are busy. Retry shortly.
- `504` The request took too long and was cancelled; retry.

**Gotchas**

- The set of subscriptions is frozen at activation; a failed job can be retried from POST /v1/blacklist/cleanup/:id/retry.

##### `POST /v1/blacklist/cleanup/:id/retry`

**Scope** `customers.write` - **Retry a failed blacklist cleanup**

Re-queue one FAILED required cleanup job of the account (status back to queued, attempts reset, diagnostic cleared) so the background worker resumes ending the frozen set of subscriptions. No payment provider call and no new blacklist activation.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Cleanup job id from the cleanup list. A non-uuid answers 400 {"error":"Invalid cleanup reference"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "status": "queued",
    "total": 55,
    "processed": 50,
    "ended": 48,
    "diagnostic": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:05.000Z",
    "finished_at": null,
    "next_attempt_at": null,
    "succeeded": 48,
    "skipped": 2,
    "failed": 0,
    "errors": [],
    "cleanupPending": true
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The re-queued job, same shape as one item of the cleanup list. |

**Errors**

- `400` {"error":"Invalid cleanup reference"}: :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"Account access changed"} or {"error":"Account access or permissions changed"}: the account, the key or its blacklist permission changed while the request was being authorized.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan does not include that module.
- `404` {"error":"Required cleanup not found"}: no failed cleanup with this id in the account.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"A required data table is unavailable."} when the cleanup storage is not migrated yet.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} when the blacklist controls are saturated (32 concurrent requests); Retry-After: 1, retry shortly.

**Gotchas**

- Only a job whose status is failed can be retried; a queued, running or successful job (or another account's id) answers 404.
- A retry never adds subscriptions to the frozen snapshot; it only resumes the remaining ones.

##### `GET /v1/blacklist/client/:clientId`

**Scope** `customers.read` - **List an account's blacklisted customers with their matched orders (partner view)**

Partner view: the account's blacklisted customers who appear on its transactions, with the matched orders; GET /v1/blacklist lists every entry with search and counts by source. Paged list of the account's blacklisted customers who appear on a transaction charged by that account (its keys or its CSV imports), with an optional window on when they were blacklisted.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string (owner e-mail, max 256) | **yes** | Account owner e-mail, URL-encoded (owner%40example.com). With a key it must be the key's own account (else 403). |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `dateStart` | string (YYYY-MM-DD or ISO date-time) | no | Keeps customers blacklisted at or after this instant (a bare date = 00:00:00.000Z). Filters on the blacklisting date, not on transaction dates. |
| `dateEnd` | string (YYYY-MM-DD or ISO date-time) | no | Keeps customers blacklisted at or before this instant (a bare date covers its whole UTC day). Must not be before dateStart. |
| `includeInactive` | string (true\|false\|1\|0); default `false` | no | true or 1 also returns entries that are no longer active. |
| `page` | integer (>= 1); default `1` | no | Page number. |
| `pageSize` | integer (1..500); default `100` | no | Rows per page. |

**Response**

```json
{
  "clientId": "owner@example.com",
  "dateStart": null,
  "dateEnd": null,
  "page": 1,
  "pageSize": 100,
  "total": 1,
  "customers": [
    {
      "blacklistId": "11111111-1111-4111-8111-111111111111",
      "customerId": "cus_eba180bb302fe0e3",
      "email": "jane.doe@example.com",
      "card": "4111111111111111",
      "firstName": "Jane",
      "lastName": "Doe",
      "customerName": "Jane Doe",
      "clientName": "owner@example.com",
      "orderId": "ORD-100245",
      "transactionId": "22222222-2222-4222-8222-222222222222",
      "reason": "Chargeback",
      "source": "chargeback",
      "createdBy": "owner@example.com",
      "createdAt": "2026-11-12T10:04:11.000Z",
      "active": true,
      "matchedBy": "both",
      "transactions": 3,
      "firstSeenAt": "2026-10-02T09:12:00.000Z",
      "lastSeenAt": "2026-11-11T18:40:00.000Z",
      "merchants": [
        {
          "merchantId": "33333333-3333-4333-8333-333333333333",
          "mid": "Example MID 01",
          "midNumber": "500100200300"
        }
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `clientId` | string | Echo of the path value. |
| `dateStart / dateEnd` | string \| null | The normalised window applied (ISO). |
| `page / pageSize` | integer | Echo of the paging. |
| `total` | integer | Customers matching the scope and window, before paging. |
| `customers[]` | object[] | One row per customer (an e-mail entry and a card entry of the same person are folded into one), newest blacklisting first. |
| `customers[].blacklistId` | uuid | Id of the newest blacklist entry of the customer. |
| `customers[].customerId` | string \| null | Stable cus_ id derived from the e-mail, the same as the transaction endpoints return; null when no e-mail is known. |
| `customers[].email` | string \| null | Blacklisted e-mail, else the e-mail of the newest matched transaction. |
| `customers[].card` | string \| null | Card value as stored on the entry (the full card number for an entry added with a full PAN), else the card of the newest matched transaction. |
| `customers[].firstName / lastName / customerName` | string \| null | From the newest matched transaction. |
| `customers[].clientName` | string \| null | Account e-mail of the newest matched transaction. |
| `customers[].orderId / transactionId` | string \| null | Newest matched order and transaction. |
| `customers[].reason / source / createdBy / createdAt` | mixed | Why (reason text), how (refund, chargeback, manual, csv), who and when the customer was blacklisted (createdAt is what the date window filters). |
| `customers[].active` | boolean | false only with includeInactive. |
| `customers[].matchedBy` | string | email \| card \| both: how the entry was tied to a transaction of the scope. |
| `customers[].transactions` | integer | Matched charges (any outcome) inside the scope. |
| `customers[].firstSeenAt / lastSeenAt` | string (ISO 8601) | First and last matched charge. |
| `customers[].merchants[]` | object[] | {merchantId, mid (name), midNumber} of the account's MIDs they transacted on. |

**Errors**

- `400` clientId is required; Invalid request (details: zod flatten; bad includeInactive, page or pageSize); dateStart/dateEnd must be ISO dates (YYYY-MM-DD) or ISO datetimes; or dateStart must be <= dateEnd.
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.read missing); or clientId does not match the account this key belongs to.
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret).

**Gotchas**

- Only this account's blacklist entries are considered. A customer appears when an active entry matches a transaction of the scope by e-mail or by card (card matches need the card number on the transaction, so wallet charges only match by e-mail). A customer who never transacted in the scope is not listed.
- customerId is the same stable id the transaction endpoints return, which lets a CRM join this list to its transactions.

##### `POST /v1/blacklist/import`

**Scope** `customers.write` - **Import blacklist e-mails now (synchronous)**

Imports blacklist e-mails now, inside the request (synchronous, for small lists); POST /v1/blacklist/import-jobs runs the same import as a background job for large lists. Blacklists a list of e-mails synchronously, one activation per e-mail with source csv (cards are not imported here). Each activation and its subscription cleanup snapshot commit on their own; the request as a whole is NOT atomic. For large files, the durable import jobs (POST /v1/blacklist/import-jobs) are the reliable path.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `emails` | string[] | **yes** | 1..50000 entries. EVERY element must be a valid e-mail of max 254 chars: one bad element rejects the whole batch. Trimmed, lower-cased and de-duplicated before activation. |
| `reason` | string; default `CSV import` | no | Max 64 chars, applied to every row. |
| `requestId` | uuid | no | Caller-kept UUID; a per-e-mail request reference is derived from it so a retry with the identical body replays instead of re-activating. Omitted: every activation gets a server-generated reference. |

**Request body**

```json
{
  "emails": [
    "repeat.refunder@example.com",
    "Chargeback.Andy@Example.com",
    "disputes@example.com"
  ],
  "reason": "Q3 chargeback list",
  "requestId": "00000000-0000-4000-8000-000000000131"
}
```

**Response** `201`

```json
{
  "added": 3,
  "subsEnded": null,
  "cleanupPending": true,
  "cleanupJobs": 3
}
```

| response field | type | description |
|---|---|---|
| `added` | integer | Unique e-mails processed after trim, lower-case and de-duplication. |
| `subsEnded` | integer\|null | Confirmed total only when every cleanup is complete; null if any is pending. |
| `cleanupPending` | boolean | At least one e-mail still has a required cleanup. |
| `cleanupJobs` | integer | Number of saved cleanup operations referenced by this call. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>}: emails missing or empty, more than 50000 entries, an element not a valid e-mail or over 254 chars, reason over 64 chars, requestId not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted Kontrol subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the plan excludes the payments tool.
- `403` {"error":"No account"} when the caller resolves to no account.
- `403` {"error":"Account access changed"} / {"error":"Account access or permissions changed"}: the account, the key or the caller's access changed while the write was admitted (rechecked inside the transaction); nothing was activated.
- `409` {"error":"Request ID already used with different blacklist input or permissions"}: the requestId was already used with another body or caller; nothing new was activated.
- `413` The body exceeds the 1 MB request limit: rejected before the handler, nothing imported (in practice about 25000 to 30000 e-mails).
- `429` Rate limited: 300 requests per minute per client IP (the API default).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` The database is momentarily unavailable (Retry-After: 1); retry after a second.
- `503` {"error":"Blacklist cleanup migration is unavailable"}, {"error":"Blacklist cleanup worker is unavailable; nothing was activated"} (background workers disabled) or {"error":"Blacklist import controls are busy. Retry shortly."}: nothing was activated. Retry with the SAME requestId.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` The activation exceeded its deadline (10 s per activation, 25 s per request) and was cancelled ("The request took too long and was cancelled ..."). The outcome may be uncertain for the last item: retry with the SAME requestId to reconcile.

**Gotchas**

- FIELD-TYPE TRAP: `added` is a NUMBER here but an OBJECT on POST /v1/blacklist.
- `added` counts the unique e-mails sent (after de-duplication), not rows created.
- Not atomic: e-mails are activated one by one, so an error or a deadline part-way leaves the earlier ones active. Retry with the same requestId: done e-mails replay, the rest are activated.
- Sequential within one request (25-second budget): a large list can time out. Use the import jobs for files of any size.
- A re-imported e-mail is reactivated and its reason replaced; its source and created_by are kept.
- subsEnded is null as soon as one e-mail still has a pending cleanup.

##### `GET /v1/blacklist/import-capabilities`

**Scope** `customers.read` - **Blacklist import capability**

Says whether background blacklist e-mail imports can be submitted with POST /v1/blacklist/import-jobs. Also checks the caller's current right to import.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | True when background jobs run on this deployment (and the import storage exists). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly. {"error":"Required storage for blacklist imports is unavailable. Complete the current database migrations.","requestId":"<id>"} when the import storage is missing.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- If the import storage is missing the answer is a 503 {"error":"Required storage for blacklist imports is unavailable. Complete the current database migrations.","requestId":"<id>"} (a missing migration), not enabled:false.

##### `GET /v1/blacklist/import-jobs`

**Scope** `customers.read` - **List blacklist imports**

Lists up to 20 blacklist imports of the caller, active ones (queued, running or with cleanup pending) first, then newest first. Optionally finds the job of one requestId.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | no | Return only the job created with this requestId (use it to recover a job after an uncertain POST answer). |

**Response**

```json
{
  "jobs": [
    {
      "id": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
      "request_id": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
      "reason": "CSV import",
      "status": "running",
      "total": 1200,
      "processed": 350,
      "subs_total": 14,
      "subs_processed": 0,
      "subs_ended": 0,
      "cancel_requested": false,
      "cleanup_pending": false,
      "version": 1,
      "attempts": 1,
      "next_attempt_at": "2026-11-20T14:00:00.000Z",
      "error": null,
      "diagnostic": null,
      "created_at": "2026-11-20T14:00:00.000Z",
      "updated_at": "2026-11-20T14:00:12.000Z",
      "finished_at": null,
      "added": 350,
      "phase": "Adding emails"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | At most 20 jobs; never the e-mail list. |
| `jobs[].id` | string (uuid) | Job id. |
| `jobs[].request_id` | string (uuid) | The requestId sent at creation. |
| `jobs[].reason` | string | Reason written on the blacklist rows (default "CSV import"). |
| `jobs[].status` | enum: queued \| running \| success \| partial \| failed \| cancelled | Lifecycle status. A stopped job with subscription cleanup still to do stays running. |
| `jobs[].total` | integer | Distinct e-mails to import (after trimming, lowercasing and de-duplication). |
| `jobs[].processed` | integer | E-mails already added to the blacklist (committed pages of 50). |
| `jobs[].subs_total` | integer | Active, paused or failed subscriptions of those e-mails found so far, to be ended. |
| `jobs[].subs_processed` | integer | Subscriptions handled by the cleanup so far. |
| `jobs[].subs_ended` | integer | Subscriptions actually ended so far. |
| `jobs[].cancel_requested` | boolean | True once a stop was requested. |
| `jobs[].cleanup_pending` | boolean | True while subscription cleanup is still owed (it continues even after a stop). |
| `jobs[].version` | integer | Row version, incremented on each control change. |
| `jobs[].attempts` | integer | Worker attempts of the current step (transient errors retry at most 3 times). |
| `jobs[].next_attempt_at` | string (ISO 8601) | When the worker may next pick the job. |
| `jobs[].error` | string \| null | Failure reason. |
| `jobs[].diagnostic` | object \| null | Safe diagnostic of a failed step: {stage: activation \| cleanup, code: cleanup_owner_mismatch \| pending_charge_owner_mismatch \| access_changed \| database_transient \| checkpoint_failed, checkpoint, subId?, ordinalFrom?, ordinalTo?}. |
| `jobs[].created_at` | string (ISO 8601) | Creation time. |
| `jobs[].updated_at` | string (ISO 8601) | Last change. |
| `jobs[].finished_at` | string \| null | End time. |
| `jobs[].added` | integer | Same value as processed. |
| `jobs[].phase` | enum: Adding emails \| Ending subscriptions | Ending subscriptions while cleanup_pending is true, else Adding emails. |

**Errors**

- `400` {"error":"Invalid request ID"} when requestId is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Blacklist import history is unavailable"} when the deployment has no import storage.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- No pagination; the e-mail list itself is never returned.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/blacklist/import-jobs`

**Scope** `customers.write` - **Queue a blacklist e-mail import (background job)**

Queues a blacklist e-mail import as a background job (up to 50000 e-mails); POST /v1/blacklist/import imports a small list synchronously. Queues a background import of up to 50000 e-mails into the account's blacklist and answers 202 {jobId, job}. The worker adds the e-mails in pages of 50 (an existing row is reactivated and its reason updated), snapshots the active, paused or failed subscriptions of those e-mails, then ends them (the cleanup phase). Use it instead of many POST /v1/blacklist calls.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Your idempotency key. Same requestId with the same e-mails, reason and caller returns the existing job; a different input or caller answers 409. |
| `emails` | string[] | **yes** | 1 to 50000 e-mail addresses. |
| `emails[]` | string (email) | **yes** | A valid e-mail, max 254 characters. Trimmed, lowercased and de-duplicated before import. |
| `reason` | string; default `CSV import` | no | Reason stored on each blacklist row, max 64 characters. |

**Request body**

```json
{
  "requestId": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
  "emails": [
    "buyer.one@example.com",
    "buyer.two@example.com"
  ],
  "reason": "Chargeback list"
}
```

**Response**

```json
{
  "jobId": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
  "job": {
    "id": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
    "request_id": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
    "reason": "Chargeback list",
    "status": "queued",
    "total": 2,
    "processed": 0,
    "subs_total": 0,
    "subs_processed": 0,
    "subs_ended": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "version": 1,
    "attempts": 0,
    "next_attempt_at": "2026-11-20T14:00:00.000Z",
    "error": null,
    "diagnostic": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:00.000Z",
    "finished_at": null,
    "added": 0,
    "phase": "Adding emails"
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | string (uuid) | The job id. |
| `job` | object | The job (HTTP 202). |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.reason` | string | Reason written on the blacklist rows (default "CSV import"). |
| `job.status` | enum: queued \| running \| success \| partial \| failed \| cancelled | Lifecycle status. A stopped job with subscription cleanup still to do stays running. |
| `job.total` | integer | Distinct e-mails to import (after trimming, lowercasing and de-duplication). |
| `job.processed` | integer | E-mails already added to the blacklist (committed pages of 50). |
| `job.subs_total` | integer | Active, paused or failed subscriptions of those e-mails found so far, to be ended. |
| `job.subs_processed` | integer | Subscriptions handled by the cleanup so far. |
| `job.subs_ended` | integer | Subscriptions actually ended so far. |
| `job.cancel_requested` | boolean | True once a stop was requested. |
| `job.cleanup_pending` | boolean | True while subscription cleanup is still owed (it continues even after a stop). |
| `job.version` | integer | Row version, incremented on each control change. |
| `job.attempts` | integer | Worker attempts of the current step (transient errors retry at most 3 times). |
| `job.next_attempt_at` | string (ISO 8601) | When the worker may next pick the job. |
| `job.error` | string \| null | Failure reason. |
| `job.diagnostic` | object \| null | Safe diagnostic of a failed step: {stage: activation \| cleanup, code: cleanup_owner_mismatch \| pending_charge_owner_mismatch \| access_changed \| database_transient \| checkpoint_failed, checkpoint, subId?, ordinalFrom?, ordinalTo?}. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.added` | integer | Same value as processed. |
| `job.phase` | enum: Adding emails \| Ending subscriptions | Ending subscriptions while cleanup_pending is true, else Adding emails. |

**Errors**

- `400` {"error":"Invalid import","details":<zod flatten()>} for an invalid body (not a uuid, an invalid e-mail, more than 50000 e-mails, a reason over 64 characters, an unknown field).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Blacklist import history is unavailable"} when the deployment has no import storage.
- `409` {"error":"Request ID already used with different input or permissions"}; {"error":"Another blacklist import or required cleanup is active"}.
- `413` Body larger than 14 MiB.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import background jobs are disabled"} when background jobs are off on this deployment. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- Strict body: an unknown field is a 400. Body limit 14 MiB.
- One import (or one pending subscription cleanup) at a time per account: another one answers 409 until it finishes.
- Ending subscriptions cannot be undone, and a charge already in progress at a provider is not reversed by the import.
- Stopping (POST /v1/blacklist/import-jobs/:id/cancel) keeps the e-mails already added and still finishes the owed subscription cleanup.
- Finished jobs are deleted 7 days after they end (a job with cleanup still pending is kept).
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/blacklist/import-jobs/:id`

**Scope** `customers.read` - **Get a blacklist import**

Reads one blacklist import's progress. Poll it until status is success, partial, failed or cancelled and cleanup_pending is false.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
    "request_id": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
    "reason": "CSV import",
    "status": "running",
    "total": 1200,
    "processed": 350,
    "subs_total": 14,
    "subs_processed": 0,
    "subs_ended": 0,
    "cancel_requested": false,
    "cleanup_pending": false,
    "version": 1,
    "attempts": 1,
    "next_attempt_at": "2026-11-20T14:00:00.000Z",
    "error": null,
    "diagnostic": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:12.000Z",
    "finished_at": null,
    "added": 350,
    "phase": "Adding emails"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job. |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.reason` | string | Reason written on the blacklist rows (default "CSV import"). |
| `job.status` | enum: queued \| running \| success \| partial \| failed \| cancelled | Lifecycle status. A stopped job with subscription cleanup still to do stays running. |
| `job.total` | integer | Distinct e-mails to import (after trimming, lowercasing and de-duplication). |
| `job.processed` | integer | E-mails already added to the blacklist (committed pages of 50). |
| `job.subs_total` | integer | Active, paused or failed subscriptions of those e-mails found so far, to be ended. |
| `job.subs_processed` | integer | Subscriptions handled by the cleanup so far. |
| `job.subs_ended` | integer | Subscriptions actually ended so far. |
| `job.cancel_requested` | boolean | True once a stop was requested. |
| `job.cleanup_pending` | boolean | True while subscription cleanup is still owed (it continues even after a stop). |
| `job.version` | integer | Row version, incremented on each control change. |
| `job.attempts` | integer | Worker attempts of the current step (transient errors retry at most 3 times). |
| `job.next_attempt_at` | string (ISO 8601) | When the worker may next pick the job. |
| `job.error` | string \| null | Failure reason. |
| `job.diagnostic` | object \| null | Safe diagnostic of a failed step: {stage: activation \| cleanup, code: cleanup_owner_mismatch \| pending_charge_owner_mismatch \| access_changed \| database_transient \| checkpoint_failed, checkpoint, subId?, ordinalFrom?, ordinalTo?}. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.added` | integer | Same value as processed. |
| `job.phase` | enum: Adding emails \| Ending subscriptions | Ending subscriptions while cleanup_pending is true, else Adding emails. |

**Errors**

- `400` {"error":"Invalid job ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Job not found"}; {"error":"Blacklist import history is unavailable"} when the deployment has no import storage.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- Counters reflect committed pages only; nothing is guessed for a page whose outcome is unknown.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/blacklist/import-jobs/:id/cancel`

**Scope** `customers.write` - **Stop a blacklist import**

Stops selecting new e-mails and returns the job. Without pending cleanup the job becomes cancelled at once; with subscriptions still to end it stays running until the cleanup is done. E-mails already added stay blacklisted. A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
    "request_id": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
    "reason": "CSV import",
    "status": "cancelled",
    "total": 1200,
    "processed": 350,
    "subs_total": 14,
    "subs_processed": 0,
    "subs_ended": 0,
    "cancel_requested": true,
    "cleanup_pending": false,
    "version": 2,
    "attempts": 1,
    "next_attempt_at": "2026-11-20T14:00:00.000Z",
    "error": null,
    "diagnostic": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:12.000Z",
    "finished_at": "2026-11-20T14:01:00.000Z",
    "added": 350,
    "phase": "Adding emails"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after the stop. |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.reason` | string | Reason written on the blacklist rows (default "CSV import"). |
| `job.status` | enum: queued \| running \| success \| partial \| failed \| cancelled | Lifecycle status. A stopped job with subscription cleanup still to do stays running. |
| `job.total` | integer | Distinct e-mails to import (after trimming, lowercasing and de-duplication). |
| `job.processed` | integer | E-mails already added to the blacklist (committed pages of 50). |
| `job.subs_total` | integer | Active, paused or failed subscriptions of those e-mails found so far, to be ended. |
| `job.subs_processed` | integer | Subscriptions handled by the cleanup so far. |
| `job.subs_ended` | integer | Subscriptions actually ended so far. |
| `job.cancel_requested` | boolean | True once a stop was requested. |
| `job.cleanup_pending` | boolean | True while subscription cleanup is still owed (it continues even after a stop). |
| `job.version` | integer | Row version, incremented on each control change. |
| `job.attempts` | integer | Worker attempts of the current step (transient errors retry at most 3 times). |
| `job.next_attempt_at` | string (ISO 8601) | When the worker may next pick the job. |
| `job.error` | string \| null | Failure reason. |
| `job.diagnostic` | object \| null | Safe diagnostic of a failed step: {stage: activation \| cleanup, code: cleanup_owner_mismatch \| pending_charge_owner_mismatch \| access_changed \| database_transient \| checkpoint_failed, checkpoint, subId?, ordinalFrom?, ordinalTo?}. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.added` | integer | Same value as processed. |
| `job.phase` | enum: Adding emails \| Ending subscriptions | Ending subscriptions while cleanup_pending is true, else Adding emails. |

**Errors**

- `400` {"error":"Invalid job ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Job not found"}; {"error":"Blacklist import history is unavailable"} when the deployment has no import storage.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- No body is read.
- Idempotent on a finished job.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/blacklist/import-jobs/:id/retry-cleanup`

**Scope** `customers.write` - **Retry blacklist import cleanup**

Restarts the owed subscription cleanup of an import whose cleanup stopped after exhausting its retries: resets attempts, clears error and diagnostic, marks the job running and stops selecting new e-mails. Returns the job.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Job id. |

**Response**

```json
{
  "job": {
    "id": "2e9b7c4a-1d3f-4a8e-9b6c-5f0a2d7e1c93",
    "request_id": "7f3a9c1e-5b2d-4e6a-8c4f-1a0b9d2e7c58",
    "reason": "CSV import",
    "status": "running",
    "total": 1200,
    "processed": 350,
    "subs_total": 14,
    "subs_processed": 0,
    "subs_ended": 0,
    "cancel_requested": true,
    "cleanup_pending": true,
    "version": 3,
    "attempts": 0,
    "next_attempt_at": "2026-11-20T14:00:00.000Z",
    "error": null,
    "diagnostic": null,
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:12.000Z",
    "finished_at": null,
    "added": 350,
    "phase": "Ending subscriptions"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after the retry request. |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.reason` | string | Reason written on the blacklist rows (default "CSV import"). |
| `job.status` | enum: queued \| running \| success \| partial \| failed \| cancelled | Lifecycle status. A stopped job with subscription cleanup still to do stays running. |
| `job.total` | integer | Distinct e-mails to import (after trimming, lowercasing and de-duplication). |
| `job.processed` | integer | E-mails already added to the blacklist (committed pages of 50). |
| `job.subs_total` | integer | Active, paused or failed subscriptions of those e-mails found so far, to be ended. |
| `job.subs_processed` | integer | Subscriptions handled by the cleanup so far. |
| `job.subs_ended` | integer | Subscriptions actually ended so far. |
| `job.cancel_requested` | boolean | True once a stop was requested. |
| `job.cleanup_pending` | boolean | True while subscription cleanup is still owed (it continues even after a stop). |
| `job.version` | integer | Row version, incremented on each control change. |
| `job.attempts` | integer | Worker attempts of the current step (transient errors retry at most 3 times). |
| `job.next_attempt_at` | string (ISO 8601) | When the worker may next pick the job. |
| `job.error` | string \| null | Failure reason. |
| `job.diagnostic` | object \| null | Safe diagnostic of a failed step: {stage: activation \| cleanup, code: cleanup_owner_mismatch \| pending_charge_owner_mismatch \| access_changed \| database_transient \| checkpoint_failed, checkpoint, subId?, ordinalFrom?, ordinalTo?}. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.added` | integer | Same value as processed. |
| `job.phase` | enum: Adding emails \| Ending subscriptions | Ending subscriptions while cleanup_pending is true, else Adding emails. |

**Errors**

- `400` {"error":"Invalid job ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"} when the account's plan lacks the payments module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access changed"}; {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Job not found"}; {"error":"Blacklist import history is unavailable"} when the deployment has no import storage.
- `409` {"error":"No pending subscription cleanup"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Blacklist import controls are busy. Retry shortly.","requestId":"<id>"} with Retry-After: 1 when the import controls are saturated (more than 32 concurrent control requests per instance): retry shortly.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the bounded database work exceeds its budget.

**Gotchas**

- Only for a job with cleanup_pending true: otherwise 409.
- It also stops the import of further e-mails (cancel_requested becomes true).
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/blacklist/merchant/:merchantId`

**Scope** `customers.read` - **List blacklisted customers of a merchant (one MID)**

Paged list of the account's blacklisted customers who appear on a transaction charged through ONE of the account's MIDs, with an optional window on when they were blacklisted.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `merchantId` | string (max 128) | **yes** | The MID: its gateway id (uuid, paymentGatewayId on transactions) or its MID number. It must belong to the account. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `clientId` | string (owner e-mail) | no | With a key: optional, must be the key's own account if sent (else 403). With X-Refund-Key: the account that owns the MID (omitted = the platform owner's account). |
| `dateStart` | string (YYYY-MM-DD or ISO date-time) | no | Keeps customers blacklisted at or after this instant (a bare date = 00:00:00.000Z). Filters on the blacklisting date, not on transaction dates. |
| `dateEnd` | string (YYYY-MM-DD or ISO date-time) | no | Keeps customers blacklisted at or before this instant (a bare date covers its whole UTC day). Must not be before dateStart. |
| `includeInactive` | string (true\|false\|1\|0); default `false` | no | true or 1 also returns entries that are no longer active. |
| `page` | integer (>= 1); default `1` | no | Page number. |
| `pageSize` | integer (1..500); default `100` | no | Rows per page. |

**Response**

```json
{
  "merchantId": "500100200300",
  "dateStart": null,
  "dateEnd": null,
  "page": 1,
  "pageSize": 100,
  "total": 1,
  "customers": [
    {
      "blacklistId": "11111111-1111-4111-8111-111111111111",
      "customerId": "cus_eba180bb302fe0e3",
      "email": "jane.doe@example.com",
      "card": "4111111111111111",
      "firstName": "Jane",
      "lastName": "Doe",
      "customerName": "Jane Doe",
      "clientName": "owner@example.com",
      "orderId": "ORD-100245",
      "transactionId": "22222222-2222-4222-8222-222222222222",
      "reason": "Chargeback",
      "source": "chargeback",
      "createdBy": "owner@example.com",
      "createdAt": "2026-11-12T10:04:11.000Z",
      "active": true,
      "matchedBy": "both",
      "transactions": 3,
      "firstSeenAt": "2026-10-02T09:12:00.000Z",
      "lastSeenAt": "2026-11-11T18:40:00.000Z",
      "merchants": [
        {
          "merchantId": "33333333-3333-4333-8333-333333333333",
          "mid": "Example MID 01",
          "midNumber": "500100200300"
        }
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `merchantId` | string | Echo of the path value. |
| `dateStart / dateEnd` | string \| null | The normalised window applied (ISO). |
| `page / pageSize` | integer | Echo of the paging. |
| `total` | integer | Customers matching the scope and window, before paging. |
| `customers[]` | object[] | One row per customer (an e-mail entry and a card entry of the same person are folded into one), newest blacklisting first. |
| `customers[].blacklistId` | uuid | Id of the newest blacklist entry of the customer. |
| `customers[].customerId` | string \| null | Stable cus_ id derived from the e-mail, the same as the transaction endpoints return; null when no e-mail is known. |
| `customers[].email` | string \| null | Blacklisted e-mail, else the e-mail of the newest matched transaction. |
| `customers[].card` | string \| null | Card value as stored on the entry (the full card number for an entry added with a full PAN), else the card of the newest matched transaction. |
| `customers[].firstName / lastName / customerName` | string \| null | From the newest matched transaction. |
| `customers[].clientName` | string \| null | Account e-mail of the newest matched transaction. |
| `customers[].orderId / transactionId` | string \| null | Newest matched order and transaction. |
| `customers[].reason / source / createdBy / createdAt` | mixed | Why (reason text), how (refund, chargeback, manual, csv), who and when the customer was blacklisted (createdAt is what the date window filters). |
| `customers[].active` | boolean | false only with includeInactive. |
| `customers[].matchedBy` | string | email \| card \| both: how the entry was tied to a transaction of the scope. |
| `customers[].transactions` | integer | Matched charges (any outcome) inside the scope. |
| `customers[].firstSeenAt / lastSeenAt` | string (ISO 8601) | First and last matched charge. |
| `customers[].merchants[]` | object[] | {merchantId, mid (name), midNumber} of the account's MIDs they transacted on. |

**Errors**

- `400` merchantId is required; Invalid request (details: zod flatten); dateStart/dateEnd must be ISO dates (YYYY-MM-DD) or ISO datetimes; or dateStart must be <= dateEnd.
- `401` Missing X-Refund-Key or a scoped account API key (no credential, or a key without an owner and no X-Refund-Key); Invalid API key (the Authorization / X-Api-Key value matches no active key; no fallback); or Invalid refund key.
- `402` A paid platform subscription is required (code subscription_required, subscriptionStatus unpaid, billingPath /subscription): the target account has no paid or granted platform subscription.
- `403` Account suspended (the key owner is banned); API key scope denied (code insufficient_scope; customers.read missing); or clientId does not match the account this key belongs to.
- `404` Unknown merchant for this account (checked before the subscription).
- `429` Too Many Requests: this route has its own per-IP limit, RATE_LIMIT_REFUND (default 20 per minute).
- `503` Refund endpoint not configured (X-Refund-Key path only, the server has no partner secret).

**Gotchas**

- Only this account's blacklist entries are considered. A customer appears when an active entry matches a transaction of the scope by e-mail or by card (card matches need the card number on the transaction, so wallet charges only match by e-mail). A customer who never transacted in the scope is not listed.
- customerId is the same stable id the transaction endpoints return, which lets a CRM join this list to its transactions.

### Reports

The Reports menu, one subcategory per report page, the background report jobs, and the Reporting API (stable partner reports).

#### Dashboard metrics

GET /v1/metrics: the KPI payload of the Dashboard page, also the source of the Gateways report (perMid, perWallet, perWire, noGateway).

- `GET /v1/metrics` returns counts and money per row; the dashboard and the Gateways report derive their rates as described in Overview > Dashboard and Reports > Gateways. For a long range use `POST /v1/metrics/jobs` with `kind: "main"` and the same query.

##### `GET /v1/metrics`

**Scope** `reports.read` - **Dashboard metrics (with Straight / Subscription split and ad spend)**

The dashboard metrics payload, with the Straight / Subscription split (side) and ad spend; GET /v1/reports/gateways is the Reporting API's stable projection of the same computation. The whole-dashboard aggregate for a time window: totals + approval-rate splits, per-MID gateway performance, per-wallet finance, per-ATRI breakdown, top decline reasons, request outcomes, auth failures, global finance/refunds/chargebacks, store/traffic/brand/source breakdowns, and (optionally) a bucketed chart series. Returns the ChargeMetrics object at the TOP LEVEL - no wrapper key. v3.9.3: `split` - the Straight / Subscription halves of the dashboard cards (Gross, Net, Success, Declines, Approval rate, Refunds, Chargebacks, Fees), computed with the SAME window, tenant scope and ATRI view-filter as `totals` / `finance`, partitioned by the shared rebillSql classifier (Straight = NOT rebill, so the recovery sales sit inside Straight exactly as in `perSource`); `sources` - the /transactions `source` value each side's drill-down must send; `perStore[].straight_cents` - the straight half of a store's volume (a per-store Straight ROAS divides it, never `approvedCents`). v3.9.4: the read refreshes TODAY's Pilot spend first (60 s window per account, single-flight, 4 s budget - `pilot.refreshed_at` / `stale` / `refresh_reason`) and `finance.adSpendCents` carries the "Ad Spend Pilot" line (null = N/A). v3.9.9: the live refresh is handed the range's Pilot days (lib/pilotDays pilotDayRange - the days the read uses) and makes no Pilot call when they do not hold the report tz's today (nor yesterday before 06:00): a past range reads its closed days as stored (pilot.stale false). v3.9.9 (stats): every figure equals the /transactions list its dashboard link opens - refunds / chargebacks are the refund EVENTS (a successful non-test refunds row of a LIVE charge, dated by the refund, counted per transaction: the list's `refund=refund|chargeback`), the ATRI rows partition on the ATRI an order ENDED on (`atriFinal`), the store / traffic rows on the list's INHERITED dimensions (`storefront=` / `traffic=`), `noGateway` is the charges that ended on no gateway (`accountId=none`), the decline reasons count transactions and add up to the declines. v3.9.13 - the dashboard's Straight / Subscription / Both tab: the optional `side` (straight | subscription | both) splits the payload in two families. The CARD fields (`totals` apart from its two latency figures, `finance`, `refunds`, `chargebacks`, `split`, `sources`, `pilot`, `subs`, `series`, `perSource`, `requestOutcomes`, `authFailures`) are computed as without it, whatever the side - the Data cards never move with the tab. The BLOCK fields (`perAtri` with its p95 and cascaded counts, `perStore`, `perTrafficSource`, `perCardBrand`, `perWallet`, `perMid`, `noGateway`, `declineReasons`, `totals.avgLatencyMs` / `p95LatencyMs`) are the side's: Straight = the straight sales (sale + recovery, not rebillSql), Subscription = the subscription charges (rebillSql), Both = every charge. Four keys appear with it: `side`, `sideTotals`, `sideFinance`, `walletTraffic`. Without `side` the read is unchanged, byte for byte: no new key, the store straight only. Every `series[]` point gains `completed`, and `finance.transactionFeeCents` is read from the unfiltered attempt aggregate (see the field). Source breakdown: perSource includes Straight, Rebill and Friendlies base rows plus Recoveries (source: recovery) and Post-sells (source: upsell), each with subsetOf: straight. Subset rows already belong to Straight and can overlap each other; exclude rows with subsetOf when summing charges, volume and approval-rate denominators. Use source=recovery or source=upsell for the respective transaction drill-down. Existing range, tenant, live-transaction and selected filters apply equally. Wire payments are reported separately in perWire, with bank fees and refund events; they are excluded from Card and Wallet buckets.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `hours` | integer, 1..8760; default `24` | no | Trailing window in hours, used when `from` and `to` are not both sent. Non-integer or out of range is a 400. |
| `from` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Start of the range, inclusive: an ISO instant (any offset) or a YYYY-MM-DD day read in `tz`. Honoured only together with `to`; one bound alone is ignored and the trailing `hours` window applies. |
| `to` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | End of the range, inclusive (a day is its last millisecond in `tz`). Honoured only together with `from`. `to` before `from` is a 400 `to is before from`. |
| `bucket` | enum: hour \| day | no | Chart series granularity. Without it `series` is empty. Hourly bins advance in elapsed hours from local midnight, daily bins start at local midnight in tz; applies to ranges and trailing windows. Use bucketStart as the identity (labels may repeat at DST fall-back). |
| `tz` | string, max 64 (IANA timezone); default `account timezone` | no | Clock of the series buckets, the `hour` filter and calendar-day bounds. An unknown zone is a 400 `not a known IANA timezone`; an invalid stored account timezone is a 400 `Invalid report timezone`. |
| `atriView` | CSV of ATRI uuids, max 4000 | no | Whole-dashboard ATRI restriction: every KPI, breakdown, finance total and the chart series are limited to these trips (cascade-aware). Intersected with the caller's user_trips grants; empty/absent = all ATRIs the caller may see. An extra of this route (not a catalog key). |
| `side` | enum: straight \| subscription \| friendlies \| both | no | v3.9.13 - the dashboard's Straight / Subscription / Both tab. Read by this route only (GET /v1/metrics/products, /v1/metrics/series and /v1/metrics/alerts accept and ignore it; /v1/metrics/segments refuses it). `straight` = the straight sales (sale + recovery: not rebillSql, the list's `source=straight`), `subscription` = the subscription charges (rebillSql, `source=subscription`), `friendlies` = the Friendlies sales (source=friendlies; empty blocks when the account has no active Friendlies integration), `both` = every charge. The BLOCK fields follow it (perAtri incl. p95LatencyMs and the cascaded counts, perStore, perTrafficSource, perCardBrand, perWallet, perMid, noGateway, declineReasons, totals.avgLatencyMs / p95LatencyMs). They follow it through ONE clause on the charge, with no second run: a correlated EXISTS for the attempt tables, and in perMid's LEFT JOIN so every MID stays listed. The CARD fields never follow it. The payload gains `side`, `sideTotals`, `sideFinance` and `walletTraffic`. It composes with the dimension filters: a filter and a side read their intersection. Absent = the read without it, byte for byte. Any other value is a 400. Without `side` (or with side=both), a unified `source=friendlies` filter narrows the BLOCK fields to the Friendlies sales the same way. |
| `sections` | enum: gateways | no | Optional Payment projection. gateways returns only perMid, perWallet and noGateway with the same filters, scope, sides and live gateway fee calculations as the full report. Omitting it retains the complete dashboard payload. |
| `hour` | CSV of integers 0..23, max 200 | no | Filter catalog, Date: CSV of hours 00-23 in tz (needs tz). Needs a valid tz: an hour without one is a 400 `hour needs a valid tz`. |
| `status` | CSV enum | no | Filter catalog, Transaction: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `source` | CSV enum, max 100 | no | Filter catalog, Transaction: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. An unknown value is a 400 naming it. |
| `pass` | CSV enum, max 40 | no | Filter catalog, Transaction: initial / cascade. Allowed values: initial, cascade. An unknown value is a 400 naming it. |
| `method` | CSV enum, max 40 | no | Filter catalog, Transaction: card / wallet / wire. Allowed values: card, wallet, wire. An unknown value is a 400 naming it. |
| `population` | CSV enum, max 40 | no | Filter catalog, Transaction: live / test / imported (reports: live only). Allowed values: live, test, imported. An unknown value is a 400 naming it. |
| `credentialMode` | CSV enum, max 20 | no | Filter catalog, Transaction: Wire: mit / cit. Allowed values: mit, cit. An unknown value is a 400 naming it. |
| `threeDs` | CSV enum | no | Filter catalog, Transaction: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. An unknown value is a 400 naming it. |
| `declineCategory` | string, max 1000 | no | Filter catalog, Transaction: Decline-engine category. |
| `declineSeverity` | CSV enum, max 40 | no | Filter catalog, Transaction: soft / hard. Allowed values: soft, hard. An unknown value is a 400 naming it. |
| `amountMin` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount >= (cents). |
| `amountMax` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount <= (cents). |
| `currency` | CSV of 3-letter codes, max 200 | no | Filter catalog, Transaction: ISO-4217 currency. |
| `gatewayTxnId` | string, max 4000 | no | Filter catalog, Transaction: Gateway transaction id (exact, CSV). |
| `authCode` | string, max 1000 | no | Filter catalog, Transaction: Auth code of any attempt (exact, CSV). |
| `descriptor` | string, max 128 | no | Filter catalog, Transaction: Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum | no | Filter catalog, Transaction: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. An unknown value is a 400 naming it. |
| `product` | string, max 4000 | no | Filter catalog, Transaction: Basket product name / slug / ref. |
| `productSlug` | string, max 4000 | no | Filter catalog, Transaction: Basket product slug. |
| `productKey` | string, max 4000 | no | Filter catalog, Transaction: Product per store: <host>\|<ref>. |
| `accountId` | CSV of MID uuids, wallet:<uuid>, wire:<uuid> or none, max 4000 | no | Filter catalog, Routing: Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string, max 100 | no | Filter catalog, Routing: a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Any category of the final MID (ids). |
| `primaryCategory` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Primary category of the final MID (ids). |
| `atri` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI reached (ids). |
| `atriFinal` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI the order ended on (ids). |
| `processor` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Processor ids, none. |
| `acquiringBank` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Acquiring bank ids, none. |
| `company` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Company ids, none. |
| `gatewayMcc` | string, max 1000 | no | Filter catalog, Routing: Final MID MCC. |
| `gatewayBin` | string, max 1000 | no | Filter catalog, Routing: Final MID acquirer BIN. |
| `brand` | string, max 200 | no | Filter catalog, Card: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string, max 100 | no | Filter catalog, Card: APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string, max 200 | no | Filter catalog, Card: Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string, max 200 | no | Filter catalog, Card: bin_info card type (or a wallet). |
| `cardLevel` | string, max 4000 | no | Filter catalog, Card: bin_info card level (or a wallet). |
| `issuer` | string, max 4000 | no | Filter catalog, Card: Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay, max 4000 | no | Filter catalog, Card: CSV of 6-digit BINs or a wallet label. |
| `first6` | string of 1..6 digits | no | Filter catalog, Card: Card prefix (1-6 digits). |
| `last4` | string of 1..4 digits | no | Filter catalog, Card: Card suffix (1-4 digits). |
| `country` | string, max 2000 | no | Filter catalog, Customer: Billing country (ISO-2, inherited from the sale). |
| `storefront` | string, max 4000 | no | Filter catalog, Customer: Store host bucket, (direct). May include __no_store__ for canonical standalone orders (no store), which is not a blank-URL test. |
| `traffic` | string, max 2000 | no | Filter catalog, Customer: Traffic source, (direct/organic). |
| `utmSource` | string, max 4000 | no | Filter catalog, Customer: UTM source (case-insensitive). |
| `utmCampaign` | string, max 4000 | no | Filter catalog, Customer: UTM campaign (case-insensitive). |
| `device` | string, max 200 | no | Filter catalog, Customer: Mobile / Tablet / Desktop. |
| `os` | string, max 200 | no | Filter catalog, Customer: Operating system. |
| `browser` | string, max 200 | no | Filter catalog, Customer: Browser. |
| `ipType` | CSV enum, max 40 | no | Filter catalog, Customer: IPv4 / IPv6. Allowed values: IPv4, IPv6. An unknown value is a 400 naming it. |
| `ip` | string, max 2000 | no | Filter catalog, Customer: CSV of client IPs. |
| `email` | string, max 200 | no | Filter catalog, Customer: E-mail contains. |
| `phone` | string, max 40 | no | Filter catalog, Customer: Phone contains. |
| `firstName` | string, max 120 | no | Filter catalog, Customer: First name contains. |
| `lastName` | string, max 120 | no | Filter catalog, Customer: Last name contains. |
| `customerEmail` | CSV of e-mails, max 4000 | no | Filter catalog, Client: Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum, max 200 | no | Filter catalog, Client: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. An unknown value is a 400 naming it. |
| `clientBlacklisted` | enum | no | Filter catalog, Client: Blacklisted (e-mail or card). Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientLiveSub` | enum | no | Filter catalog, Client: Has a live (active / paused) subscription. Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientOrdersMin` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders >=. |
| `clientOrdersMax` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders <=. |
| `clientLtvMin` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value >= (cents). |
| `clientLtvMax` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value <= (cents). |
| `clientFirstFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen from. |
| `clientFirstTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen to. |
| `clientLastFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen from. |
| `clientLastTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen to. |
| `checkout` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped.. Derived from the immutable purchase session version, not the current store assignment; unknown or foreign flow ids are a 400 (`Unknown flow filter`). |
| `affiliate` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids.. Account-owned disabled affiliates stay valid for history; malformed, unknown or foreign ids are a 400 (`Invalid affiliate filter` / `Unknown affiliate filter`), never an unfiltered answer. |
| `subscription` | CSV of uuids, max 4000 | no | Filter catalog, Subscription: Subscription product ids. |
| `cycle` | CSV of integers 0..999, max 200 | no | Filter catalog, Subscription: Charge cycle (0 = the straight sale). |
| `cycleMin` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle >=. |
| `cycleMax` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle <=. |
| `engine` | CSV enum, max 60 | no | Filter catalog, Subscription: subscription / legacy / external. Allowed values: subscription, legacy, external. An unknown value is a 400 naming it. |
| `subStatus` | CSV enum | no | Filter catalog, Subscription: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. An unknown value is a 400 naming it. |
| `attachedBy` | CSV enum, max 60 | no | Filter catalog, Subscription: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. An unknown value is a 400 naming it. |
| `due` | enum | no | Filter catalog, Subscription: Next charge: overdue / 24h / 7d. Allowed values: overdue, 24h, 7d. An unknown value is a 400 naming it. |
| `endCause` | string, max 1000 | no | Filter catalog, Subscription: End cause. |
| `subCreatedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created from. |
| `subCreatedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created to. |
| `subEndedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended from. |
| `subEndedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended to. |
| `schedule` | CSV of uuids, max 4000 | no | Filter catalog, Schedule: Schedule (day) ids. |
| `scheduleStatus` | CSV enum | no | Filter catalog, Schedule: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. An unknown value is a 400 naming it. |
| `scheduleType` | CSV enum, max 60 | no | Filter catalog, Schedule: subscription / auto / manual. Allowed values: subscription, auto, manual. An unknown value is a 400 naming it. |
| `dayFrom` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum | no | Filter catalog, Schedule: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. An unknown value is a 400 naming it. |
| `entryReason` | string, max 4000 | no | Filter catalog, Schedule: Charge reason (decline reason of the entry). |
| `refund` | CSV enum, max 100 | no | Filter catalog, Refund: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `refundBasis` | enum | no | Filter catalog, Refund: Refund event dated by refund (default) / charge. Allowed values: refund, charge. An unknown value is a 400 naming it. |
| `refunded` | CSV enum, max 20 | no | Filter catalog, Refund: Refunded state flag. Allowed values: true, false. An unknown value is a 400 naming it. |
| `refundStatus` | CSV enum, max 80 | no | Filter catalog, Refund: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. An unknown value is a 400 naming it. |
| `refundTest` | enum | no | Filter catalog, Refund: Test refunds: exclude (= absent) / include / only. Allowed values: exclude, include, only. An unknown value is a 400 naming it. |
| `q` | string, max 200 | no | Filter catalog, Search: The page's identity search. Accepted by the strict catalog; identity search of list pages. |

**Response**

```json
{
  "windowHours": 24,
  "totals": {
    "total": 1842, "approved": 613, "declined": 1180, "error": 41, "unknown": 5,
    "pending": 3, "duplicate": 0, "blocked": 0, "completed": 1839, "approvalRate": 0.3333, "approvedCents": 4821900,
    "avgLatencyMs": 2140, "p95LatencyMs": 6100,
    "approvalRateExApplePay": 0.2981, "completedExApplePay": 1620, "approvedExApplePay": 483,
    "applePayApprovalRate": 0.8125, "applePayCompleted": 160, "applePayApproved": 130
  },
  "perMid": [
    { "id": "3f2b91c4-...", "name": "ALPHA-01", "activated": true,
      "charges": 420, "approved": 151, "declined": 260, "approvalRate": 0.3595,
      "approvalRateMidFixable": 0.4812, "midFixableDenom": 314,
      "attempts": 538, "arAttempts": 0.2806,
      "classicAttempts": 390, "arClassic": 0.3179,
      "cascadeAttempts": 148, "arCascade": 0.1824,
      "monthlyCapCents": 10000000, "usedCents": 3421900,
      "atris": ["Checkout US"],
      "processorId": "a1b2c3d4-0000-4000-8000-000000000001", "processorName": "PRIORITY",
      "acquiringBankId": "a1b2c3d4-0000-4000-8000-000000000002",
      "acquiringBankName": "SYNOVUS", "companyId": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35", "companyName": "STELLAR TIDE LLC",
      "sentCents": 1290400, "routedCents": 2041800,
      "grossCents": 512300, "discountFeeCents": 15369, "transactionFeeCents": 16140,
      "reserveCents": 25615, "refundCents": 8900, "refundCount": 2, "refundFeesCents": 500,
      "chargebackCents": 0, "chargebackCount": 0, "chargebackFeesCents": 0, "netCents": 445776 },
    "... one object per NMI MID in scope"
  ],
  "perWallet": [
    { "name": "Apple Pay", "processorId": "a1b2c3d4-0000-4000-8000-000000000003", "processorName": "CONVESIO PAY", "acquiringBankId": "a1b2c3d4-0000-4000-8000-000000000004", "acquiringBankName": "ADYEN", "companyId": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35", "companyName": "STELLAR TIDE LLC",
      "charges": 160, "approved": 130, "declined": 28, "approvalRate": 0.8125,
      "grossCents": 981200, "discountFeeCents": 29436, "transactionFeeCents": 3900,
      "reserveCents": 49060, "refundCents": 0, "refundCount": 0, "refundFeesCents": 0,
      "chargebackCents": 0, "chargebackCount": 0, "chargebackFeesCents": 0, "netCents": 898804 },
    "... 'Google Pay' / 'Wallet'"
  ],
  "declineReasons": [
    { "reason": "DECLINE", "count": 411, "byMid": [{ "name": "ALPHA-01", "count": 260 }, "..."] },
    "... top 10 reasons, desc"
  ],
  "requestOutcomes": [{ "outcome": "approved", "count": 613 }, "..."],
  "perAtri": [
    { "id": "9c1e...", "name": "Checkout US", "type": "classic", "total": 1500, "approved": 500,
      "declined": 960, "error": 38, "unknown": 2, "approvalRate": 0.3333,
      "approvedCents": 3910000, "p95LatencyMs": 5800 },
    "... cascade rows, plus a synthetic { id: '__no_atri__', name: 'Wallet / no ATRI' } row"
  ],
  "authFailures": [{ "id": "7a44...", "name": "BRAVO-02", "count": 12 }, "..."],
  "finance": {
    "grossCents": 4821900, "discountFeeCents": 144657, "transactionFeeCents": 61200,
    "reserveCents": 241095, "refundCents": 88000, "refundFeesCents": 2500,
    "chargebackCents": 24500, "chargebackFeesCents": 3500, "netCents": 4256448
  },
  "refunds": { "amountCents": 88000, "count": 14, "feesCents": 2500 },
  "chargebacks": { "amountCents": 24500, "count": 3, "feesCents": 3500 },
  "perStore": [
    { "name": "shop.example.com", "charges": 1200, "approved": 400, "declined": 770,
      "error": 28, "blocked": 0, "approvalRate": 0.3333, "approvedCents": 3120000 },
    "... top 50 by volume, then an aggregated '(other)' row when the cap bites"
  ],
  "perTrafficSource": ["... same MetricBreakdown shape, name '(direct/organic)' when empty"],
  "perCardBrand": ["... same shape, name Visa|Mastercard|Amex|Discover|Other (no cap)"],
  "perSource": ["... same shape, name 'Straight' | 'Rebill' | 'Friendlies', plus 'Recoveries' (source: recovery, subsetOf: straight) and 'Post-sells' (source: upsell, subsetOf: straight); subsets must not be added to totals"],
  "series": [
    { "label": "14:00", "total": 92, "approved": 31, "declined": 59, "completed": 90, "approvedCents": 241000 },
    "... empty unless bucket is sent"
  ],
  "side": "straight",
  "sideTotals": { "charges": 1310, "completed": 1308, "approved": 402, "declined": 870, "error": 30, "unknown": 6, "approvedCents": 3290100 },
  "sideFinance": { "grossCents": 3290100, "...": "finance's lines for the side", "netCents": 2904412, "adSpendCents": null },
  "walletTraffic": true
}
```

| response field | type | description |
|---|---|---|
| `windowHours` | number | Size of the analysed window in hours. On the from/to path it is RECOMPUTED as max(1, round((to-from)/3600000)), not the `hours` you sent. |
| `totals.total` | number | All LIVE transactions in the window (v3.9 section 1: no test card, no CSV import, no 3DS park). A charge cocoapi refused before any MID is not a transaction any more (charge_rejections), so it is in no figure. |
| `totals.approved` | number | Count of status='approved'. |
| `totals.declined` | number | v3.9 section 1 - the MID verdicts: the declines (status 'declined' or 'error', TXN_DECLINED_SQL) that are not technical errors. totals.declined + totals.error = every decline of the window. |
| `totals.error` | number | Technical errors (status 'error': gateway 5xx / timeout / no eligible account / adapter exception) - the other half of the v3.9 section 1 declines. |
| `totals.unknown` | number | Ambiguous timeouts needing manual review (no auto-failover happened). |
| `totals.pending` | number | Count of status='pending'. |
| `totals.duplicate` | number | Count of status='duplicate'. |
| `totals.completed` | number | v3.9 section 1 - the approval rate's base (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). Read it instead of re-summing the buckets: it is what every approvalRate divides by. |
| `totals.blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `totals.approvalRate` | number (ratio 0..1) | approved / totals.completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). 0 when the base is 0. Multiply by 100 for a percentage. |
| `totals.approvedCents` | integer cents | Sum of amount_cents over successful transactions. |
| `totals.avgLatencyMs` | number | Mean transaction_attempts.latency_ms over the window (integer ms). v3.9.13 - with `side` = straight / subscription: the side's attempts only. With p95LatencyMs, the only `totals` fields that follow the side (no card reads them). |
| `totals.p95LatencyMs` | number | 95th percentile attempt latency in ms (percentile_disc). v3.9.13 - follows `side` like avgLatencyMs (the dashboard's "NMI latency p95" row under the tab). |
| `totals.approvalRateExApplePay` | number (ratio 0..1) | Card/NMI-only AR - excludes crm='convesio' wallet traffic, which approves far higher and inflates the global rate. |
| `totals.completedExApplePay` | number | Completed non-wallet transactions (denominator of approvalRateExApplePay). |
| `totals.approvedExApplePay` | number | Approved non-wallet transactions. |
| `totals.applePayApprovalRate` | number (ratio 0..1) | Wallet-only AR (crm='convesio' - covers Apple Pay AND Google Pay). |
| `totals.applePayCompleted` | number | Completed wallet transactions. |
| `totals.applePayApproved` | number | Approved wallet transactions. |
| `perMid[].id` | string (uuid) | nmi_accounts.id of the MID. |
| `perMid[].name` | string | MID display name. |
| `perMid[].activated` | boolean | Whether the MID is currently activated for routing. |
| `perMid[].charges` | number | LIVE transactions whose final_account_id is this MID (orders that ENDED here - v3.9 section 1: no test card, no CSV import, no 3DS park), all statuses; not attempts. |
| `perMid[].approved` | number | Successful transactions that ended on this MID. |
| `perMid[].declined` | number | v3.9 section 1 declines that ended on this MID: MID verdicts AND technical errors (status 'declined' or 'error') - there is no separate error column on this row. |
| `perMid[].completed` | number | v3.9 section 1 - the approval rate's base of the row: LIVE orders that ENDED on this MID with status approved, declined, error or unknown (pending and duplicate are out). approvalRate = approved / completed, so a Total / grouped row recomputes sum of approved / sum of completed on it - never approved / charges (charges also counts pending rows). |
| `perMid[].approvalRate` | number (ratio 0..1) | approved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out; orders that ENDED on the MID), final_account-based, so it UNDERCOUNTS the MID's real work (a declined attempt later approved elsewhere is credited to the other MID). |
| `perMid[].approvalRateMidFixable` | number (ratio 0..1) | The 'real' MID AR: approved attempts / (approved + WINNABLE declines). Unwinnable cardholder declines (NSF, pick-up, expired) are removed from the denominator. v3.9 section 1: a timeout is a technical error, so timed-out attempts sit in the winnable denominator next to declined / error ones (ATTEMPT_DECLINED_SQL), and only attempts of LIVE transactions count. |
| `perMid[].midFixableDenom` | number | Sample size behind approvalRateMidFixable. Treat a small value as statistically meaningless. |
| `perMid[].attempts` | number | Non-skipped transaction_attempts on this MID in the window. |
| `perMid[].arAttempts` | number (ratio 0..1) | Approved attempts / all attempts - the true gateway performance. |
| `perMid[].classicAttempts` | number | Attempts on the first (classic) pass. |
| `perMid[].arClassic` | number (ratio 0..1) | AR on first-attempt (classic) traffic. |
| `perMid[].cascadeAttempts` | number | Attempts on failover (cascade) traffic - cards already declined elsewhere. |
| `perMid[].arCascade` | number (ratio 0..1) | AR on cascade traffic; structurally lower than arClassic. |
| `perMid[].monthlyCapCents` | integer cents | Configured monthly processing cap. |
| `perMid[].usedCents` | integer cents | Cap usage for the CURRENT billing period (account_usage), independent of the requested window. v3.9.13 - a MID attribute: the same value under every `side` (like monthlyCapCents and atris). |
| `perMid[].atris` | string[] | Names (not ids) of the ATRIs this MID belongs to, sorted. [] when none. |
| `perMid[].atriRefs` | object[] | Current ATRI memberships as { id: UUID, name: string } for unambiguous item references. Not window-scoped. Empty when the MID has no ATRI membership. The legacy atris name array remains unchanged; never resolve an ID by its name. |
| `perMid[].processorId` | string (uuid) \| null | v3.9 section 0 - the MID's processor (nmi_accounts.processor_id -> processors.id); null when the gateway has none set. |
| `perMid[].processorName` | string \| null | processors.name of processorId, as stored (UPPERCASE, e.g. 'PRIORITY'); null with it. Group the rows on it for a per-processor view. |
| `perMid[].acquiringBankId` | string (uuid) \| null | v3.9 section 0 - the MID's acquiring bank (nmi_accounts.acquiring_bank_id -> acquiring_banks.id); null when unset. |
| `perMid[].acquiringBankName` | string \| null | acquiring_banks.name of acquiringBankId (e.g. 'SYNOVUS'); null with it. |
| `perMid[].companyId` | string (uuid) \| null | v3.9.2 section 0 - the MID's company (nmi_accounts.company_id -> companies.id: the legal entity it is boarded under); null when unset. |
| `perMid[].companyName` | string \| null | companies.name of companyId (e.g. 'STELLAR TIDE LLC'); null with it. |
| `perMid[].sentCents` | integer cents | Volume of ALL orders that ended on this MID (approved or not), from final_account_id. |
| `perMid[].routedCents` | integer cents | Volume this MID actually ATTEMPTED. Summing across MIDs deliberately EXCEEDS total volume - a cascaded order is routed to every MID that tried it. |
| `perMid[].grossCents` | integer cents | Approved volume that ended on this MID. |
| `perMid[].discountFeeCents` | integer cents | Discount (%) fee on approved captures - v3.9.6 live fees: the MID's CURRENT discount_fee_bps x each approved amount, computed at read time (never the row's snapshot), so a rate edit re-prices every past capture. |
| `perMid[].transactionFeeCents` | integer cents | attempts x the MID's configured flat transaction_fee_cents - billed per authorization, INCLUDING declined ones (already live before v3.9.6: the MID's current fee). |
| `perMid[].reserveCents` | integer cents | Rolling-reserve amount held on approved captures - v3.9.6 live fees: the MID's CURRENT reserve_rate_bps x each approved amount, at read time. |
| `perMid[].refundCents` | integer cents | Successful refunds (is_chargeback = false) attributed to this MID. |
| `perMid[].refundCount` | number | Number of successful non-chargeback refund rows. |
| `perMid[].refundFeesCents` | integer cents | Fees on those refunds - v3.9.6 live fees: each successful refund priced at the MID's CURRENT per-brand fee (Mastercard -> mc_refund_fee_cents, Visa -> visa_refund_fee_cents, other networks 0) at read time. |
| `perMid[].chargebackCents` | integer cents | Refund rows reclassified as chargebacks (refunds.is_chargeback). |
| `perMid[].chargebackCount` | number | Number of chargeback-marked refund rows. |
| `perMid[].chargebackFeesCents` | integer cents | Fees on chargeback-marked rows. |
| `perMid[].netCents` | integer cents | gross - (discount + reserve + transactionFee + threeDsFee) - refunds - refundFees - chargebacks - chargebackFees. Can be negative. v3.9.6 live fees: every term at the MID's / integration's CURRENT rates. |
| `perWallet[].name` | string | 'Apple Pay' \| 'Google Pay' \| 'Wallet' (bucketed from raw_payload->>'paySource'). |
| `perWallet[].processorId / processorName / acquiringBankId / acquiringBankName` | string \| null (each) | v3.9 section 0 - the wallet provider's processor / acquiring bank (wallet_providers.processor_id / acquiring_bank_id, the same reference tables as perMid). All four null on the '(unattributed)' row and when the provider has none set. |
| `perWallet[].companyId / companyName` | string \| null (each) | v3.9.2 section 0 - the wallet provider's company (wallet_providers.company_id, the same reference table as perMid). Both null on the '(unattributed)' row and when the provider has none set. |
| `perWallet[].completed` | number | v3.9 section 1 - the approval rate's base of the wallet row (live and completed charges: status approved, declined, error or unknown); approvalRate = approved / completed, and a Total / grouped row recomputes sum of approved / sum of completed on it. |
| `perWallet[].approvalRate` | number (ratio 0..1) | approved / completed for wallet traffic (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out) - the same base as totals.approvalRate since v3.9 section 1. |
| `perWallet[].netCents` | integer cents | gross - discount - transaction - reserve - 3DS fees, every term at the wallet provider's CURRENT schedule (v3.9.6 live fees: wallet_providers.discount_fee_bps / reserve_rate_bps x the approved amount, ONE transaction_fee_cents per completed wallet charge - wallet rows carried 0 in every fee column before) - refunds - refund fees - chargebacks - chargeback fees (the row's wallet refunds / chargebacks at the provider's CURRENT per-brand fee, the same figure finance carries - hard-coded to 0 before v3.9.6). Can be negative. |
| `declineReasons[].reason` | string | response_text, else decline_reason, else '(no reason)'. Top 10 by count. v3.9.8 item 1 - plus the WALLET declines (a wallet charge has no attempts row): the transaction's own decline reason, its MID named '<wallet> - <wallet provider>' (e.g. 'Apple Pay - MY STORE CONVESIO/ADYEN'). |
| `declineReasons[].count` | number | Attempts with outcome in (declined, error, timeout) - ATTEMPT_DECLINED_SQL - carrying this reason, on LIVE transactions only (v3.9 section 1: an attempt of a test-card / imported / parked row never counts). |
| `declineReasons[].byMid` | array | Per-MID split: { name, count }, desc. name is '(unknown MID)' when the attempt has no account_name. v3.9.8 item 1 - a wallet decline's name is '<Apple Pay \| Google Pay> - <wallet provider>' ('(unattributed)' without a provider). |
| `requestOutcomes[]` | array of { outcome: string, count: number } | Outcomes from charge_request_logs (request level, before routing). Scoped by api_key ONLY - no wallet and no ATRI filtering - so it will NOT reconcile with totals. v3.9.13 - charge_request_logs has no side (no source, channel or transaction column), so it is unsided whatever `side`. The dashboard reads "-" on these rows under Straight / Subscription. |
| `perAtri[].id` | string (uuid) or '__no_atri__' | Trip id, or the synthetic '__no_atri__' bucket (wallet / no trip) appended so the breakdown sums to the global totals. |
| `perAtri[].type` | string | enum: classic\|cascade. The synthetic no-ATRI row is reported as 'classic'. |
| `perAtri[].total` | number | Classic: completed orders routed to the ATRI. Cascade: DISTINCT orders that reached it (not attempt rows). |
| `perAtri[].approvalRate` | number (ratio 0..1) | approved / total (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). |
| `perAtri[].approvedCents` | integer cents | Approved volume on the ATRI. |
| `perAtri[].p95LatencyMs` | number | 95th percentile attempt latency for the ATRI; 0 for the '__no_atri__' row. |
| `authFailures[]` | array of { id, name, count } | MIDs whose attempts failed GATEWAY AUTHENTICATION (bad login/password/security key) - a credentials/config bug, not a normal decline. Fix these first. |
| `finance.grossCents` | integer cents | Same value as totals.approvedCents. |
| `finance.discountFeeCents` | integer cents | Discount fees over approved transactions in the window - v3.9.6 live fees: each approved row x its gateway's CURRENT discount_fee_bps (the MID's, else the wallet provider's), computed at read time; a rate edit re-prices the whole range. |
| `finance.transactionFeeCents` | integer cents | Per-ATTEMPT fees: every non-skipped attempt of a live transaction on a MID the account owns, at the attempting MID's flat transaction_fee_cents, failed authorizations included. Since v3.9.6, plus the wallet providers' flat fee, ONE per completed wallet charge (wallet_providers.transaction_fee_cents - a wallet has no attempts row). v3.9.13 - read from the UNFILTERED, UNSIDED attempt aggregate (the `split` statement's attempts, straight + subscription), no longer sum of perMid[].transactionFeeCents: perMid follows the dimension filters, `pass` and `side`, and no other finance line does. On a read with no filter, no pass and no side the value is unchanged (checked to the cent on production). Under a filter or pass=initial it is now the window's whole fee, like the rest of the ledger. Before, the filtered attempt fees were mixed into the unfiltered ledger; finance.netCents and pilot.net_blended_roas move with it. |
| `finance.reserveCents` | integer cents | Reserve held over approved transactions - v3.9.6 live fees: each approved row x its gateway's CURRENT reserve_rate_bps. |
| `finance.refundCents / refundFeesCents` | integer cents | Successful refunds NOT marked as chargebacks, plus their fees - v3.9.6 live fees: each refund priced at the charge's gateway CURRENT per-brand fee (the MID's, else the wallet provider's; Mastercard / Visa columns, other networks 0). |
| `finance.chargebackCents / chargebackFeesCents` | integer cents | Refunds reclassified via 'Mark CB' (refunds.is_chargeback), plus their fees (the same live per-brand fee as a refund). Marking moves money between buckets; netCents is unchanged. |
| `finance.netCents` | integer cents | gross - discount - reserve - transactionFees - threeDsFees - refunds - refundFees - chargebacks - chargebackFees. Can be negative. v3.9.6 live fees: 'fees at today's gateway rates' - nothing here is stored, so the net of any past range changes when a fee setting changes. |
| `finance.adSpendCents` | integer \| null | v3.9.4 - the "Ad Spend Pilot" line of the finance breakdown (a line generated by the Pilot integration, GeneratedBy pilot): `pilot.spend_cents` (the range's TikTok ad spend from Pilot, the campaigns targeted 'ignored' excluded) when the Pilot integration is active AND the range holds synced Pilot days (`pilot.reason` null - a synced $0 is a real 0); null = N/A, the reason in `pilot.reason` ('Pilot is not configured', 'not synced yet', 'no Pilot data in this range'...). It is NOT subtracted from netCents: "Net after ad spend" = netCents - adSpendCents is computed on the dashboard side, only when adSpendCents is not null. Placed after the fees on the dashboard's finance panel. |
| `refunds` | { amountCents: integer cents, count: number, feesCents: integer cents } | Successful refund rows EXCLUDING chargeback-marked ones. |
| `chargebacks` | { amountCents: integer cents, count: number, feesCents: integer cents } | Only the chargeback-marked refund rows. |
| `perStore[]` | MetricBreakdown[] | By storefront HOST ('(direct)' when missing). Fields: name, charges, approved, declined, error, approvalRate (0..1), approvedCents. Capped at 50 + an '(other)' remainder row. v3.9.10 - without `side` the rows count the STRAIGHT sales only (sale + recovery; approvedCents = straight_cents) and the '(other)' remainder closes on perSource's Straight row. v3.9.13 - with `side`: `straight` = those same rows; `subscription` = the subscription charges' rows (rebillSql); `both` = every charge's rows (straight + subscription). The Subscription and Both rows cost ONE more statement; the Pilot attribution keeps reading the straight rows. Under a side the '(other)' remainder closes on `sideTotals`. |
| `perTrafficSource[]` | MetricBreakdown[] | By traffic_source ('(direct/organic)' when empty). Same shape and same 50 + '(other)' cap. v3.9.13 - follows `side` (the side's charges). Under a side the '(other)' remainder closes on `sideTotals` (= the window's counts under both); without it, on the window's totals. |
| `perCardBrand[]` | MetricBreakdown[] | v3.9.8 item 1 - by the brand DIMENSION (METHOD_CASE, the `brand` filter of each row's link): Visa \| Mastercard \| Amex \| Discover, Apple Pay \| Google Pay for the wallet charges (the wallet wins over the network behind it), Other for a card with no recognised network. No cap, no '(other)' row. |
| `perSource[]` | MetricBreakdown[] | Source breakdown: perSource includes Straight, Rebill and Friendlies base rows plus Recoveries (source: recovery) and Post-sells (source: upsell), each with subsetOf: straight. Subset rows already belong to Straight and can overlap each other; exclude rows with subsetOf when summing charges, volume and approval-rate denominators. Use source=recovery or source=upsell for the respective transaction drill-down. Existing range, tenant, live-transaction and selected filters apply equally. The perSource response remains unsided; consumers may display the rows appropriate to their selected tab. |
| `series[]` | array of { label, bucketStart, total, approved, declined, completed, approvedCents } | Chronological chart buckets when bucket is supplied, including trailing-hours windows. label is HH24:MI (hour) or MM-DD (day) in tz; bucketStart is the unique ISO UTC instant. DST days can have 23 or 25 hourly buckets. total counts live transactions, declined includes declined/error, and approvedCents is integer cents. A CARD field, never sided: the dashboard uses /v1/metrics/series?source= for Straight/Subscription. |
| `perWallet[].declined` | number | v3.9 section 1 declines on the row (status 'declined' or 'error' - technical errors folded in). |
| `perStore[].blocked / perTrafficSource[].blocked / perCardBrand[].blocked / perSource[].blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `split` | object | {straight: SIDE, subscription: SIDE} with SIDE = {gross_cents, net_cents, approved, declined, approval_rate, refunds: {n, cents}, chargebacks: {n, cents}, fees_cents}. Invariant: straight.x + subscription.x = the global figure of every field (gross = finance.grossCents, net = finance.netCents, approved = totals.approved, declined = totals.declined + totals.error, refunds / chargebacks = the `refunds` / `chargebacks` blocks, fees = discount + reserve + transaction fees). v3.9.13 - a CARD field: unsided whatever `side`. The tab's Finance ledger is `sideFinance`. |
| `split.straight.gross_cents` | integer | Approved volume of the straight sales (cents) - the Gross volume card's straight half. |
| `split.straight.net_cents` | integer | gross - fees_cents - 3DS fees (the charges' and the rejections') - refunds - refund fees - chargebacks - chargeback fees - the Net volume card's straight half. |
| `split.straight.approved` | integer | Success (status approved) on the straight side. |
| `split.straight.declined` | integer | The Declines card's straight half: MID verdicts AND technical errors (status declined or error) - i.e. perSource Straight `declined + error`. |
| `split.straight.approval_rate` | number \| null | approved / completed (the APPROVAL_BASE, like every approval rate); null when approved + declined = 0 - render a dash, never 0 %. |
| `split.straight.refunds` | object | {n, cents, fees_cents} - successful refunds not reclassified as chargebacks, dated by the REFUND, whose transaction is a straight sale; v3.9.3 review: fees_cents = the side's refund fees (sum of sides = finance.refundFeesCents), so a half of the Refunds card can show amount + fees. |
| `split.straight.chargebacks` | object | {n, cents, fees_cents} - successful refunds marked as chargebacks, same attribution; v3.9.3 review: fees_cents = the side's chargeback fees (sum of sides = finance.chargebackFeesCents). The Chargebacks card renders chargebackCents + chargebackFeesCents, so its Straight / Subscription halves are cents + fees_cents. |
| `split.straight.fees_cents` | integer | discount + reserve + per-attempt transaction fees (+ the wallet providers' per-charge fee, v3.9.6) of the straight side - the Fees card's formula (3DS fees are deducted in net_cents only, as on the card); every term at the gateways' CURRENT rates (v3.9.6 live fees). |
| `split.subscription` | object | The same SIDE for the subscription charges (rebillSql: channel rebill% / legacy, or a rebill-named ATRI for an unknown channel). |
| `sources` | object | {straight: 'sale,recovery', subscription: 'rebill'} - the `source` filter value a side's drill-down sends to GET /v1/transactions (and the CSV export / id list). A Straight link sending 'sale' alone opens FEWER rows than the number clicked: the recovery sales (a straight sale attributed to an abandoned-cart relance) are a separate bucket of the `source` filter. |
| `perStore[].straight_cents` | integer | v3.9.3 - the approved volume of the store's STRAIGHT charges (cents); `approvedCents` was straight + subscription until v3.9.10. The `(other)` remainder row carries the straight gross minus the listed rows'. v3.9.10 - the rows are straight only without `side`, so there straight_cents = approvedCents. v3.9.13 - under side=both, the row's straight half (approvedCents = straight + subscription; the Straight ROAS numerator); under side=subscription, 0. |
| `pilot` | object | v3.9.3 Pilot - the Pilot Spend / Straight ROAS / Blended ROAS cards: { active: boolean (the Pilot integration is enabled AND its API key saved), reason: string \| null (why a dash is shown - 'Pilot is not configured' / 'Pilot is switched off' / 'Pilot API key missing' / 'no account' while inactive; 'not synced yet' / 'Pilot data starts YYYY-MM-DD' / 'Pilot data ends YYYY-MM-DD' / 'no Pilot data in this range' when active but nothing synced for the range; null when the figures are real), spend_cents: integer (sum of the synced Pilot days whose key falls in the range's calendar days in `tz`, the campaigns targeted 'ignored' excluded), straight_roas: number \| null (split.straight.gross_cents / spend_cents, 4 decimals; null when spend_cents = 0 or inactive), blended_roas: number \| null ((split.straight.gross_cents + split.subscription.gross_cents) / spend_cents; same null rule), synced_through: 'YYYY-MM-DD' \| null (the account's latest synced Pilot day, any range), days_missing: integer (calendar days of the range, up to today, without a synced total row), ignored_cents: integer, unattributed_cents: integer (spend of campaigns with no effective target, plus the spend of a named campaign its destination URLs do not cover - in spend_cents, on no Store / Product row), unmatched_cents: integer (v3.9.3 review: attributed spend whose host has NO Store row in the range - spend_cents - store_spend_cents = unattributed_cents + unmatched_cents, within Pilot's rounding between its campaign and destination breakdowns), store_spend_cents: integer (sum of perStore[].pilot_spend_cents - the Store table's spend total), timezone: string (the tz the days were cut in; 'UTC' when `tz` is absent / invalid) }. Read from pilot_spend_daily (jobs/pilotSpendSync.ts) in ONE statement; no statement runs while inactive; a failed side-table read (a timeout, migration 163 rolled back under a live process) degrades to { active: true, reason: 'Pilot read failed: <code>' } with the zeros / nulls - never a 500 for the cards. A Pilot day is a day in the PILOT profile's timezone (America/New_York by default): when it differs from `tz` the day skew is a documented deviation. v3.9.4 - the live refresh (docs/PILOT.md section 3.1): the read re-reads TODAY (+ yesterday before 06:00 in the report tz) from Pilot's /api/live-report/day BEFORE the side tables are read - at most once per 60 s per account (the stored synced_at of today's total rows is the clock, shared by every instance), one refresh in flight per account, a 4 s budget past which the stored numbers are served and the refresh completes in the background; never a failure of the read. Three more fields: refreshed_at: ISO \| null (the account's last live read of today / yesterday - the stored synced_at; null before the first, or while inactive), stale: boolean (this call did NOT refresh within the window: the budget passed, a Pilot error, a sync pass on the account - or no refresh was run; false while inactive: nothing to refresh), refresh_reason: string \| null ('Pilot did not answer within 4000 ms - refreshing in the background' \| 'UNAUTHENTICATED (401)' and the other typed Pilot codes \| 'a sync pass is on the account' \| the migration-163 sentence; null when refreshed or already fresh). `reason` keeps answering "why N/A"; `stale` answers "were these figures refreshed from Pilot just now". v3.9.9 - + net_straight_roas: number \| null (the Net volume card's straight half / spend: split.straight.net_cents / spend_cents, the net = gross - discount / transaction / 3DS fees - reserve - refunds - refund fees - chargebacks - chargeback fees at today's gateway rates) and net_blended_roas: number \| null (the Net volume card / spend: finance.netCents / spend_cents); each null exactly when its gross twin is, may be negative (a net loss). |
| `perStore[].pilot_spend_cents` | integer \| null | v3.9.3 Pilot - the Pilot spend attributed to the store, at DESTINATION granularity first (D4, v3.9.3 review): sum of Pilot's per-landing-URL spend (the `destination` rows of pilot_spend_daily) whose host is this store, plus the campaigns no landing URL names (URL-less ads) whose effective target (manual > auto) is this host or a product URL on it; a manual override on a campaign the landing URLs DO name takes its share back from them pro rata. Matched exactly on the host first, then by registrable host (pay.shop.com / www.shop.com are the shop's aliases; the row with the most straight volume wins when several share it). null when the integration is inactive, the host is unmapped, the spend is 0 (both tables agree: a dash, never $0), and always on '(direct)' / '(other)'. v3.9.4 - Pilot's real byProduct keys are `host::slug` (the landing URL rides in the stored name): the destination identity is the stored landing URL (docs/PILOT.md section 4.1), so the destination rows now reach the Store rows (they matched nothing before - 0 % coverage in production, fixed and verified read-only by api/scripts/pilot-attribution-check.ts, docs/PILOT.md section 12). v3.9.13 - with `side`: `straight` = as without it; `both` = the spend of the row's host from the straight attribution, joined by name (the spend is attributed ONCE, on the straight rows); `subscription` = null on every row (Pilot has no side: the ad spend buys the first sale). |
| `perStore[].straight_roas` | number \| null | v3.9.3 Pilot - straight_cents / pilot_spend_cents (4 decimals); null when pilot_spend_cents is null / 0 (render a dash, never infinity). A Total row recomputes sum of straight_cents of the MATCHED rows / sum of pilot_spend_cents on the dashboard side. v3.9.13 - under side=both, the row's straight_cents / pilot_spend_cents; null on every row under side=subscription. |
| `finance.threeDsFeeChargesCents` | number | v3.9.9 - the 3DS fees of the window's live CHARGES (the rows `threeDs=applied,attempted` opens carry them). threeDsFeeCents = threeDsFeeChargesCents + threeDsFeeRejectionsCents. |
| `finance.threeDsFeeRejectionsCents` | number | v3.9.9 - the 3DS fees of the authentications that never became a charge (3DS rejections: policy refusals, abandoned parks) - no transaction row. |
| `noGateway` | object \| null | v3.9.9 - the per-gateway report's "(no gateway)" row: the finance shape of a perWallet row (charges, approved, declined, completed, approvalRate, grossCents, the fee lines, refundCents / refundCount / refundFeesCents, chargebackCents / chargebackCount / chargebackFeesCents, threeDsFeeCents, netCents) for the charges with no final MID and no wallet provider (NO_GATEWAY_SQL - the list's `accountId=none`), the refunds of such charges, and - when no dimension filter is applied - the rejections' 3DS fees (`threeDsRejectionFeeCents`). perMid + perWallet + noGateway = the cards. null when empty. v3.9.11 - under a SOURCE-ONLY filter (straight / subscription alone) `threeDsRejectionFeeCents` is that side's rejections' 3DS fees (their own channel); under any other filter 0. v3.9.13 - with `side` = straight / subscription: the side's no-gateway charges and their refunds. threeDsRejectionFeeCents = the side's rejections (their own channel), intersected with a Source-only filter when both apply. |
| `perWallet[]` | array | v3.9.9 - the charges that ended on a wallet PROVIDER with no MID (walletProvider=<id>); a provider whose refunds / chargebacks fall in the window with no charge of its own there has a row too (charges 0). |
| `perAtri[].charges` | number | v3.9.9 - every live order that ENDED on the ATRI (db/txFilters ATRI_FINAL_SQL: the cascade pool of its first non-skipped cascade-pass attempt, else its own ATRI; dated by the order) - the list's `atriFinal=<id>`. `total` stays the completed ones (the approval rate's base); `cascaded` (classic rows) = the list's `atri=<id>&pass=cascade&status=completed`. v3.9.13 - follows `side`, like every perAtri figure (total, approved, p95LatencyMs, cascaded). |
| `perStore[].completed` | number | v3.9.9 - every breakdown row (perStore, perTrafficSource, perCardBrand, perSource) carries its approval-rate base, so a Total recomputes sum of approved / sum of completed. perStore / perTrafficSource group on the list's inherited STOREFRONT_EXPR / TRAFFIC_EXPR (a subscription charge reads its originating sale's). |
| `declineReasons[].other` | boolean (optional) | v3.9.9 - the decline reasons are counted per TRANSACTION (the final reason of every decline of the window, on the gateway it ended on - a MID, "<wallet> - <provider>" or "(no gateway)"): the top 10, then ONE `other: true` row with the rest, so sum of count = totals.declined + totals.error. |
| `split.straight.completed` | number | v3.9.9 - the side's approval-rate base (split.subscription.completed likewise). The refunds / chargebacks halves follow D1 (refund events of live charges, per transaction). |
| `side` | 'straight' \| 'subscription' \| 'both' (only with `side`) | v3.9.13 - the side the BLOCK fields were computed for (the param, echoed). Absent when the request carried no `side`, like `sideTotals`, `sideFinance` and `walletTraffic`: a read without the param (the alerts, the partner report, Reports -> Payment) gains no key. |
| `sideTotals` | { charges, completed, approved, declined, error, unknown, approvedCents } (only with `side`) | v3.9.13 - the side's counts, from the order-source statement's Straight / Rebill row (the row perSource and `split` read; `both` = the two rows summed = the window's counts). `declined` = the MID verdicts and `error` = the technical errors (declined + error = the side's declines, as in `totals`). `unknown` = the ambiguous timeouts (the "Timeouts (review)" row of the Request outcomes block under the tab). `completed` = the approval rate's base. `approvedCents` = the side's gross. The side's perStore / perTrafficSource '(other)' remainders close on it. |
| `sideFinance` | object - `finance`'s shape (only with `side`) | v3.9.13 - the Finance ledger of the side, line by line: grossCents, discountFeeCents, transactionFeeCents (the side's per-attempt fees + its wallet charges' flat fee), reserveCents, refundCents / refundFeesCents and chargebackCents / chargebackFeesCents (the refund events of the side's charges), threeDsFeeCents = threeDsFeeChargesCents (the side's charges) + threeDsFeeRejectionsCents (the side's 3DS rejections, by the rejection's own channel: rebillChannelSql), netCents, adSpendCents. Built from the same rows as `split`: sideFinance(straight) + sideFinance(subscription) = `finance` to the cent, and sideFinance.netCents = split[side].net_cents. `adSpendCents` is null on straight / subscription (Pilot spend has no side - Reports -> Financial's rule) and finance.adSpendCents under both. Under both, every line equals `finance`. |
| `walletTraffic` | boolean (only with `side`) | v3.9.13 - true when the window holds at least one wallet charge (a live charge that ended on a wallet provider and no MID - perWallet's population) on EITHER side. Unsided, so the dashboard shows the Wallet block on every tab while it is true; a side with no wallet charge shows the block's empty state. |
| `series[].completed` | number | v3.9.13 - the bucket's approval-rate base (TXN_COMPLETED_SQL: status approved, declined, error or unknown - the cards' base). The chart's approval and its vs-yesterday row read sum of approved / sum of completed on every tab (the filtered chart read approved / (approved + declined) before). Present with or without `side`; the partner /v1/reports/gateways projects it out. |
| `friendlies.netCostCents` | integer\|null | Present while Friendlies is active: USD cost per recorded attempt plus approved discount and reserve. Null when any cost is missing or fees require currency conversion. |
| `subs.activeSubs` | integer | Currently active account subscriptions across all creation dates. This is a current inventory count, not a historical end-of-period snapshot and not limited by the selected from/to range. Paused, failed and cancelled subscriptions are excluded. |
| `finance.affiliateCuts` | array<{currency:string,amountMinor:string}> | Event-dated append-only cut totals, separated by ISO currency; integer minor units serialized as strings. |
| `finance.affiliateCutCents` | integer \| null | Comparable deduction in minor units, including negative reversal periods. Null when currencies cannot be combined. |
| `finance.netUnavailableReason` | string \| null | Explains nullable net when no FX conversion is configured or source figures are unavailable. |
| `topAffiliates` | array | Feature-gated top ten per revenue currency for the selected period and filters: id, name, publicId, currency, orders, revenueMinor and cuts. Initial plus captured upsell revenue; recurring rebills excluded. |
| `perSource[].source` | string (optional) | recovery or upsell on qualified subset rows; use as the /v1/transactions source filter. |
| `perSource[].subsetOf` | string (optional) | straight on Recoveries and Post-sells. These are informational subsets, not additional accounting rows. Omitted on base sources. |
| `series[].bucketStart` | string (date-time) | ISO UTC start instant of the bucket. Unique chronological identity, including repeated local hours at DST fall-back. Older cached payloads may omit it. |
| `perWire` | object[] | Bank-account payment metrics, including amount, approvals, fees and refund events. Uses the same applied scope as perMid and perWallet; source drill-downs use wire:<id>. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: an unknown query parameter (the catalog is strict), an unknown value of a closed vocabulary, hours outside 1..8760, a malformed from / to, bucket not hour | day, side or sections outside their values, `hour` without a valid tz, a reversed range pair (for example `to is before from`), a value over its max length; `Invalid report timezone` when the account's stored timezone is invalid. `Synchronous reports support at most 400 days. Use report jobs for larger ranges.` when the resolved window is longer than 400 days (one hour of tolerance); use POST /v1/metrics/jobs with kind=main. The gate also refuses a malformed or foreign `affiliate` / `flow` filter (`Invalid affiliate filter`, `Unknown affiliate filter`, `Invalid flow filter`, `Unknown flow filter`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). The database is temporarily unavailable (Retry-After: 1) when this API process already runs its 4 reporting reads and 40 more are waiting.
- `504` The request took too long and was cancelled (the 25-second budget, queue time included, was exceeded); retry, narrow the range or use POST /v1/metrics/jobs with kind=main.

**Gotchas**

- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- v3.9.15 - FD22: a filtered TRAILING-HOURS read (no from/to, `hours` + a filter) is filtered too (its window synthesised); it used to ignore every filter.
- v3.9.15 - the rejections' 3DS fees of the "(no gateway)" row follow every key a rejection row carries (source side, ATRI, store, amount, BIN / first6 / last4 / brand of its masked card, IP, e-mail hash, order id); a key it has no column for leaves them out.
- v3.9.15 - every catalog key applies on BOTH paths: with from+to, and on the trailing-`hours` path (a filtered trailing read synthesises its window and takes the filtered path - the filters are no longer discarded there).
- Even on the from+to path those filters reach ONLY four queries: perMid, perWallet and the per-MID refund attribution. totals, finance, refunds, chargebacks, series, perAtri, perStore, perTrafficSource, perCardBrand, perSource, declineReasons, requestOutcomes and authFailures are computed WITHOUT them. Never present totals as 'the filtered KPIs'. v3.9.13 - finance.transactionFeeCents too: it summed the FILTERED perMid rows before; it is now the window's whole attempt fee, like every other finance line.
- v3.9 section 2 - the Traffic report's dimensions are filters here too, on the expressions Reports > Traffic groups on (db/txFilters): `hour` needs a known IANA `tz`, `bin` takes six-digit BINs (or a wallet word), `pricePoint` the seven bucket labels verbatim - v3.9.15: any other value is a 400 naming it. device / os / browser / country / storefront / traffic read a subscription charge's originating sale's context, and there is no '(unknown)' / 'Other' value to filter on (a row without a value matches nothing; `brand=Other` alone survives as 'no recognised network'). Like every dimension filter they narrow perMid / perWallet only.
- `series` is empty unless `bucket` (hour or day) is sent; it is produced on both the range and the trailing-hours window.
- `from` alone or `to` alone is IGNORED and the request falls back to the trailing-hours window. This differs from /v1/metrics/products, where either bound alone works. Always send both.
- v3.9.15 - from/to: an ISO instant with any offset ('2026-08-01T00:00:00Z', '...+02:00') or a YYYY-MM-DD day read in `tz` (UTC when absent); epoch millis and anything else are a 400.
- `atri` and `atriView` are different parameters with similar names. `atriView` (an extra of this route) restricts the ENTIRE response (all KPIs, breakdowns, finance, series); `atri` is the catalog's dimension filter and touches only perMid / perWallet.
- atriView is intersected with the caller's user_trips grants. If nothing survives the intersection (you picked ATRIs you have no grant for) it silently FALLS BACK to the caller's full grant set - you get more data, not zero.
- `pass` ORs its values: pass=initial,cascade is both (no narrowing); an unknown value is a 400 (v3.9.15). `source` (v3.9 section 2) ORs its values on SOURCE_BUCKET (sale | rebill | recovery, 'sale' excluding the recovery rows) + the words straight (= sale + recovery) / subscription (= rebill); an unknown word is a 400; a Source-only filter keeps that side's rejections' 3DS fees in the "(no gateway)" row.
- v3.9.15 - STRICT (it was not): an unknown query parameter is a 400. `groupBy`, `winners` and `mode` belong to the sibling /v1/metrics/* routes and are a 400 here.
- Every role including admin is scoped to its own api keys + owned wallet providers. An account with no keys and no wallet providers gets a fully-zeroed 200 with empty arrays - not a 403, and not a bug.
- When ANY dimension filter is active, perMid switches to `having count(t.id) > 0`, so MIDs with no matching charges disappear from the array. Unfiltered, EVERY MID in the account is listed, including ones with 0 charges. v3.9.13 - a `side` alone never prunes: every MID stays listed, with zeros for the other side's traffic, so the rows of straight + subscription add up to both row by row.
- v3.9 section 1 - every figure composes the central definitions (api/src/db/declines.ts): LIVE = no test card, no CSV import, no 3DS park; a DECLINE = a MID verdict (declined) or a technical error (error); the approval rate's base = live and completed (approved / declined / error / unknown). A charge cocoapi refused before any MID is not a transaction (charge_rejections, GET /v1/rejections) and appears in no figure. A raw transaction count for the same window still differs by the excluded rows.
- Both range bounds are INCLUSIVE (created_at >= from AND created_at <= to). Chaining adjacent windows double-counts rows sitting exactly on the boundary.
- perMid[].routedCents is intentionally over-counted: a cascaded order is credited to every MID that attempted it, so summing routedCents across MIDs exceeds total volume. Use sentCents (final_account based) if you need something that sums.
- perMid[].transactionFeeCents is attempts x flat fee, so declines cost money. v3.9.13 - finance.transactionFeeCents is no longer the sum of that column. It is the unfiltered attempt aggregate plus one wallet-provider flat fee per completed wallet charge (v3.9.6), so it equals sum of perMid + the wallet fee only on a read with no filter, no pass and no side.
- v3.9.6 live fees - RETROACTIVE BY DESIGN: no fee is stored on a row any more; every fee and net here is derived at read time from the gateways' CURRENT settings (nmi_accounts / wallet_providers discount bps, transaction fee, reserve bps, per-brand refund fees; account_integrations attemptFeeUsd for 3DS, the owner's 3DS rate for the rejections' fees). Edit a MID's discount rate and every past range re-prices at once - the dashboard's finance panel says 'fees at today's gateway rates'.
- perStore and perTrafficSource are capped at the top 50 by approved volume; when the cap bites, a synthetic '(other)' row is appended by SUBTRACTING the listed rows from the global totals - its approvalRate is derived, not measured. perAtri may contain a synthetic '__no_atri__' row. The store's remainder closes on the straight side's totals without `side` (v3.9.10). Under `side`, both remainders close on `sideTotals`.
- requestOutcomes comes from charge_request_logs and is api_key-scoped ONLY (no wallet, no ATRI restriction), so it never reconciles with totals for accounts with wallet traffic.
- All bigints are converted with Number() before serialization, so money and counts come back as JSON numbers, not strings - but they are still integer CENTS, and every *Rate / ar* field is a 0..1 ratio, not a percentage.
- v3.9 section 1 (this release): totals.declined / totals.error are the two halves of the declines (MID verdicts / technical errors); perMid[].declined and perWallet[].declined FOLD technical errors in (no error column on those rows); EVERY approvalRate is approved / completed - the one APPROVAL_BASE (live and completed) for totals, perMid, perWallet, perAtri and the breakdowns, so the per-MID rate no longer divides by charges incl. pending; a timed-out attempt is a decline in declineReasons and in the MID-fixable denominator; `blocked` is always 0 and goes away next release - the guards' refusals live in GET /v1/rejections.
- v3.9.3: the split is the CARDS' population - like totals / finance / refunds it ignores the per-gateway report's dimension filters (`status`, `atri`, `brand`...) and `pass`, which narrow perMid / perWallet only; a filtered report still receives the unfiltered split.
- v3.9.3: the split's new fields are snake_case (the v3.9.3 dashboard contract) next to the older camelCase ones; both conventions coexist in this payload on purpose.
- v3.9.3: a per-side approval rate is approved / completed of that side (completed = approved + declined + error + unknown), never approved / (approved + declined) - the same base as totals.approvalRate.
- v3.9.9 - every statistic equals its /transactions drill-down (population=live): Refunds = refund=refund, Chargebacks = refund=chargeback (dated by the refund), an ATRI row = atriFinal=<id>, "+ n -> cascade" = atri=<id>&pass=cascade&status=completed, a store / traffic row = storefront= / traffic= (inherited), "(no gateway)" = accountId=none, a wallet row = walletProvider=<id>&paysource=..., an "(unset)" reference bucket = processor|acquiringBank|company=none. The partner /v1/reports/gateways returns the same payload (minus split / sources / pilot).
- v3.9.13 - `side` splits the payload. The CARD fields (totals apart from avgLatencyMs / p95LatencyMs, finance, refunds, chargebacks, split, sources, pilot, subs, series, perSource, requestOutcomes, authFailures) are the same whatever the side; pilot's store attribution still reads the straight store rows. The BLOCK fields (perAtri, perStore, perTrafficSource, perCardBrand, perWallet, perMid, noGateway, declineReasons, the two latency totals) follow it. Never compare a sided block with `totals` or `finance`: compare it with `sideTotals` / `sideFinance` (the decline reasons add up to sideTotals.declined + sideTotals.error).
- v3.9.13 - for every additive block figure, side=straight + side=subscription = side=both: to the cent for sideTotals / sideFinance and for the total of every additive block (its rows plus its '(other)' / remainder row), and row by row for a row listed on all three sides. v3.9.13 (review round 3) - the capped lists do NOT add up row by row: perStore and perTrafficSource (the top 50 + an '(other)' row) and declineReasons (the top 10 + a remainder row) - each side ranks its own top rows and its remainder closes on that side's own totals (sideTotals), so a host can be a row on one side and inside '(other)' on another, and the '(other)' rows do not add up across sides either; perStore's straight rows also come from another statement than its subscription / both rows. Not additive, and the same on every side: perMid[].monthlyCapCents / usedCents (the cap usage of the current UTC month) and perMid[].atris (MID attributes), requestOutcomes and authFailures (no side), and the p95 latencies (percentiles do not add).
- v3.9.13 - side=both is NOT the same as leaving `side` out. The block fields equal the read without it, EXCEPT perStore: under both it holds every charge's rows, without `side` the straight sales only (v3.9.10). The four side keys also appear.
- v3.9.13 - `side` composes with the dimension filters (status, atri, source, pass...): a block read under a filter AND a side is their intersection, so source=subscription with side=straight gives empty blocks, not an error. The rejections' 3DS fee in noGateway follows the same intersection.
- Friendlies are excluded from ordinary approval rates, gross/net figures and Pilot ROAS. Both covers Straight and Subscription. Friendlies are shown through their own metrics and columns.
- The Active Subs card reads subs.activeSubs; newSubs/lostSubs remain period-based. Changing the date period does not turn activeSubs into a historical cohort count.
- V5 filter admission is scoped to the effective account and current feature flags. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing legacy storefront data alone is not No store.
- Net deducts the cut ledger exactly once using the shared dashboard/report formula. Cuts appear in all 16 financial breakdowns and exports. Different currencies are never implicitly summed or converted; incompatible net is null. Test payments never accrue cuts. The durable cut consumer may briefly lag payment confirmation.
- Do not sum all perSource rows: filter out subsetOf rows first. A recovered post-sell can be present in both subsets while counted only once in Straight.
- sections=gateways skips dashboard totals, charts, breakdowns, Pilot refresh/spend and affiliate ranking/commission work. It retains Friendlies group decoration and the same rejection/refund populations. main report jobs preserve sections in their execution and cache identity; the full and projected payloads never share a singleflight result.
- When tz is omitted, this report uses the effective account timezone, matching background report preparation. Trailing-hour windows keep that timezone for their labels and calendar-dependent calculations.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A trailing `hours` window (8760 at most) never reaches it. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=main for a longer range.

#### Gateways

The Gateways report page. It has no endpoint of its own: it reads GET /v1/metrics?sections=gateways (Dashboard metrics), GET /v1/metrics/traffic (Traffic) and GET /v1/accounts (Payments > Gateways). The figures it computes are below.

The Gateways report reads `GET /v1/metrics?sections=gateways` (rows `perMid`, `perWallet`, `perWire`, `noGateway`), `GET /v1/metrics/traffic` (Routing tab: dims `category,atri,gatewayType,processor,acquiringBank,gatewayMcc,gatewayBin`; Authentication tab: dim `threeDs`) and `GET /v1/accounts` (categories of each MID). Everything below is computed in the browser:

- Group by Any category / Processor / Acquiring bank / Company: rows summed from perMid, perWallet and perWire; a MID with several categories counts in each, and the Total then counts each MID once.
- Per row: Margin = net volume / gross volume; Refund % (count) = refundCount / approved; Refund % (volume) = refundCents / grossCents; CB % (count) = chargebackCount / approved; CB % (volume) = chargebackCents / grossCents; Approval rate = approved / completed. A ratio across two currencies is not computed (N/A).
- Total row (`sections=gateways` returns none): sums of the counts and money, every rate recomputed from the summed numerator and denominator.
- Routing and Authentication tabs: Share = row charges / table total; table Total = sum of the rows + the API's `tail`.

#### BINs

The BINs and issuers report.

- Share = row charges / total charges of the window (the API sorts by share but does not return it). Total-row rates are recomputed from `totals`. Card profiles tab (`GET /v1/metrics/traffic` with dims `brand,funding,level`): share and Total as in Reports > Traffic.
- The export holds only the page on screen; page with `limit` and `offset`.

##### `GET /v1/metrics/bins`

**Scope** `reports.read` - **Get the Bin & Issuers report**

Reports > Bin & Issuers (/reports/bins - a tool of its own beside Traffic since v3.9.1; v3.9 section 4): ONE list keyed by issuing bank (`axis=issuer`, bin_info.issuer of the card's BIN) or BIN (`axis=bin`, the first six digits of the card) over the same LIVE rows, tenant + ATRI scope, filter set and v3.9 section 1 counts as GET /v1/metrics/traffic (the shared builder in axis mode). WITHOUT `dim` (v3.9.1 - the page's Group by = All): one row per issuing bank / BIN of the WHOLE population of the window - every issuer / BIN with orders, no top-N cap, no breakdown, the same nine metrics. WITH `dim` (gateway, gatewayMcc, gatewayBin, processor, acquiringBank, pricePoint, hour, geo, threeDs, brand, level, funding, or any other Traffic dimension): the top `axisLimit` issuers / BINs by orders, each cut by that dimension - one row per (axis value, dimension value). Either way the list is sorted (`sort` / `dir`) and paged (`limit` / `offset`) server-side; every row carries `axis` and `key`, and the /transactions list reproduces it with `issuer=<axis>` (or `bin=<axis>`) - plus, under a cut, the dimension's own filter param (`accountId`, `gatewayMcc`, `gatewayBin`, `processor`, `acquiringBank`, `amountMin`/`amountMax`, `hour`+`tz`, `country`, `threeDs`, `brand`, `cardLevel`, `funding`...) - with the same filters. No 'Unknown' row: the orders without a value for the dimension, and those with no axis value at all (a wallet charge has no BIN), come back as `excluded` counts. Read-only. v3.9.9 - ONE statement in both views; Refunds / CB are the window's refund EVENTS (`refund=refund` / `refund=chargeback`); under a cut the issuers / BINs beyond the top `axisLimit` come back folded into `tail` (every cell of theirs) and `totals` = every row of the list + the tail (the dashboard's Total row); `summary` is the whole filtered window (the orders without an axis value included - the page's "N results").

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | **yes** | Window start, inclusive - a full ISO-8601 datetime accepted by zod `.datetime()` (`2026-09-01T04:00:00Z`). Compared against `transactions.created_at`. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). |
| `to` | string | **yes** | Window end, INCLUSIVE (`created_at <= to`). Same format as `from`. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). |
| `tz` | string; default `account_settings.timezone` | no | IANA timezone (<= 64 chars) the Hour dimension and the `hour` filter are read in - the dashboard sends its display timezone, the one its `from`/`to` day bounds were built in. Omitted -> the account's timezone. Unknown zone -> 400 `details.tz`. |
| `axis` | enum: issuer\|bin | **yes** | What the rows are keyed under: `issuer` = the issuing bank name (bin_info.issuer, empty -> no value), `bin` = the six-digit BIN of the card (rows without a numeric card, i.e. wallet charges, have none). |
| `dim` | string; default `(absent = All: one row per issuer / BIN, no cut)` | no | OPTIONAL since v3.9.1. Absent = the All view: one row per issuing bank / BIN over the whole population (`axis` = `key` = `name`), no breakdown, no cap; the answer carries `dim: null`, `axisLimit: null` and `excluded` keyed by the axis alone. Sent = the dimension each axis value is cut by - a `dims` key of GET /v1/metrics/traffic (gateway, gatewayType, category, atri, processor, acquiringBank, company, gatewayMcc, gatewayBin, threeDs, brand, funding, level, source, traffic, storefront, device, browser, os, ipType, hour, geo, pricePoint), ONE vocabulary shared with the dashboard (v3.9 section 2): `source` = the order origin (sale / rebill / recovery), `traffic` = the traffic source, `acquiringBank` = the bank, `company` = the legal entity the gateway is boarded under (v3.9.2 section 0) (the former `acquirer` spelling is unknown -> 400). Echoed back as sent. Unknown (an EMPTY `dim=` included: absent is not empty) -> 400 `details.dim`; equal to the axis (`issuer` under `axis=issuer`, `bin` under `axis=bin`) -> 400 `details.dim`. Also supports checkout, subscription and currency. |
| `limit` | integer; default `50` | no | Page size, 1..10000. |
| `offset` | integer; default `0` | no | Rows to skip, >= 0 (applied after the sort). |
| `axisLimit` | integer; default `100` | no | Under a cut (`dim` sent): how many axis values the cut covers - the top N issuers / BINs by orders in the filtered window, 1..5000; rows of other issuers / BINs are not in the list, in `total` or in `totals`. Without `dim` (the All view, v3.9.1) it is accepted but unused: the whole list comes back and the answer carries `axisLimit: null`. |
| `sort` | enum: axis\|name\|charges\|approved\|declined\|approvalRate\|grossCents\|aovCents\|refunds\|refundRate\|chargebacks\|chargebackRate\|share; default `charges` | no | The column the whole list is ordered by before paging (`share` orders like `charges`); ties break on orders desc, then the axis value, then the key. v3.9.9 - + refunds / chargebacks (the Refunds / CB count columns). |
| `dir` | enum: asc\|desc; default `desc` | no | Sort direction. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |
| `checkout` | string | no | Unified filter: comma-separated checkout UUIDs at sale, or none for unattributed / legacy charges. Intersects all other filters, scope and date bounds. |
| `affiliate` | CSV of affiliate UUIDs and/or none | no | Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `storefront` | CSV string | no | Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `flow` | string | no | Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |

**Response**

```json
{
  "axis": "issuer",
  "dim": "gateway",
  "tz": "America/New_York",
  "rows": [
    {
      "axis": "JPMORGAN CHASE BANK, N.A.",
      "key": "0f1e2d3c-4b5a-4c6d-8e7f-a0b1c2d3e4f5",
      "name": "AQUA WORLD PRIORITY/SYNOVUS",
      "charges": 812,
      "approved": 561,
      "declined": 238,
      "completed": 799,
      "refunds": 14,
      "chargebacks": 2,
      "grossCents": 2711300,
      "approvalRate": 0.7021,
      "refundRate": 0.025,
      "chargebackRate": 0.0036,
      "aovCents": 4833
    },
    {
      "axis": "CAPITAL ONE BANK USA, N.A.",
      "key": "0f1e2d3c-4b5a-4c6d-8e7f-a0b1c2d3e4f5",
      "name": "AQUA WORLD PRIORITY/SYNOVUS",
      "charges": 604,
      "approved": 366,
      "declined": 231,
      "completed": 597,
      "refunds": 11,
      "chargebacks": 1,
      "grossCents": 1740100,
      "approvalRate": 0.6131,
      "refundRate": 0.0301,
      "chargebackRate": 0.0027,
      "aovCents": 4754
    }
  ],
  "total": 1218,
  "offset": 0,
  "limit": 2,
  "sort": "charges",
  "dir": "desc",
  "axisCount": 100,
  "axisLimit": 100,
  "axisTotal": 1514,
  "excluded": {
    "gateway": 0,
    "issuer": 9731
  },
  "excludedEvents": {
    "gateway": { "refunds": 0, "chargebacks": 0 },
    "issuer": { "refunds": 21, "chargebacks": 4 }
  },
  "tail": { "key": "", "name": "", "rows": 2731, "axes": 1414, "charges": 11240, "approved": 4402, "declined": 6712, "completed": 11190, "refunds": 164, "chargebacks": 31, "grossCents": 16452300, "approvalRate": 0.3934, "refundRate": 0.0373, "chargebackRate": 0.007, "aovCents": 3737 },
  "totals": {
    "charges": 48120,
    "approved": 30311,
    "declined": 16888,
    "completed": 47199,
    "refunds": 702,
    "chargebacks": 61,
    "grossCents": 146402300
  },
  "summary": {
    "charges": 48120,
    "approved": 30311,
    "declined": 16888,
    "completed": 47199,
    "approvalRate": 0.6422,
    "grossCents": 146402300,
    "aovCents": 4830,
    "refunds": 702,
    "refundRate": 0.0232,
    "chargebacks": 61,
    "chargebackRate": 0.002
  }
}
```

| response field | type | description |
|---|---|---|
| `axis` | enum: issuer\|bin | The axis requested. |
| `dim` | string \| null | The dimension requested, spelled as the caller sent it (`acquiringBank` stays `acquiringBank`); null in the All view (no `dim` sent - v3.9.1). |
| `tz` | string | The timezone the Hour dimension and the `hour` filter were read in (the `tz` sent, else the account's). |
| `rows` | object[] | The page of the sorted list. All view (no `dim`, v3.9.1): one row per issuing bank / BIN with orders in the window - the whole population, no cap - with `axis` = `key` = `name`. Under a cut: one row per (axis value, dimension value) with orders, top `axisLimit` axis values by orders; rows without a value for the dimension are NOT here (see `excluded`). |
| `rows[].axis` | string | The issuing bank name or the six-digit BIN the row is cut under - the value of the /transactions `issuer` / `bin` filter. v3.9.8 item 1 - 'Apple Pay' / 'Google Pay' for the wallet charges (they have no PAN): the `issuer=` / `bin=` value that reproduces the row. |
| `rows[].key` | string | The dimension's filter value that reproduces the row: an id for gateway / category / atri / processor / acquiringBank / company, the label itself otherwise (a two-digit hour, a price bucket label, a country code, a 3DS stamp, sale / rebill / recovery for `source`...). All view: the axis value itself (the `issuer` / `bin` filter value). v3.9.9 - gateway: the MID id, else `wallet:<provider id>:<wallet>` (a wallet charge's provider x wallet - `accountId=wallet:<id>` + `brand`). |
| `rows[].name` | string | The display label (the gateway / category / ATRI / processor / bank name); equals `key` for a value dimension and in the All view. |
| `rows[].charges / approved / declined / completed / refunds / chargebacks` | integer | v3.9 section 1 counts of the cell: LIVE rows (not test, not imported, not the 3DS park) created in [from, to]; approved = status 'approved'; declined = status 'declined' or 'error'; completed = the approval rate's base (approved, declined, error, unknown), Friendlies sales left out. With the Friendlies integration active, charges / approved / declined / refunds / chargebacks include the Friendlies sales. v3.9.9 - the window's refund / chargeback EVENTS, the dashboard's Refunds / Chargebacks cards' basis: `refunds` = the transactions of the bucket with a successful, non-test refunds row NOT marked chargeback dated in [from, to] (the refund date - the refunded charge may be older than the window, it is attributed to ITS dimension values), `chargebacks` = the same row marked chargeback; per transaction; a chargeback is never a refund. The /transactions drill-down is `refund=refund` / `refund=chargeback` (+ the row's params, `population=live`). Every charge figure (charges, approved, declined, completed, grossCents) reads the window's charges only, so a bucket can hold events and no charge. |
| `rows[].grossCents` | integer | sum  amount_cents over the APPROVED rows of the cell (Friendlies sales included when the integration is active), integer CENTS. |
| `rows[].approvalApproved / approvalGrossCents` | integer | The approved count and the approved gross (integer cents) WITHOUT the Friendlies sales: the base of every rate and of the AOV. Equal to approved / grossCents without the Friendlies integration. |
| `rows[].friendliesSales / friendliesAmountCents / friendliesAmountCurrency / friendliesCostCents` | integer \| string \| null | The Friendlies part of the cell: approved Friendlies sales, their amount (null when they span several currencies) and its currency, and their cost (null while a Friendlies cost is unknown). 0 without the Friendlies integration. |
| `rows[].approvalRate / refundRate / chargebackRate / aovCents` | number | approvalApproved / completed; refunds / approvalApproved and chargebacks / approvalApproved - EVENTS of the period divided by the ordinary approved SALES of the period (the dashboard's ratio, not a cohort: a bucket can exceed 1 when its refunds are of older sales) - 0..1 ratios, 0 when the base is 0 (the dashboard shows a dash); round(approvalGrossCents / approvalApproved) in cents. Friendlies sales never enter a rate or the AOV. The dashboard recomputes them from the components. |
| `total` | integer | Rows in the whole list (every page), for paging. |
| `offset / limit / sort / dir` | mixed | The paging and sort applied, echoed. |
| `axisCount` | integer | Axis values in the list: under a cut the top `axisLimit` (<= axisLimit), in the All view the whole list (= `total`). v3.9.9 - `axisTotal` says how many the population holds. |
| `axisLimit` | integer \| null | The axis cap applied under a cut; null in the All view (no cap - v3.9.1). |
| `axisTotal` | integer | v3.9.9 - the axis values (issuers / BINs) of the whole filtered population: beyond `axisCount` (under a cut) they are the `tail`. |
| `excluded` | object | Under a cut, two counts keyed by the `dim` sent and by the `axis`: orders of the axis population without a value for the dimension (inside the population), and orders of the filtered window with no axis value at all - a card without a BIN, hence no issuer either (outside the population, not in `summary`; v3.9.8 item 1 - never a wallet charge: its issuer / BIN is its wallet, 'Apple Pay' / 'Google Pay', an axis row of the list). In the All view the axis key alone (`{ issuer: n }` / `{ bin: n }`): nothing is excluded inside the population. The dashboard's footnote ("n orders without ..."). v3.9.9 - the axis count now comes from the cut's own statement (its no-axis group), no second statement. |
| `excludedEvents` | object | v3.9.9 - keyed like `excluded`: `{ refunds, chargebacks }` - the refund / chargeback events of those orders (the dashboard's notes carry them), so totals + excludedEvents = the summary's events = the dashboard cards. |
| `tail` | object \| null | v3.9.9 - under a cut, the issuers / BINs beyond the top `axisLimit` (and any cell beyond the per-axis cap) folded into ONE row: `{ key: '', name: '', rows, axes, charges, approved, declined, completed, refunds, chargebacks, grossCents, approvalApproved, approvalGrossCents, the friendlies* fields, approvalRate, refundRate, chargebackRate, aovCents }` (`axes` = the axis values folded; its orders without a value for the dimension are in `excluded[dim]`). null in the All view and when nothing is cut. No filter reproduces it: the dashboard shows it as the list's last row, "Other (n)", plain text. |
| `totals` | object | sum  charges / approved / declined / completed / refunds / chargebacks / grossCents / approvalApproved / approvalGrossCents (+ grossCurrencies) over EVERY row of the list (all pages) and, v3.9.9, the `tail`: the dashboard's Total row (never the page on screen) and the Share column's base. totals.charges + excluded[dim] + excluded[axis] = summary.charges. |
| `summary` | object | v3.9.9 - the WHOLE filtered window: charges (the page's "N results", = the /transactions list with the same filters + population=live), approved, declined, completed, grossCents, refunds / chargebacks (the window's events = the dashboard's cards for the same scope) and the rates; the orders without an axis value included. |

**Errors**

- `400` Query validation failed - `from` / `to` / `axis` missing or malformed, `limit` outside 1..10000, `offset` < 0, `axisLimit` outside 1..5000, `sort` / `dir` not in their enums ({"error":"Invalid","details":<zod flatten()>}); an unknown timezone ({"details":{"tz":"not a known IANA timezone"}}); a `dim` that is sent but unknown (an empty `dim=` included) or is the axis itself ({"details":{"dim":"..."}}). A missing `dim` is NOT an error since v3.9.1: it is the All view. Also {"error":"Synchronous reports support at most 400 days. Use report jobs for larger ranges."} when the resolved window (from/to, or the trailing hours) is longer than 400 days (one hour of tolerance). Use POST /v1/metrics/jobs with kind=bins for a longer range.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"reports.read"} when the key's scopes lack reports.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` Unhandled database / server error. Body: {"error":"Internal Server Error","requestId":"<id>"}. A read that runs out of time is a 504, not a 500.
- `503` Back-pressure - too many requests in flight on this worker. Also {"error":"The database is temporarily unavailable ..."} with Retry-After: 1 when this API process already runs 4 reporting reads and has 40 more waiting for a connection. Also {"error":"Authentication scope is temporarily unavailable"} when the account scope cannot load (the report is never answered unscoped).
- `504` {"error":"The request took too long and was cancelled ..."} (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget. The budget starts with the read and includes the wait for a reporting connection; the SQL is cancelled. Retry, narrow the range, or use POST /v1/metrics/jobs with kind=bins.

**Gotchas**

- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- Under a cut (`dim` sent), ONE statement per call (v3.9.9 - the no-axis count used to be a second one): the builder's grouping-sets cut over every row of the filtered window - the top axes, the tail, the orders without an axis value - whatever the page (the sort and the page are applied in memory on the route). A 30-day window on a large account takes a few seconds; the page size does not change that.
- The All view (no `dim`, v3.9.1) is ONE lighter statement - a plain group by on the axis over the whole filtered base, no top-N pre-pass, no grouping sets (measured 2026-09-25 on the platform account, 30 days: ~ 0.8 s for ~ 1.6 k issuers / ~ 3.7 k BINs); its NULL group is the `excluded[axis]` count. The sort and the page are still applied in memory on the route, so the page size does not change the cost either.
- Under a cut the list covers the top `axisLimit` (default 100) issuers / BINs by orders in the FILTERED window: an issuer outside that top is in neither `rows`, `total`, `totals` nor `summary`. Raise `axisLimit` (<= 5000) for a wider list; `axisCount == axisLimit` tells you the cap bit. The All view has NO cap: `total` is every issuer / BIN with orders (90 days ~ 6 k BINs) - page it (`limit` / `offset`), the default sort (orders desc) keeps the busy ones on the first pages.
- The `issuer` axis is the raw bin_info.issuer string, not the rule engine's alias-folded issuer key (GET /v1/bin-issuers): two spellings of the same bank are two rows, in the All view as under a cut - folding them would break the exact `issuer=` drill-down.
- A wallet charge (Apple Pay / Google Pay) carries no numeric card: it has no BIN and no issuer, so it is never in this report under either axis - it is the `excluded.issuer` / `excluded.bin` count. Its card brand (when the wallet provider returned it) is only visible in GET /v1/metrics/traffic's brand dimension.
- `hour` (the dimension and the filter) is read in `tz`. Send the same `tz` you built `from` / `to` with, or the hour buckets shift against the day.
- ONE dimension vocabulary (v3.9 section 2): `dim` takes the dashboard's keys, which are the builder's - `source` is the ORDER ORIGIN dimension (sale / rebill / recovery, the `source` filter's own expression), `traffic` the traffic source, `acquiringBank` the bank, `company` the legal entity (v3.9.2 section 0). No alias: `acquirer` is a 400.
- The `issuer` axis value is the /transactions `issuer` filter value; that filter is a CSV read with RFC-4180 quoting, so an issuing bank whose name contains a comma ("... BANK, N.A.") is reproduced by sending it double-quoted (the dashboard does - such rows link like any other).
- Every `*Rate` is a 0..1 ratio, never a percentage, and their denominators differ (approvalRate on completed, refundRate / chargebackRate on approvalApproved, the approved sales without Friendlies). All money is integer CENTS.
- Invisible ATRI scoping: a member with ATRI grants gets every number restricted to those ATRIs (cascade-aware), with nothing in the response saying so; an API key sees the whole account.
- The account scope is loaded before the handler runs. If it cannot be loaded the request is refused (503), never answered with an empty or unscoped report. A caller with no keys, wallets or gateways still gets 200 with empty figures: no data and no scope look the same.
- Dashboard ownership: acquisition/devices/geography in Traffic; routing/authentication in Payment; card profiles in BIN & Issuers; pricing/currency in Products. The generic API stays backward compatible.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- Friendlies (an account with the Friendlies integration active): charges, approved, declined, grossCents, refunds and chargebacks include the Friendlies sales, but completed leaves them out and every rate uses the ordinary sales only. approvalApproved = approved without the Friendlies sales, approvalGrossCents = their gross; approvalRate = approvalApproved / completed, refundRate = refunds / approvalApproved, chargebackRate = chargebacks / approvalApproved, aovCents = round(approvalGrossCents / approvalApproved). friendliesSales, friendliesAmountCents (null when the Friendlies sales span several currencies), friendliesAmountCurrency and friendliesCostCents (null while a Friendlies cost is unknown) describe the Friendlies part. Without the integration, Friendlies-tagged transactions are left out of the report entirely, and approvalApproved = approved, approvalGrossCents = grossCents.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=bins for a longer range or a heavier cut.
- Every transaction filter of the unified catalog is accepted, with the same names and values as GET /v1/transactions (listed above); an unknown key or value answers 400.

#### Refunds

The segment analysis behind the Refunds and chargebacks report (mode=refunds) and the Subscriptions report (mode=rebill).

The Refunds and chargebacks report (mode `refunds`) and the Subscriptions report (mode `rebill`) both read `GET /v1/metrics/segments`. In the browser:

- Every dimension table's Total row is summed from its rows (only the product table has an API total, `totals.product`); the Subscriptions report hides segments with 0 charges.
- Profiles tab, Best / Worst profile: eligible segments have at least max(10, 1% of the card_brand sample) charges; the score is the approval rate for Best and -(refundRate + chargebackRate) for Worst.

##### `GET /v1/metrics/segments`

**Scope** `reports.read` - **Segment analysis (dashboard: with totals)**

Dashboard segment analysis with totals; GET /v1/reports/segments is the Reporting API's stable shape without totals. Cuts the window across 17 dimensions (price point, initial value, card brand/type/issuer/level, store, geo, hour, source, device, OS, traffic, product and - since v3.9 section 0 - the processor and the acquiring bank of the charge's gateway, and since v3.9.2 section 0 its company; v3.9.12 - mode 'rebill' adds five, 22 there: the subscription product, the cycle, the gateway (MID), its primary category and its MCC) and returns per dimension value the figures of one of two reports. v3.9.9 - every figure the dashboard shows equals the /transactions list its link opens. mode 'rebill' (Reports > Subscription > Charges): the window's subscription charges (the list's source=rebill) - charges, success, declines, approval rate, volume. mode 'refunds' (Reports > Refund & CHB): the window's approved SALES (status=approved), the REFUNDS booked in the window (a successful, non-test refunds row not marked chargeback, dated by the refund - the list's refund=refund) and the CHARGEBACKS booked in it (refund=chargeback), each attributed to the refunded transaction's segment; rates = events of the period / sales of the period. Counts are per transaction; `totals.product` is the product table's Total (a basket's products overlap). Scoped to the caller's account and, since v3.9.9, to its ATRI view (user_trips grants) exactly as the list. v3.9.11: `source` (straight / subscription, or the raw values) restricts both populations - the sales and the refund events' transactions - to that side.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `mode` | enum: rebill \| refunds; default `rebill` | no | enum: rebill\|refunds (default rebill). Which report. v3.9.15 - declared in the schema: any other value ('refund', 'Refunds') is a 400. |
| `hours` | integer, 1..8760; default `24` | no | Trailing window length, min 1, max 8760. Used ONLY to derive the start when `from` is absent (start = end - hours). Ignored entirely when `from` is supplied. |
| `from` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Window start, inclusive: an ISO instant (any offset) or a YYYY-MM-DD day read in `tz`. When omitted, start = end - hours. |
| `to` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40; default `now` | no | Window end, inclusive (a day is its last millisecond in `tz`). `to` before `from` is a 400. |
| `tz` | string, max 64 (IANA timezone); default `account timezone` | no | Clock of the `hour` labels, calendar-day bounds and the `hour` filter. Unknown is a 400. |
| `hour` | CSV of integers 0..23, max 200 | no | Filter catalog, Date: CSV of hours 00-23 in tz (needs tz). Needs a valid tz: an hour without one is a 400 `hour needs a valid tz`. |
| `status` | CSV enum | no | Filter catalog, Transaction: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `source` | CSV enum, max 100 | no | Filter catalog, Transaction: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. An unknown value is a 400 naming it. |
| `pass` | CSV enum, max 40 | no | Filter catalog, Transaction: initial / cascade. Allowed values: initial, cascade. An unknown value is a 400 naming it. |
| `method` | CSV enum, max 40 | no | Filter catalog, Transaction: card / wallet / wire. Allowed values: card, wallet, wire. An unknown value is a 400 naming it. |
| `population` | CSV enum, max 40 | no | Filter catalog, Transaction: live / test / imported (reports: live only). Allowed values: live, test, imported. An unknown value is a 400 naming it. |
| `credentialMode` | CSV enum, max 20 | no | Filter catalog, Transaction: Wire: mit / cit. Allowed values: mit, cit. An unknown value is a 400 naming it. |
| `threeDs` | CSV enum | no | Filter catalog, Transaction: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. An unknown value is a 400 naming it. |
| `declineCategory` | string, max 1000 | no | Filter catalog, Transaction: Decline-engine category. |
| `declineSeverity` | CSV enum, max 40 | no | Filter catalog, Transaction: soft / hard. Allowed values: soft, hard. An unknown value is a 400 naming it. |
| `amountMin` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount >= (cents). |
| `amountMax` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount <= (cents). |
| `currency` | CSV of 3-letter codes, max 200 | no | Filter catalog, Transaction: ISO-4217 currency. |
| `gatewayTxnId` | string, max 4000 | no | Filter catalog, Transaction: Gateway transaction id (exact, CSV). |
| `authCode` | string, max 1000 | no | Filter catalog, Transaction: Auth code of any attempt (exact, CSV). |
| `descriptor` | string, max 128 | no | Filter catalog, Transaction: Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum | no | Filter catalog, Transaction: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. An unknown value is a 400 naming it. |
| `product` | string, max 4000 | no | Filter catalog, Transaction: Basket product name / slug / ref. |
| `productSlug` | string, max 4000 | no | Filter catalog, Transaction: Basket product slug. |
| `productKey` | string, max 4000 | no | Filter catalog, Transaction: Product per store: <host>\|<ref>. |
| `accountId` | CSV of MID uuids, wallet:<uuid>, wire:<uuid> or none, max 4000 | no | Filter catalog, Routing: Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string, max 100 | no | Filter catalog, Routing: a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Any category of the final MID (ids). |
| `primaryCategory` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Primary category of the final MID (ids). |
| `atri` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI reached (ids). |
| `atriFinal` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI the order ended on (ids). |
| `processor` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Processor ids, none. |
| `acquiringBank` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Acquiring bank ids, none. |
| `company` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Company ids, none. |
| `gatewayMcc` | string, max 1000 | no | Filter catalog, Routing: Final MID MCC. |
| `gatewayBin` | string, max 1000 | no | Filter catalog, Routing: Final MID acquirer BIN. |
| `brand` | string, max 200 | no | Filter catalog, Card: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string, max 100 | no | Filter catalog, Card: APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string, max 200 | no | Filter catalog, Card: Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string, max 200 | no | Filter catalog, Card: bin_info card type (or a wallet). |
| `cardLevel` | string, max 4000 | no | Filter catalog, Card: bin_info card level (or a wallet). |
| `issuer` | string, max 4000 | no | Filter catalog, Card: Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay, max 4000 | no | Filter catalog, Card: CSV of 6-digit BINs or a wallet label. |
| `first6` | string of 1..6 digits | no | Filter catalog, Card: Card prefix (1-6 digits). |
| `last4` | string of 1..4 digits | no | Filter catalog, Card: Card suffix (1-4 digits). |
| `country` | string, max 2000 | no | Filter catalog, Customer: Billing country (ISO-2, inherited from the sale). |
| `storefront` | string, max 4000 | no | Filter catalog, Customer: Store host bucket, (direct). May include __no_store__ for canonical standalone orders (no store), which is not a blank-URL test. |
| `traffic` | string, max 2000 | no | Filter catalog, Customer: Traffic source, (direct/organic). |
| `utmSource` | string, max 4000 | no | Filter catalog, Customer: UTM source (case-insensitive). |
| `utmCampaign` | string, max 4000 | no | Filter catalog, Customer: UTM campaign (case-insensitive). |
| `device` | string, max 200 | no | Filter catalog, Customer: Mobile / Tablet / Desktop. |
| `os` | string, max 200 | no | Filter catalog, Customer: Operating system. |
| `browser` | string, max 200 | no | Filter catalog, Customer: Browser. |
| `ipType` | CSV enum, max 40 | no | Filter catalog, Customer: IPv4 / IPv6. Allowed values: IPv4, IPv6. An unknown value is a 400 naming it. |
| `ip` | string, max 2000 | no | Filter catalog, Customer: CSV of client IPs. |
| `email` | string, max 200 | no | Filter catalog, Customer: E-mail contains. |
| `phone` | string, max 40 | no | Filter catalog, Customer: Phone contains. |
| `firstName` | string, max 120 | no | Filter catalog, Customer: First name contains. |
| `lastName` | string, max 120 | no | Filter catalog, Customer: Last name contains. |
| `customerEmail` | CSV of e-mails, max 4000 | no | Filter catalog, Client: Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum, max 200 | no | Filter catalog, Client: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. An unknown value is a 400 naming it. |
| `clientBlacklisted` | enum | no | Filter catalog, Client: Blacklisted (e-mail or card). Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientLiveSub` | enum | no | Filter catalog, Client: Has a live (active / paused) subscription. Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientOrdersMin` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders >=. |
| `clientOrdersMax` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders <=. |
| `clientLtvMin` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value >= (cents). |
| `clientLtvMax` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value <= (cents). |
| `clientFirstFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen from. |
| `clientFirstTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen to. |
| `clientLastFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen from. |
| `clientLastTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen to. |
| `checkout` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped.. Derived from the immutable purchase session version, not the current store assignment; unknown or foreign flow ids are a 400 (`Unknown flow filter`). |
| `affiliate` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids.. Account-owned disabled affiliates stay valid for history; malformed, unknown or foreign ids are a 400 (`Invalid affiliate filter` / `Unknown affiliate filter`), never an unfiltered answer. |
| `subscription` | CSV of uuids, max 4000 | no | Filter catalog, Subscription: Subscription product ids. |
| `cycle` | CSV of integers 0..999, max 200 | no | Filter catalog, Subscription: Charge cycle (0 = the straight sale). |
| `cycleMin` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle >=. |
| `cycleMax` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle <=. |
| `engine` | CSV enum, max 60 | no | Filter catalog, Subscription: subscription / legacy / external. Allowed values: subscription, legacy, external. An unknown value is a 400 naming it. |
| `subStatus` | CSV enum | no | Filter catalog, Subscription: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. An unknown value is a 400 naming it. |
| `attachedBy` | CSV enum, max 60 | no | Filter catalog, Subscription: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. An unknown value is a 400 naming it. |
| `due` | enum | no | Filter catalog, Subscription: Next charge: overdue / 24h / 7d. Allowed values: overdue, 24h, 7d. An unknown value is a 400 naming it. |
| `endCause` | string, max 1000 | no | Filter catalog, Subscription: End cause. |
| `subCreatedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created from. |
| `subCreatedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created to. |
| `subEndedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended from. |
| `subEndedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended to. |
| `schedule` | CSV of uuids, max 4000 | no | Filter catalog, Schedule: Schedule (day) ids. |
| `scheduleStatus` | CSV enum | no | Filter catalog, Schedule: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. An unknown value is a 400 naming it. |
| `scheduleType` | CSV enum, max 60 | no | Filter catalog, Schedule: subscription / auto / manual. Allowed values: subscription, auto, manual. An unknown value is a 400 naming it. |
| `dayFrom` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum | no | Filter catalog, Schedule: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. An unknown value is a 400 naming it. |
| `entryReason` | string, max 4000 | no | Filter catalog, Schedule: Charge reason (decline reason of the entry). |
| `refund` | CSV enum, max 100 | no | Filter catalog, Refund: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `refundBasis` | enum | no | Filter catalog, Refund: Refund event dated by refund (default) / charge. Allowed values: refund, charge. An unknown value is a 400 naming it. |
| `refunded` | CSV enum, max 20 | no | Filter catalog, Refund: Refunded state flag. Allowed values: true, false. An unknown value is a 400 naming it. |
| `refundStatus` | CSV enum, max 80 | no | Filter catalog, Refund: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. An unknown value is a 400 naming it. |
| `refundTest` | enum | no | Filter catalog, Refund: Test refunds: exclude (= absent) / include / only. Allowed values: exclude, include, only. An unknown value is a 400 naming it. |
| `q` | string, max 200 | no | Filter catalog, Search: The page's identity search. Accepted by the strict catalog; identity search of list pages. |

**Response**

```json
{
  "mode": "refunds",
  "segments": [
    {
      "dim": "card_type",
      "key": "Apple Pay",
      "charges": 500,
      "approved": 500,
      "declined": 0,
      "blocked": 0,
      "completed": 500,
      "approvalRate": 1,
      "volumeCents": 2500000,
      "refunds": 0,
      "refundRate": 0,
      "chargebacks": 5,
      "chargebackRate": 0.01
    },
    {
      "dim": "geo",
      "key": "(unknown)",
      "charges": 0,
      "approved": 0,
      "declined": 0,
      "blocked": 0,
      "completed": 0,
      "approvalRate": 0,
      "volumeCents": 0,
      "refunds": 2,
      "refundRate": 0,
      "chargebacks": 0,
      "chargebackRate": 0
    },
    {
      "dim": "source",
      "key": "Straight",
      "charges": 1600,
      "approved": 1600,
      "declined": 0,
      "blocked": 0,
      "completed": 1600,
      "approvalRate": 1,
      "volumeCents": 8000000,
      "refunds": 40,
      "refundRate": 0.025,
      "chargebacks": 8,
      "chargebackRate": 0.005
    }
  ],
  "totals": {
    "product": {
      "charges": 1900,
      "approved": 1900,
      "declined": 0,
      "completed": 1900,
      "volumeCents": 8900000,
      "refunds": 30,
      "chargebacks": 6
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `mode` | string | The mode actually applied ('rebill' or 'refunds'). Echo it back - this is the only way to detect that a misspelled `mode` was silently coerced to 'rebill'. |
| `segments` | array<object> | Flat list of (dimension, value) cells. NOT grouped - group by `dim` client-side. Empty array when the caller's api-key scope is empty or the window has no matching rows. |
| `segments[].dim` | string | enum: price_point\|initial_value\|card_brand\|store\|geo\|hour\|source\|device\|os\|traffic\|card_type\|issuer\|card_level\|product\|processor\|acquiring_bank\|company\|subscription\|cycle\|mid\|category\|mcc. 17 dimensions (processor and acquiring_bank were added to the original 14 in v3.9 section 0, company in v3.9.2 section 0) (the source comment saying 13 predates the product dimension). v3.9.12 - mode=rebill adds five (22 there): subscription (the charge's sub's subscription product), cycle (the entry's rebill_number), mid (the gateway: a MID, or a wallet provider x wallet), category (the MID's PRIMARY category), mcc (the MID's MCC). mode=refunds is unchanged (17). |
| `segments[].key` | string | The dimension value - v3.9.9: for every dimension the dashboard links, the key IS the value of the /transactions filter that reproduces the cell, on that filter's own expression. price_point / initial_value carry a sort prefix ('1. < $25' ... '7. $200+'); hour is 'HH:00' in `tz`; geo an upper-cased country; source 'Straight' (the list's SOURCE_BUCKET sale + recovery), 'Rebill' (source=rebill) or 'Friendlies' (source=friendlies, only with an active Friendlies integration); card_brand the list's brand value (METHOD_CASE: 'Visa', 'Mastercard', 'Amex', 'Discover', 'Apple Pay', 'Google Pay' - the wallet first; '(unknown)' is exactly brand=Other, no network); store the storefront HOST (storeExpr), '(direct)' when the order has none; device / os the shared CASEs; traffic falls back to 'direct / organic' (the list's '(direct/organic)'); product the basket line's name, else slug, else ref - the list's `product` value, '(unknown)' included. card_type / issuer / card_level of a wallet charge are its wallet ('Apple Pay' / 'Google Pay'). Every other unresolved value is the literal '(unknown)' (no filter expresses it). v3.9.12 - subscription: the product's name, '(none)' = a charge no sub produced (a legacy / batch-API rebill); cycle: 'Cycle N', '(none)' likewise; mid: the MID's name, or '<provider> - <wallet>' for a wallet charge (the Payment report's wallet row), '(no gateway)' when the charge ended on none; category: the MID's PRIMARY category name (its first by name, the id breaking a tie - the list's primaryCategory), '(none)' = a MID without one or a wallet charge; mcc: the MID's MCC, '(none)' likewise; processor / acquiring_bank / company (both modes): the reference name, '(unset)' = a gateway WITHOUT that reference, '(no gateway)' = a charge that ended on no MID and no wallet provider - the two read '(unset)' together before v3.9.12. |
| `segments[].ref` | string (optional) | v3.9.12 - the /transactions value behind an id-keyed row, absent on the others: subscription -> the product id (the list's `subscription`); cycle -> N (`cycle`); mid -> the MID id (`accountId`), `wallet:<provider id>:<wallet>` (accountId=wallet:<provider id> + brand=<wallet>) or `none` on '(no gateway)' (accountId=none); category -> the category id (`primaryCategory`), `nogw` on '(no gateway)', absent on '(none)'; mcc -> `nogw` on '(no gateway)' only (the key itself is the list's `gatewayMcc` value); processor / acquiring_bank / company (both modes) -> the reference id (`processor` / `acquiringBank` / `company`), `none` on '(unset)' (that filter's own `none`: a gateway without the reference), `nogw` on '(no gateway)' (accountId=none). A row is (dim, key, ref): two products or MIDs of one name are two rows. |
| `segments[].charges` | integer | v3.9.9 - the cell's CHARGES: live rows (no test card, no CSV import, no 3DS park) CREATED in the window, counted per transaction. mode=refunds: the approved sales (so it equals `approved`); mode=rebill: every subscription charge. A segment reached only through a refund / chargeback EVENT of an earlier charge reads 0 here (its refunds / chargebacks are not 0). |
| `segments[].approved` | integer | Charges of the cell with status 'approved' (mode=refunds: the Sales - equals `charges`). Drill-down: status=approved (+ source=rebill on the rebill tool). |
| `segments[].approvalApproved` | integer | Approved charges of the cell WITHOUT the Friendlies sales: the base of approvalRate, refundRate and chargebackRate. Equal to `approved` when the account has no active Friendlies integration (Friendlies-tagged transactions are then excluded from the report). |
| `segments[].declined` | integer | Charges of the cell with status 'declined' or 'error' - the v3.9 section 1 declines (a technical error is one). Always 0 in mode=refunds. Drill-down: status=failed. |
| `segments[].completed` | integer | v3.9 section 1 - the approval rate's base of the cell: the charges with status approved, declined, error or unknown (pending and duplicate are out). Friendlies sales are left out. approvalRate = approvalApproved / completed, so a Total row recomputes the sum of approvalApproved over the sum of completed. In mode=refunds it equals approved. |
| `segments[].blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `segments[].approvalRate` | number (ratio 0..1) | approvalApproved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out), Friendlies sales in neither term - NOT approved / charges and no longer approved / (approved + declined). 0 when the base is 0; always 1 in mode=refunds when there is an ordinary sale. |
| `segments[].volumeCents` | integer | Integer CENTS of the cell's approved charges (a JSON number). On dim='product': mode=refunds = that product's own basket lines of the sales (the lines aggregated per order and product - they partition the sales' revenue); mode=rebill = the subscription charges' amounts. |
| `segments[].refunds` | integer | v3.9.9 - the refunds BOOKED in the window: transactions of the cell with a successful, non-test refunds row NOT marked chargeback whose created_at (the refund's date) is in the window - whatever the charge's own date - attributed to the refunded transaction's segment, counted per transaction. Never a chargeback (the old count read the transactions.refunded flag, which a chargeback sets too, on the window's sales). Drill-down: /transactions?refund=refund&population=live + the segment's filter (the list dates `refund` by the refunds row). |
| `segments[].refundRate` | number | RATIO: refunds / approvalApproved - events of the period divided by the ordinary (non-Friendlies) sales of the period (the card networks' ratio, not a cohort propensity: a segment can exceed 1, or hold events with no sale of the period). 0 when approvalApproved is 0 (the dashboard shows a dash). |
| `segments[].chargebacks` | integer | v3.9.9 - the chargebacks BOOKED in the window: the same refunds rows marked is_chargeback, dated by that row, per transaction. Drill-down: /transactions?refund=chargeback&population=live + the segment's filter. |
| `segments[].chargebackRate` | number | RATIO: chargebacks / approvalApproved - events of the period divided by the ordinary (non-Friendlies) sales of the period (the card networks' ratio, not a cohort propensity: a segment can exceed 1, or hold events with no sale of the period). 0 when approvalApproved is 0 (the dashboard shows a dash). |
| `segments[].friendliesSales / friendliesAmountCents / friendliesAmountCurrency / friendliesCostCents` | integer \| string \| null (optional) | Present only when the account's Friendlies integration is active: the cell's approved Friendlies sales, their amount (null when they span several currencies) and its currency, and their cost (null while a Friendlies cost is unknown). charges, approved, declined, volumeCents, refunds and chargebacks include the Friendlies sales; completed and every rate do not. |
| `totals` | object | v3.9.9 - the Totals no row sum can give. |
| `totals.product` | object | The product table's Total: every transaction of the window that has a basket, counted ONCE whatever its products (a basket with two products sits on two product rows, so sum of rows over-counts). Same fields as a segment's counts (charges, approved, approvalApproved, declined, completed, volumeCents, refunds, chargebacks); volumeCents = sum of the basket lines in mode=refunds (= sum of the product rows), each charge's amount once in mode=rebill. Covers every product row, the ancillary lines (Shipping Protection) included. |
| `segments[].dim (expanded)` | string | Both modes now include subscription, mid, category, mcc, company, processor, acquiring_bank, checkout, three_ds and currency. Existing rebill cycle/initial_value dimensions stay available. Checkout is historical attribution of the counted charge, not the current store assignment; 3DS is the counted charge authentication. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: an unknown parameter (strict catalog; `side`, `atriView` and `bucket` are not parameters here), an unknown closed-vocabulary value, mode outside rebill | refunds, hours outside 1..8760, a malformed from / to, an unknown tz, a reversed range pair, a value over its max length; `Invalid report timezone` when the account's stored timezone is invalid. `Synchronous reports support at most 400 days. Use report jobs for larger ranges.` when the resolved window is longer than 400 days (one hour of tolerance); use POST /v1/metrics/jobs with kind=segments. The gate also refuses a malformed or foreign `affiliate` / `flow` filter (`Invalid affiliate filter`, `Unknown affiliate filter`, `Invalid flow filter`, `Unknown flow filter`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). The database is temporarily unavailable (Retry-After: 1) when this API process already runs its 4 reporting reads and 40 more are waiting.
- `504` The request took too long and was cancelled (the 25-second budget, queue time included, was exceeded); retry, narrow the range or use POST /v1/metrics/jobs with kind=segments.

**Gotchas**

- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- v3.9.15 - `mode` is declared (it was read outside the schema). The Source / Wire filters of v3.9.11 / migration 171 are two keys of the catalog now.
- v3.9.15 - `mode` is validated: only 'rebill' (default) and 'refunds'; 'refund', 'Refunds' or 'REFUNDS' are a 400. The response echoes `mode`.
- mode=rebill reads the window's SUBSCRIPTION charges only - the list's source=rebill (SOURCE_BUCKET: channel 'rebill%' / 'legacy', or a rebill-named ATRI for an unknown channel). Straight sales are absent by design. A segment that only holds a refund / chargeback event of an earlier subscription charge comes back with charges 0 (the dashboard hides such rows).
- mode=refunds (v3.9.9): the population is the window's approved sales plus the transactions refunded or charged back in the window. `charges` = `approved` = `completed` = the Sales, `declined` is 0, approvalRate is 1 when there is a sale. Refunds and chargebacks are the EVENTS booked in the window (refunds.created_at), on sales of ANY date - a segment can show refunds with 0 sales (a refund of an earlier sale) and its rates are then 0 here, '-' on the dashboard; a rate can exceed 1.
- Refunds never include chargebacks, and a TEST refund (partner TEST key, no provider call) is never an event - the row set of the list's refund=... filter (txFilters REFUND_EVENT_SQL). The report used to count the window's sales flagged transactions.refunded (a chargeback sets it too): Apple Pay read "10 refunds - 10 CB" (the same 10 sales) while its link opened the 88 chargebacks of the month.
- Every count is per TRANSACTION (count distinct). On dim='product' a transaction sits once on each product of its basket (the basket is aggregated per order and product, as the list's `product` EXISTS): sum of the product rows is NOT the number of transactions - read `totals.product`.
- v3.9.9 - the caller's ATRI view (user_trips grants) IS applied, on the counted rows, exactly as GET /v1/transactions applies it (tripTxnScope, cascade-aware); the origin / basket look-ups are not ATRI-scoped. v3.9.15 - `atri` is a catalog filter and IS applied; `atriView` is not a parameter of this route (a 400).
- Scoped to the caller account's full tenancy (clientTenantScope: its api keys, wallet providers, MIDs, members) for every role. An empty scope returns HTTP 200 with `segments: []` and zero totals - 'no permission' and 'no data' are indistinguishable.
- `hour` labels are formatted in `tz`; the from/to window is the instants given (the dashboard sends its display-timezone day bounds), so a day range and its hour buckets read the same clock as the list's `hour` + `tz` filter.
- Window resolution is asymmetric: `from` alone -> from..now (hours ignored); `to` alone -> (to - hours)..to; both -> hours ignored; neither -> last 24h. `to` is inclusive.
- No pagination, no limit, no minimum-sample cutoff - every (dim, key) pair comes back in one flat array. High-cardinality dims (issuer, store, product) can push this into thousands of entries; a 1-row cell with a 0% or 100% rate is statistical noise, not a signal.
- All four *Rate fields are 0..1 ratios, not percentages, and all *Cents fields are integer cents.
- Contextual dimensions (device, os, geo, store, traffic, initial_value, product) on subscription charges are INHERITED from the originating sale, matched on order_id alone - measured identical to the list's own inheritance on every September row, so those cells link too. Rebills whose original sale is not in the DB (legacy imports) land in '(unknown)'.
- dim='processor' / dim='acquiring_bank' (v3.9 section 0) / dim='company' (v3.9.2 section 0): `key` is the reference NAME of the charge's own gateway - the final MID's processor / acquiring bank / company, else the wallet provider's (the GATEWAY_REF_JOIN of txFilters) - as stored (UPPERCASE, 'PRIORITY', 'SYNOVUS'). v3.9.12 - '(unset)' = a gateway WITHOUT that reference (ref `none`), '(no gateway)' = a charge that ended on no MID and no wallet provider (ref `nogw`); both read '(unset)' before. Unlike device / os / geo, a rebill is NOT matched to its originating sale on these three dims: it ran on its own MID and reports that MID's reference. To drill into a cell use GET /v1/transactions?processor=<ref> / ?acquiringBank=<ref> / ?company=<ref> (`none` included); `nogw` -> ?accountId=none.
- v3.9.11 - under `source` the Per Source table keeps that side's rows only (source=straight: the Straight row alone) and every other table counts that side's sales and refund events.
- v3.9.12 - the dashboard's Subscription tool (Reports -> Subscription -> Charges) shows its tables in contained tabs in the filter bar (`?view=`): Subscription (Per Subscription Product, Per Cycle, Per Price Point (order), Per Initial Order Value, Per Hour) - Routing (Per MID, Per Gateway Category, Per MCC, Per Acquirer = acquiring_bank, Per Processor, Per Company) - Cards (Per Bank (issuer), Per Card Brand, Per Type of Card, Per Card Level) - Traffic (Per Traffic Source, Per Store, Per Original Product, Per Geo, Per Device, Per OS) - Profiles (Best / Worst over every table). The 'source' dim is not shown there (one side). Verified on production (2026-09-28): every linked cell equals its /transactions list.
- Refunds/chargebacks are dated by successful live refund events, not the sale date. All monetary cells retain currency sets. Subscription attribution is a single product, preferring the charge entry then the originating attachment.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- When tz is omitted, this report uses the effective account timezone, matching background report preparation. Trailing-hour windows keep that timezone for their labels and calendar-dependent calculations.
- Friendlies (integration active): the Friendlies sales are counted in charges, approved, declined, volumeCents, refunds and chargebacks and get their own source row (key 'Friendlies'), but never in completed or a rate: approvalRate = approvalApproved / completed, refundRate and chargebackRate divide by approvalApproved. Without the integration, Friendlies-tagged transactions are excluded from the report.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=segments for a longer range.

#### Checkouts

Checkout analytics: conversion, payments, day by day and breakdowns.

- Conversion table: the funnel rows joined to the payment rows of `GET /v1/metrics/checkouts` by checkout (visitors counted once per checkout). AOV = approved volume / approved orders, per currency. Totals: approval rate = sum(approved) / sum(completed); CVR = sum(paid_visitors) / sum(visitors); completion rate = sum(completed_pay_visitors) / sum(visitors_to_pay); average time recomputed from the summed engagement.

##### `GET /v1/metrics/checkouts`

**Scope** `reports.read` - **Checkout analytics**

Read account-scoped per-checkout financial performance and visitor funnel for a required date range. Financial rows and daily series are separated by currency. Funnel counts are independent of currency and attached to the checkout actually presented at event time.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | **yes** | Required range start: an ISO instant with Z or an offset, or YYYY-MM-DD read in tz (its first millisecond). Max 40 characters. |
| `to` | string | **yes** | Required range end (inclusive): an ISO instant, or YYYY-MM-DD read in tz (its last millisecond). Must not be before from. Max 40 characters. |
| `tz` | string | no | IANA timezone for days and hours; defaults to the account timezone. Max 64 characters; an unknown zone is a 400. |
| `groupBy` | string | no | Optional cross-breakdown: store, gateway, company, category, gatewayMcc, threeDs, subscription, source, method, country. Adds group_key/group_name to rows and daily series. Always remains partitioned by checkout and currency. Invalid value: 400. |
| `checkoutId` | uuid | no | Restrict to one checkout (historical attribution). |
| `abTestId` | uuid | no | Only payments and visitor events attributed to this AB test. |
| `hour` | CSV string | no | Optional catalog filter (Date): CSV of hours 00-23 in tz (needs tz). Comma-separated hours 0 to 23 in tz; requires a valid tz (else 400 hour needs a valid tz). Max 200 characters. |
| `status` | CSV string | no | Optional catalog filter (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated, each value one of: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 400 characters. |
| `source` | CSV string | no | Optional catalog filter (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated, each value one of: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell (an unknown value is a 400 naming it). Max 100 characters. |
| `pass` | CSV string | no | Optional catalog filter (Transaction): initial / cascade. Comma-separated, each value one of: initial, cascade (an unknown value is a 400 naming it). Max 40 characters. |
| `method` | CSV string | no | Optional catalog filter (Transaction): card / wallet / wire. Comma-separated, each value one of: card, wallet, wire (an unknown value is a 400 naming it). Max 40 characters. |
| `population` | CSV string | no | Optional catalog filter (Transaction): live / test / imported (reports: live only). Comma-separated, each value one of: live, test, imported (an unknown value is a 400 naming it). Max 40 characters. |
| `credentialMode` | CSV string | no | Optional catalog filter (Transaction): Wire: mit / cit. Comma-separated, each value one of: mit, cit (an unknown value is a 400 naming it). Max 20 characters. |
| `threeDs` | CSV string | no | Optional catalog filter (Transaction): 3DS outcome. Comma-separated, each value one of: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only (an unknown value is a 400 naming it). Max 400 characters. |
| `declineCategory` | string | no | Optional catalog filter (Transaction): Decline-engine category. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `declineSeverity` | CSV string | no | Optional catalog filter (Transaction): soft / hard. Comma-separated, each value one of: soft, hard (an unknown value is a 400 naming it). Max 40 characters. |
| `amountMin` | string (integer) | no | Optional catalog filter (Transaction): Amount >= (cents). A whole number (1 to 12 digits). |
| `amountMax` | string (integer) | no | Optional catalog filter (Transaction): Amount <= (cents). A whole number (1 to 12 digits). |
| `currency` | CSV string | no | Optional catalog filter (Transaction): ISO-4217 currency. Comma-separated 3-letter ISO currency codes. Max 200 characters. |
| `gatewayTxnId` | string | no | Optional catalog filter (Transaction): Gateway transaction id (exact, CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `authCode` | string | no | Optional catalog filter (Transaction): Auth code of any attempt (exact, CSV). Free text (CSV where the field is multi-valued), max 1000 characters. |
| `descriptor` | string | no | Optional catalog filter (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). Free text (CSV where the field is multi-valued), max 128 characters. |
| `pricePoint` | CSV string | no | Optional catalog filter (Transaction): Price bucket. Comma-separated, each value one of: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+ (an unknown value is a 400 naming it). Max 400 characters. |
| `product` | string | no | Optional catalog filter (Transaction): Basket product name / slug / ref. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productSlug` | string | no | Optional catalog filter (Transaction): Basket product slug. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productKey` | string | no | Optional catalog filter (Transaction): Product per store: <host>\|<ref>. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `accountId` | CSV string | no | Optional catalog filter (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. Comma-separated MID UUIDs, wallet:<wallet provider UUID>, wire:<bank account UUID>, or none. Max 4000 characters. |
| `walletProvider` | CSV string | no | Optional catalog filter (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayType` | string | no | Optional catalog filter (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). Free text (CSV where the field is multi-valued), max 100 characters. |
| `category` | CSV string | no | Optional catalog filter (Routing): Any category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `primaryCategory` | CSV string | no | Optional catalog filter (Routing): Primary category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atri` | CSV string | no | Optional comma-separated ATRI UUIDs (unified filter). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atriFinal` | CSV string | no | Optional catalog filter (Routing): ATRI the order ended on (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `processor` | CSV string | no | Optional catalog filter (Routing): Processor ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `acquiringBank` | CSV string | no | Optional catalog filter (Routing): Acquiring bank ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `company` | CSV string | no | Optional catalog filter (Routing): Company ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayMcc` | string | no | Optional catalog filter (Routing): Final MID MCC. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `gatewayBin` | string | no | Optional catalog filter (Routing): Final MID acquirer BIN. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `brand` | string | no | Optional catalog filter (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Free text (CSV where the field is multi-valued), max 200 characters. |
| `paysource` | string | no | Optional catalog filter (Card): APPLEPAY / GOOGLEPAY (wallet payload). Free text (CSV where the field is multi-valued), max 100 characters. |
| `funding` | string | no | Optional catalog filter (Card): Prepaid / Debit / Credit / Charge card (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardType` | string | no | Optional catalog filter (Card): bin_info card type (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardLevel` | string | no | Optional catalog filter (Card): bin_info card level (or a wallet). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `issuer` | string | no | Optional catalog filter (Card): Issuing bank (RFC-4180 CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `bin` | CSV string | no | Optional catalog filter (Card): CSV of 6-digit BINs or a wallet label. Comma-separated 6-digit BINs or the wallet labels Apple Pay / Google Pay. Max 4000 characters. |
| `first6` | string | no | Optional catalog filter (Card): Card prefix (1-6 digits). 1 to 6 digits (prefix of the card number). |
| `last4` | string | no | Optional catalog filter (Card): Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Optional catalog filter (Customer): Billing country (ISO-2, inherited from the sale). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `storefront` | string | no | Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `traffic` | string | no | Optional catalog filter (Customer): Traffic source, (direct/organic). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `utmSource` | string | no | Optional catalog filter (Customer): UTM source (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `utmCampaign` | string | no | Optional catalog filter (Customer): UTM campaign (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `device` | string | no | Optional catalog filter (Customer): Mobile / Tablet / Desktop. Free text (CSV where the field is multi-valued), max 200 characters. |
| `os` | string | no | Optional catalog filter (Customer): Operating system. Free text (CSV where the field is multi-valued), max 200 characters. |
| `browser` | string | no | Optional catalog filter (Customer): Browser. Free text (CSV where the field is multi-valued), max 200 characters. |
| `ipType` | CSV string | no | Optional catalog filter (Customer): IPv4 / IPv6. Comma-separated, each value one of: IPv4, IPv6 (an unknown value is a 400 naming it). Max 40 characters. |
| `ip` | string | no | Optional catalog filter (Customer): CSV of client IPs. Free text (CSV where the field is multi-valued), max 2000 characters. |
| `email` | string | no | Optional catalog filter (Customer): E-mail contains. Free text (CSV where the field is multi-valued), max 200 characters. |
| `phone` | string | no | Optional catalog filter (Customer): Phone contains. Free text (CSV where the field is multi-valued), max 40 characters. |
| `firstName` | string | no | Optional catalog filter (Customer): First name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `lastName` | string | no | Optional catalog filter (Customer): Last name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `customerEmail` | string | no | Optional catalog filter (Client): Client e-mail (exact, CSV). Comma-separated e-mails, exact match, case-insensitive. Max 4000 characters. |
| `customerThreeDs` | CSV string | no | Optional catalog filter (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated, each one of: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters. |
| `clientBlacklisted` | string | no | Optional catalog filter (Client): Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | string | no | Optional catalog filter (Client): Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Optional catalog filter (Client): Lifetime orders >=. A whole number (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Optional catalog filter (Client): Lifetime orders <=. A whole number (1 to 12 digits). |
| `clientLtvMin` | string (integer) | no | Optional catalog filter (Client): Lifetime value >= (cents). A whole number (1 to 12 digits). |
| `clientLtvMax` | string (integer) | no | Optional catalog filter (Client): Lifetime value <= (cents). A whole number (1 to 12 digits). |
| `clientFirstFrom` | string (date-time or date) | no | Optional catalog filter (Client): First seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientFirstTo` | string (date-time or date) | no | Optional catalog filter (Client): First seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastFrom` | string (date-time or date) | no | Optional catalog filter (Client): Last seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastTo` | string (date-time or date) | no | Optional catalog filter (Client): Last seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `checkout` | CSV string | no | Unified filter: comma-separated checkout UUIDs at sale, or none for unattributed / legacy charges. Intersects all other filters, scope and date bounds. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `flow` | CSV string | no | Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. Account scoped. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `affiliate` | CSV string | no | Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `subscription` | CSV string | no | Optional catalog filter (Subscription): Subscription product ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `cycle` | CSV string | no | Optional catalog filter (Subscription): Charge cycle (0 = the straight sale). Comma-separated cycle numbers (0 to 999; 0 = the straight sale). Max 200 characters. |
| `cycleMin` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle >=. A whole number (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle <=. A whole number (1 to 6 digits). |
| `engine` | CSV string | no | Optional catalog filter (Subscription): subscription / legacy / external. Comma-separated, each value one of: subscription, legacy, external (an unknown value is a 400 naming it). Max 60 characters. |
| `subStatus` | CSV string | no | Optional catalog filter (Subscription): Sub status. Comma-separated, each value one of: active, paused, failed, cancelled, completed, expired (an unknown value is a 400 naming it). Max 400 characters. |
| `attachedBy` | CSV string | no | Optional catalog filter (Subscription): auto / manual / legacy / optin. Comma-separated, each value one of: auto, manual, legacy, optin (an unknown value is a 400 naming it). Max 60 characters. |
| `due` | string | no | Optional catalog filter (Subscription): Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Optional catalog filter (Subscription): End cause. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `subCreatedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subCreatedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `schedule` | CSV string | no | Optional catalog filter (Schedule): Schedule (day) ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `scheduleStatus` | CSV string | no | Optional catalog filter (Schedule): Schedule status. Comma-separated, each value one of: scheduled, processing, partial, paused, done, cancelled (an unknown value is a 400 naming it). Max 400 characters. |
| `scheduleType` | CSV string | no | Optional catalog filter (Schedule): subscription / auto / manual. Comma-separated, each value one of: subscription, auto, manual (an unknown value is a 400 naming it). Max 60 characters. |
| `dayFrom` | string (date) | no | Optional catalog filter (Schedule): Schedule run day from (YYYY-MM-DD). YYYY-MM-DD. |
| `dayTo` | string (date) | no | Optional catalog filter (Schedule): Schedule run day to (YYYY-MM-DD). YYYY-MM-DD. |
| `entryStatus` | CSV string | no | Optional catalog filter (Schedule): Charge state of the schedule entry. Comma-separated, each value one of: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed (an unknown value is a 400 naming it). Max 400 characters. |
| `entryReason` | string | no | Optional catalog filter (Schedule): Charge reason (decline reason of the entry). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `refund` | CSV string | no | Optional catalog filter (Refund): Refund event kind. Comma-separated, each value one of: refund, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 100 characters. |
| `refundBasis` | string | no | Optional catalog filter (Refund): Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV string | no | Optional catalog filter (Refund): Refunded state flag. Comma-separated, each value one of: true, false (an unknown value is a 400 naming it). Max 20 characters. |
| `refundStatus` | CSV string | no | Optional catalog filter (Refund): Refund row status. Comma-separated, each value one of: approved, pending, declined, error, unknown, cancelled (an unknown value is a 400 naming it). Max 80 characters. |
| `refundTest` | string | no | Optional catalog filter (Refund): Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Optional catalog filter (Search): The page's identity search. Free text (CSV where the field is multi-valued), max 200 characters. |

**Response**

```json
{
  "from": "2026-10-18T00:00:00.000Z",
  "to": "2026-10-18T23:59:59.999Z",
  "tz": "UTC",
  "rows": [
    {
      "checkout_id": "00000000-0000-4000-8000-000000000001",
      "checkout_name": "Shopify Checkout 1:1",
      "currency": "USD",
      "attempts": 12,
      "approved": 10,
      "declined": 2,
      "pending": 0,
      "errors": 0,
      "unknown": 0,
      "completed": 12,
      "revenue_cents": 29990,
      "refund_cents": 0,
      "approval_approved": 10,
      "approval_rate": 83.3333,
      "gateway_attempts": 13,
      "declined_attempts": 3,
      "recovered": 1
    }
  ],
  "series": [],
  "funnel": [
    {
      "checkout_id": "00000000-0000-4000-8000-000000000001",
      "checkout_name": "Shopify Checkout 1:1",
      "visitors": 100,
      "pay_button_clicks": 25,
      "visitors_to_pay": 20,
      "paid_visitors": 10,
      "completed_pay_visitors": 8,
      "cvr": 10,
      "completion_rate": 40,
      "engagement_ms": 600000,
      "engagement_views": 10,
      "avg_time_seconds": 60
    }
  ],
  "funnel_error": null
}
```

| response field | type | description |
|---|---|---|
| `funnel[]` | object[] \| null | Per checkout: visitors, pay_button_clicks, visitors_to_pay, paid_visitors and cvr. completed_pay_visitors counts visitors with an open, Pay click and success; completion_rate is its percentage of visitors_to_pay. engagement_ms and engagement_views aggregate deduplicated foreground page views; avg_time_seconds is null without measurements. Repeated visitor events, test-payment carts and test-marked events are excluded or deduplicated as appropriate. CVR is null without visitors. |
| `rows` | object[] | One financial row per checkout and currency. Monetary values are cents; avg order value = revenue_cents / approved, null when approved=0. approval_rate = 100 * approval_approved / completed (a percentage), 0 when completed = 0. Never sum different currencies. |
| `series` | object[] | Daily financial rows with an additional date field in the requested timezone. |
| `rows[].approval_approved` | integer | Approved charges WITHOUT the Friendlies sales: the numerator of approval_rate. With the Friendlies integration active, attempts, approved, declined and revenue_cents include the Friendlies sales while completed and approval_approved leave them out; without it Friendlies-tagged transactions are excluded from every financial figure. Equal to approved when no Friendlies sale is counted. |
| `funnel` | object[] \| null | Per-checkout visitor cohorts. null indicates a traffic read failure; an empty list is a successful read with no matching rows. When groupBy is present, visitor statistics are deliberately omitted (funnel=null, funnel_error=null); no synthetic attribution to gateway/MCC/subscription is made. |
| `funnel_error` | string \| null | Traffic read error independent of financial results; do not convert failed traffic reads to zeros. |
| `funnel[].visitors` | integer | Distinct visitors who opened or viewed this checkout during the period; store-scoped identities are not merged across stores. |
| `funnel[].pay_button_clicks` | integer | Raw pay_cta_pressed event count, including repeated presses before validation. |
| `funnel[].visitors_to_pay` | integer | Distinct opening visitors with a CTA press or validated pay_click. |
| `funnel[].paid_visitors` | integer | Distinct opening visitors with payment_success; wallet success can occur without a card CTA press. |
| `funnel[].completed_pay_visitors` | integer | Visitors in the opened + clicked + successful intersection. |
| `funnel[].cvr` | number \| null | 100 * paid_visitors / visitors; null with no opening visitors. |
| `funnel[].completion_rate` | number \| null | 100 * completed_pay_visitors / visitors_to_pay; null when nobody clicked. |
| `funnel[].engagement_ms` | integer | Summed foreground engagement milliseconds, cumulative snapshots deduplicated by view_id and capped at 30 minutes per view. |
| `funnel[].engagement_views` | integer | Number of checkout page views with valid engagement samples. |
| `funnel[].avg_time_seconds` | number \| null | engagement_ms / engagement_views / 1000. Background time is excluded. null when no timing samples exist; historical durations are not invented. |
| `rows[].group_key / group_name` | string \| null | Stable bucket identity and display label when groupBy is selected; null otherwise. Identical names with different entity IDs stay separate. |
| `funnel_error` | string \| null | Visitor-source warning. May accompany a non-null partially available funnel; preserve available rows and display the warning. |

**Errors**

- `400` {"error":"Invalid","details":...} for an unknown key, a malformed value, an unknown closed-vocabulary value, a reversed range (to is before from), hour without a valid tz or an unknown tz; {"error":"Invalid timezone"}; {"error":"Synchronous reports support at most 400 days. Use report jobs for larger ranges.","details":{"range":"Use a range of at most 400 days, or a report job."}} when the resolved window exceeds 400 days (one hour of tolerance)
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module reports): the plan lacks the reports module.
- `503` {"error":"The database is temporarily unavailable ..."} with Retry-After: 1 when this API process already runs 4 reporting reads and has 40 more waiting for a connection.
- `504` {"error":"The request took too long and was cancelled ..."} (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget. The budget starts with the read and includes the wait for a reporting connection; the SQL is cancelled. Retry, narrow the range, or use POST /v1/metrics/jobs with kind=checkouts.

**Gotchas**

- Visitor scope uses dates, checkout/test and store/ATRI permissions. Payment-only filters apply to financial rows.
- Visitors are distinct per store and presented checkout. CVR uses visitors with an opening and a payment_success in the selected window.
- Older events can be attributed to a current checkout only when they occurred after its last route configuration. Earlier unknown traffic remains Unattributed / legacy.
- Pay button clicks count pay_cta_pressed. Express wallet purchases count toward conversion. A traffic read failure returns funnel:null and funnel_error.
- Historical events without a reliable checkout snapshot stay Unattributed / legacy; changing a store checkout does not rewrite historical attribution.
- Reserved test-card transaction carts are excluded from the visitor funnel; financial metrics exclude is_test, imports and pre-gateway parks.
- Current account ownership is always required. An empty ATRI view means all permitted account routes, not zero routes.
- For large periods prefer POST /v1/metrics/jobs with kind=checkouts, poll job.progress, then retrieve the result. Recalculate reports marked obsolete.
- Use the ungrouped read for visitor conversion/completion/time; use groupBy for financial cross-breakdowns. Never total money across different currencies.
- gateway group keys are MID UUIDs, wallet:<provider UUID>:<Apple Pay|Google Pay|Wallet>, or none. Names are display-only; same-named gateways remain distinct. No gateway row uses an ATRI identity.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- Visitor metrics can be partial: available funnel rows are retained when a legacy traffic source fails. Inspect funnel_error even when funnel is non-null. Missing visitor coverage must be presented as unavailable, never fabricated zero; payment/transaction aggregates remain independently available.
- Friendlies (Friendlies integration active): the financial rows count the Friendlies sales in attempts, approved, declined and revenue_cents, but never in completed, approval_approved or approval_rate, so Friendlies sales do not inflate the approval rate. Without the integration they are excluded from the financial rows.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=checkouts for a longer range.
- A checkout whose only events in the window are engagement heartbeats still gets a funnel row, with its name and engagement time but zero visitors, clicks and payments (heartbeats never create a visit).
- Every key of the unified filter catalog is accepted (strict schema: an unknown query key is a 400) and applied to the report's transactions by the shared filter builder, with the same meaning as on the transactions list. Values come from GET /v1/filters/facets.

#### Flows

Flow performance.

- Per row and in the Total, from `GET /v1/metrics/flows`: AOV = cohortMinor / orders; Upsell take rate = upsellOrders / orders; totals are per currency. The API sends the definitions in `aovBasis` and `takeRateBasis`.

##### `GET /v1/metrics/flows`

**Scope** `reports.read` - **Flow performance**

Read account-scoped performance per immutable flow and currency, including initial order AOV, paid upsell take rate, upsell volume and cohort reversals. Maximum 366 days.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | **yes** | Required range start: an ISO instant with Z or an offset, or YYYY-MM-DD read in tz (its first millisecond). Max 40 characters. |
| `to` | string | **yes** | Required range end (inclusive): an ISO instant, or YYYY-MM-DD read in tz (its last millisecond). Must not be before from. Max 40 characters. |
| `tz` | string | no | IANA timezone for days and hours; defaults to the account timezone. Max 64 characters; an unknown zone is a 400. |
| `hour` | CSV string | no | Optional catalog filter (Date): CSV of hours 00-23 in tz (needs tz). Comma-separated hours 0 to 23 in tz; requires a valid tz (else 400 hour needs a valid tz). Max 200 characters. |
| `status` | CSV string | no | Optional catalog filter (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated, each value one of: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 400 characters. |
| `source` | CSV string | no | Shared source filter. Upsell is a subset of Straight; a union never counts a transaction twice. Source filtering also scopes the initial-paid-order cohort. Comma-separated, each value one of: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell (an unknown value is a 400 naming it). Max 100 characters. |
| `pass` | CSV string | no | Optional catalog filter (Transaction): initial / cascade. Comma-separated, each value one of: initial, cascade (an unknown value is a 400 naming it). Max 40 characters. |
| `method` | CSV string | no | Optional catalog filter (Transaction): card / wallet / wire. Comma-separated, each value one of: card, wallet, wire (an unknown value is a 400 naming it). Max 40 characters. |
| `population` | CSV string | no | Optional catalog filter (Transaction): live / test / imported (reports: live only). Comma-separated, each value one of: live, test, imported (an unknown value is a 400 naming it). Max 40 characters. |
| `credentialMode` | CSV string | no | Optional catalog filter (Transaction): Wire: mit / cit. Comma-separated, each value one of: mit, cit (an unknown value is a 400 naming it). Max 20 characters. |
| `threeDs` | CSV string | no | Optional catalog filter (Transaction): 3DS outcome. Comma-separated, each value one of: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only (an unknown value is a 400 naming it). Max 400 characters. |
| `declineCategory` | string | no | Optional catalog filter (Transaction): Decline-engine category. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `declineSeverity` | CSV string | no | Optional catalog filter (Transaction): soft / hard. Comma-separated, each value one of: soft, hard (an unknown value is a 400 naming it). Max 40 characters. |
| `amountMin` | string (integer) | no | Optional catalog filter (Transaction): Amount >= (cents). A whole number (1 to 12 digits). |
| `amountMax` | string (integer) | no | Optional catalog filter (Transaction): Amount <= (cents). A whole number (1 to 12 digits). |
| `currency` | CSV string | no | Optional catalog filter (Transaction): ISO-4217 currency. Comma-separated 3-letter ISO currency codes. Max 200 characters. |
| `gatewayTxnId` | string | no | Optional catalog filter (Transaction): Gateway transaction id (exact, CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `authCode` | string | no | Optional catalog filter (Transaction): Auth code of any attempt (exact, CSV). Free text (CSV where the field is multi-valued), max 1000 characters. |
| `descriptor` | string | no | Optional catalog filter (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). Free text (CSV where the field is multi-valued), max 128 characters. |
| `pricePoint` | CSV string | no | Optional catalog filter (Transaction): Price bucket. Comma-separated, each value one of: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+ (an unknown value is a 400 naming it). Max 400 characters. |
| `product` | string | no | Optional catalog filter (Transaction): Basket product name / slug / ref. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productSlug` | string | no | Optional catalog filter (Transaction): Basket product slug. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productKey` | string | no | Optional catalog filter (Transaction): Product per store: <host>\|<ref>. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `accountId` | CSV string | no | Optional catalog filter (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. Comma-separated MID UUIDs, wallet:<wallet provider UUID>, wire:<bank account UUID>, or none. Max 4000 characters. |
| `walletProvider` | CSV string | no | Optional catalog filter (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayType` | string | no | Optional catalog filter (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). Free text (CSV where the field is multi-valued), max 100 characters. |
| `category` | CSV string | no | Optional catalog filter (Routing): Any category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `primaryCategory` | CSV string | no | Optional catalog filter (Routing): Primary category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atri` | CSV string | no | Optional comma-separated ATRI UUIDs (unified filter). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atriFinal` | CSV string | no | Optional catalog filter (Routing): ATRI the order ended on (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `processor` | CSV string | no | Optional catalog filter (Routing): Processor ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `acquiringBank` | CSV string | no | Optional catalog filter (Routing): Acquiring bank ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `company` | CSV string | no | Optional catalog filter (Routing): Company ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayMcc` | string | no | Optional catalog filter (Routing): Final MID MCC. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `gatewayBin` | string | no | Optional catalog filter (Routing): Final MID acquirer BIN. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `brand` | string | no | Optional catalog filter (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Free text (CSV where the field is multi-valued), max 200 characters. |
| `paysource` | string | no | Optional catalog filter (Card): APPLEPAY / GOOGLEPAY (wallet payload). Free text (CSV where the field is multi-valued), max 100 characters. |
| `funding` | string | no | Optional catalog filter (Card): Prepaid / Debit / Credit / Charge card (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardType` | string | no | Optional catalog filter (Card): bin_info card type (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardLevel` | string | no | Optional catalog filter (Card): bin_info card level (or a wallet). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `issuer` | string | no | Optional catalog filter (Card): Issuing bank (RFC-4180 CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `bin` | CSV string | no | Optional catalog filter (Card): CSV of 6-digit BINs or a wallet label. Comma-separated 6-digit BINs or the wallet labels Apple Pay / Google Pay. Max 4000 characters. |
| `first6` | string | no | Optional catalog filter (Card): Card prefix (1-6 digits). 1 to 6 digits (prefix of the card number). |
| `last4` | string | no | Optional catalog filter (Card): Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Optional catalog filter (Customer): Billing country (ISO-2, inherited from the sale). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `storefront` | string | no | Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `traffic` | string | no | Optional catalog filter (Customer): Traffic source, (direct/organic). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `utmSource` | string | no | Optional catalog filter (Customer): UTM source (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `utmCampaign` | string | no | Optional catalog filter (Customer): UTM campaign (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `device` | string | no | Optional catalog filter (Customer): Mobile / Tablet / Desktop. Free text (CSV where the field is multi-valued), max 200 characters. |
| `os` | string | no | Optional catalog filter (Customer): Operating system. Free text (CSV where the field is multi-valued), max 200 characters. |
| `browser` | string | no | Optional catalog filter (Customer): Browser. Free text (CSV where the field is multi-valued), max 200 characters. |
| `ipType` | CSV string | no | Optional catalog filter (Customer): IPv4 / IPv6. Comma-separated, each value one of: IPv4, IPv6 (an unknown value is a 400 naming it). Max 40 characters. |
| `ip` | string | no | Optional catalog filter (Customer): CSV of client IPs. Free text (CSV where the field is multi-valued), max 2000 characters. |
| `email` | string | no | Optional catalog filter (Customer): E-mail contains. Free text (CSV where the field is multi-valued), max 200 characters. |
| `phone` | string | no | Optional catalog filter (Customer): Phone contains. Free text (CSV where the field is multi-valued), max 40 characters. |
| `firstName` | string | no | Optional catalog filter (Customer): First name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `lastName` | string | no | Optional catalog filter (Customer): Last name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `customerEmail` | string | no | Optional catalog filter (Client): Client e-mail (exact, CSV). Comma-separated e-mails, exact match, case-insensitive. Max 4000 characters. |
| `customerThreeDs` | CSV string | no | Optional catalog filter (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated, each one of: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters. |
| `clientBlacklisted` | string | no | Optional catalog filter (Client): Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | string | no | Optional catalog filter (Client): Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Optional catalog filter (Client): Lifetime orders >=. A whole number (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Optional catalog filter (Client): Lifetime orders <=. A whole number (1 to 12 digits). |
| `clientLtvMin` | string (integer) | no | Optional catalog filter (Client): Lifetime value >= (cents). A whole number (1 to 12 digits). |
| `clientLtvMax` | string (integer) | no | Optional catalog filter (Client): Lifetime value <= (cents). A whole number (1 to 12 digits). |
| `clientFirstFrom` | string (date-time or date) | no | Optional catalog filter (Client): First seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientFirstTo` | string (date-time or date) | no | Optional catalog filter (Client): First seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastFrom` | string (date-time or date) | no | Optional catalog filter (Client): Last seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastTo` | string (date-time or date) | no | Optional catalog filter (Client): Last seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `checkout` | CSV string | no | Unified filter: comma-separated checkout UUIDs at sale, or none for unattributed / legacy charges. Intersects all other filters, scope and date bounds. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `flow` | CSV string | no | Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. Account scoped. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `affiliate` | CSV string | no | Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `subscription` | CSV string | no | Optional catalog filter (Subscription): Subscription product ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `cycle` | CSV string | no | Optional catalog filter (Subscription): Charge cycle (0 = the straight sale). Comma-separated cycle numbers (0 to 999; 0 = the straight sale). Max 200 characters. |
| `cycleMin` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle >=. A whole number (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle <=. A whole number (1 to 6 digits). |
| `engine` | CSV string | no | Optional catalog filter (Subscription): subscription / legacy / external. Comma-separated, each value one of: subscription, legacy, external (an unknown value is a 400 naming it). Max 60 characters. |
| `subStatus` | CSV string | no | Optional catalog filter (Subscription): Sub status. Comma-separated, each value one of: active, paused, failed, cancelled, completed, expired (an unknown value is a 400 naming it). Max 400 characters. |
| `attachedBy` | CSV string | no | Optional catalog filter (Subscription): auto / manual / legacy / optin. Comma-separated, each value one of: auto, manual, legacy, optin (an unknown value is a 400 naming it). Max 60 characters. |
| `due` | string | no | Optional catalog filter (Subscription): Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Optional catalog filter (Subscription): End cause. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `subCreatedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subCreatedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `schedule` | CSV string | no | Optional catalog filter (Schedule): Schedule (day) ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `scheduleStatus` | CSV string | no | Optional catalog filter (Schedule): Schedule status. Comma-separated, each value one of: scheduled, processing, partial, paused, done, cancelled (an unknown value is a 400 naming it). Max 400 characters. |
| `scheduleType` | CSV string | no | Optional catalog filter (Schedule): subscription / auto / manual. Comma-separated, each value one of: subscription, auto, manual (an unknown value is a 400 naming it). Max 60 characters. |
| `dayFrom` | string (date) | no | Optional catalog filter (Schedule): Schedule run day from (YYYY-MM-DD). YYYY-MM-DD. |
| `dayTo` | string (date) | no | Optional catalog filter (Schedule): Schedule run day to (YYYY-MM-DD). YYYY-MM-DD. |
| `entryStatus` | CSV string | no | Optional catalog filter (Schedule): Charge state of the schedule entry. Comma-separated, each value one of: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed (an unknown value is a 400 naming it). Max 400 characters. |
| `entryReason` | string | no | Optional catalog filter (Schedule): Charge reason (decline reason of the entry). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `refund` | CSV string | no | Optional catalog filter (Refund): Refund event kind. Comma-separated, each value one of: refund, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 100 characters. |
| `refundBasis` | string | no | Optional catalog filter (Refund): Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV string | no | Optional catalog filter (Refund): Refunded state flag. Comma-separated, each value one of: true, false (an unknown value is a 400 naming it). Max 20 characters. |
| `refundStatus` | CSV string | no | Optional catalog filter (Refund): Refund row status. Comma-separated, each value one of: approved, pending, declined, error, unknown, cancelled (an unknown value is a 400 naming it). Max 80 characters. |
| `refundTest` | string | no | Optional catalog filter (Refund): Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Optional catalog filter (Search): The page's identity search. Free text (CSV where the field is multi-valued), max 200 characters. |

**Response**

```json
{
  "rows": [
    {
      "flowId": "11111111-1111-4111-8111-111111111111",
      "name": "Main flow",
      "currency": "USD",
      "transactions": 3,
      "approved": 2,
      "declined": 1,
      "unknown": 0,
      "pending": 0,
      "orders": 1,
      "upsellOrders": 1,
      "upsellTransactions": 1,
      "cohortMinor": "7998",
      "initialMinor": "5999",
      "upsellMinor": "1999",
      "grossMinor": "7998",
      "refundMinor": "0",
      "chargebackMinor": "0"
    }
  ],
  "basis": "Transactions created in the selected period; captured gross revenue, separated by currency. Reversals are cohort totals through period end.",
  "aovBasis": "cohortMinor / orders: initial plus upsell revenue for initial paid sessions in the period.",
  "takeRateBasis": "100 * upsellOrders / orders: initial paid sessions with a captured upsell in period and currency."
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | One row per flow/currency. Null flowId denotes direct/legacy. Transaction/status counts are distinct canonical payments. Monetary fields are decimal-string integer minor units. |
| `rows[].orders` | integer | Unique initial paid sessions in period/currency. No denominator means AOV/take rate are unavailable, not zero. |
| `rows[].upsellOrders` | integer | Initial-paid cohort sessions with one or more captured upsells in the period/currency. |
| `rows[].upsellTransactions` | integer | Captured upsell payment count, which can exceed upsellOrders. |
| `rows[].cohortMinor` | string | Initial plus upsell captured gross volume in the initial-paid session cohort; divide by orders for AOV in minor units. |
| `rows[].upsellMinor` | string | Captured upsell volume in the selected period, including upsells whose initial sale preceded the period. |
| `basis, aovBasis, takeRateBasis` | string | Human-readable metric definitions returned alongside data. |

**Errors**

- `400` {"error":"Invalid","details":...} for an unknown key, a malformed value, an unknown closed-vocabulary value, a reversed range (to is before from), hour without a valid tz or an unknown tz; {"error":"Invalid timezone"}; {"error":"Select at most 366 days"} when the resolved window exceeds 366 days; {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"} when a flow or affiliate id is not the account's.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); {"error":"Select an account"} when no account is selected; Your subscription does not include this tool. (code subscription_module_required, module reports): the plan lacks the reports module.
- `503` {"error":"The database is temporarily unavailable ..."} with Retry-After: 1 when this API process already runs 4 reporting reads and has 40 more waiting for a connection.
- `504` {"error":"The request took too long and was cancelled ..."} (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget. The budget starts with the read and includes the wait for a reporting connection; the SQL is cancelled. Retry, narrow the range.

**Gotchas**

- Transactions use immutable session/version attribution. Renaming a flow changes its display name, not its historical version.
- The range follows shared inclusive report date semantics. Pass date-only values with tz for local calendar periods.
- AOV excludes rebills and uses initial plus upsell captured volume belonging to initial-paid sessions inside the selected period. Upsells after period end are excluded.
- Take rate is paid-order take rate, not an offer-view acceptance rate. Failed charges, previews and test payments do not contribute paid upsell revenue.
- Never sum USD with EUR. Upsell is already part of Straight and gross totals; it is not an additional independent source bucket.
- Direct/legacy transactions can have gross volume but no recorded initial-flow session. Do not invent an AOV denominator for that row.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. The 366-day limit of this report stays (a longer window is a 400). A client that disconnects cancels its SQL.
- Every key of the unified filter catalog is accepted (strict schema: an unknown query key is a 400) and applied to the report's transactions by the shared filter builder, with the same meaning as on the transactions list. Values come from GET /v1/filters/facets.

#### Post-sells

Post-sell performance and diagnostics.

- Every ratio comes from `GET /v1/metrics/postsells`; only the export file is built in the browser.

##### `GET /v1/metrics/postsells`

**Scope** `reports.read` - **Read post-sell performance and diagnostics**

Return owner-scoped post-purchase conversion, captured AOV, event-dated revenue and operational diagnostics without mixing currencies or duplicating initial orders.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string | **yes** | Required range start: an ISO instant with Z or an offset, or YYYY-MM-DD read in tz (its first millisecond). Max 40 characters. |
| `to` | string | **yes** | Required range end (inclusive): an ISO instant, or YYYY-MM-DD read in tz (its last millisecond). Must not be before from. Max 40 characters. |
| `tz` | string | no | IANA timezone for days and hours; defaults to the account timezone. Max 64 characters; an unknown zone is a 400. |
| `hour` | CSV string | no | Optional catalog filter (Date): CSV of hours 00-23 in tz (needs tz). Comma-separated hours 0 to 23 in tz; requires a valid tz (else 400 hour needs a valid tz). Max 200 characters. |
| `status` | CSV string | no | Optional catalog filter (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated, each value one of: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 400 characters. |
| `source` | CSV string | no | Shared source filter. Upsell is a subset of Straight; a union never counts a transaction twice. Source filtering also scopes the initial-paid-order cohort. Comma-separated, each value one of: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell (an unknown value is a 400 naming it). Max 100 characters. |
| `pass` | CSV string | no | Optional catalog filter (Transaction): initial / cascade. Comma-separated, each value one of: initial, cascade (an unknown value is a 400 naming it). Max 40 characters. |
| `method` | CSV string | no | Optional catalog filter (Transaction): card / wallet / wire. Comma-separated, each value one of: card, wallet, wire (an unknown value is a 400 naming it). Max 40 characters. |
| `population` | CSV string | no | Optional catalog filter (Transaction): live / test / imported (reports: live only). Comma-separated, each value one of: live, test, imported (an unknown value is a 400 naming it). Max 40 characters. |
| `credentialMode` | CSV string | no | Optional catalog filter (Transaction): Wire: mit / cit. Comma-separated, each value one of: mit, cit (an unknown value is a 400 naming it). Max 20 characters. |
| `threeDs` | CSV string | no | Optional catalog filter (Transaction): 3DS outcome. Comma-separated, each value one of: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only (an unknown value is a 400 naming it). Max 400 characters. |
| `declineCategory` | string | no | Optional catalog filter (Transaction): Decline-engine category. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `declineSeverity` | CSV string | no | Optional catalog filter (Transaction): soft / hard. Comma-separated, each value one of: soft, hard (an unknown value is a 400 naming it). Max 40 characters. |
| `amountMin` | string (integer) | no | Optional catalog filter (Transaction): Amount >= (cents). A whole number (1 to 12 digits). |
| `amountMax` | string (integer) | no | Optional catalog filter (Transaction): Amount <= (cents). A whole number (1 to 12 digits). |
| `currency` | CSV string | no | Optional catalog filter (Transaction): ISO-4217 currency. Comma-separated 3-letter ISO currency codes. Max 200 characters. |
| `gatewayTxnId` | string | no | Optional catalog filter (Transaction): Gateway transaction id (exact, CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `authCode` | string | no | Optional catalog filter (Transaction): Auth code of any attempt (exact, CSV). Free text (CSV where the field is multi-valued), max 1000 characters. |
| `descriptor` | string | no | Optional catalog filter (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). Free text (CSV where the field is multi-valued), max 128 characters. |
| `pricePoint` | CSV string | no | Optional catalog filter (Transaction): Price bucket. Comma-separated, each value one of: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+ (an unknown value is a 400 naming it). Max 400 characters. |
| `product` | string | no | Optional catalog filter (Transaction): Basket product name / slug / ref. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productSlug` | string | no | Optional catalog filter (Transaction): Basket product slug. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `productKey` | string | no | Optional catalog filter (Transaction): Product per store: <host>\|<ref>. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `accountId` | CSV string | no | Optional catalog filter (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. Comma-separated MID UUIDs, wallet:<wallet provider UUID>, wire:<bank account UUID>, or none. Max 4000 characters. |
| `walletProvider` | CSV string | no | Optional catalog filter (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayType` | string | no | Optional catalog filter (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). Free text (CSV where the field is multi-valued), max 100 characters. |
| `category` | CSV string | no | Optional catalog filter (Routing): Any category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `primaryCategory` | CSV string | no | Optional catalog filter (Routing): Primary category of the final MID (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atri` | CSV string | no | Optional comma-separated ATRI UUIDs (unified filter). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `atriFinal` | CSV string | no | Optional catalog filter (Routing): ATRI the order ended on (ids). Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `processor` | CSV string | no | Optional catalog filter (Routing): Processor ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `acquiringBank` | CSV string | no | Optional catalog filter (Routing): Acquiring bank ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `company` | CSV string | no | Optional catalog filter (Routing): Company ids, none. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `gatewayMcc` | string | no | Optional catalog filter (Routing): Final MID MCC. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `gatewayBin` | string | no | Optional catalog filter (Routing): Final MID acquirer BIN. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `brand` | string | no | Optional catalog filter (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Free text (CSV where the field is multi-valued), max 200 characters. |
| `paysource` | string | no | Optional catalog filter (Card): APPLEPAY / GOOGLEPAY (wallet payload). Free text (CSV where the field is multi-valued), max 100 characters. |
| `funding` | string | no | Optional catalog filter (Card): Prepaid / Debit / Credit / Charge card (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardType` | string | no | Optional catalog filter (Card): bin_info card type (or a wallet). Free text (CSV where the field is multi-valued), max 200 characters. |
| `cardLevel` | string | no | Optional catalog filter (Card): bin_info card level (or a wallet). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `issuer` | string | no | Optional catalog filter (Card): Issuing bank (RFC-4180 CSV). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `bin` | CSV string | no | Optional catalog filter (Card): CSV of 6-digit BINs or a wallet label. Comma-separated 6-digit BINs or the wallet labels Apple Pay / Google Pay. Max 4000 characters. |
| `first6` | string | no | Optional catalog filter (Card): Card prefix (1-6 digits). 1 to 6 digits (prefix of the card number). |
| `last4` | string | no | Optional catalog filter (Card): Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Optional catalog filter (Customer): Billing country (ISO-2, inherited from the sale). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `storefront` | string | no | Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. Free text (CSV where the field is multi-valued), max 4000 characters. |
| `traffic` | string | no | Optional catalog filter (Customer): Traffic source, (direct/organic). Free text (CSV where the field is multi-valued), max 2000 characters. |
| `utmSource` | string | no | Optional catalog filter (Customer): UTM source (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `utmCampaign` | string | no | Optional catalog filter (Customer): UTM campaign (case-insensitive). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `device` | string | no | Optional catalog filter (Customer): Mobile / Tablet / Desktop. Free text (CSV where the field is multi-valued), max 200 characters. |
| `os` | string | no | Optional catalog filter (Customer): Operating system. Free text (CSV where the field is multi-valued), max 200 characters. |
| `browser` | string | no | Optional catalog filter (Customer): Browser. Free text (CSV where the field is multi-valued), max 200 characters. |
| `ipType` | CSV string | no | Optional catalog filter (Customer): IPv4 / IPv6. Comma-separated, each value one of: IPv4, IPv6 (an unknown value is a 400 naming it). Max 40 characters. |
| `ip` | string | no | Optional catalog filter (Customer): CSV of client IPs. Free text (CSV where the field is multi-valued), max 2000 characters. |
| `email` | string | no | Optional catalog filter (Customer): E-mail contains. Free text (CSV where the field is multi-valued), max 200 characters. |
| `phone` | string | no | Optional catalog filter (Customer): Phone contains. Free text (CSV where the field is multi-valued), max 40 characters. |
| `firstName` | string | no | Optional catalog filter (Customer): First name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `lastName` | string | no | Optional catalog filter (Customer): Last name contains. Free text (CSV where the field is multi-valued), max 120 characters. |
| `customerEmail` | string | no | Optional catalog filter (Client): Client e-mail (exact, CSV). Comma-separated e-mails, exact match, case-insensitive. Max 4000 characters. |
| `customerThreeDs` | CSV string | no | Optional catalog filter (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated, each one of: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters. |
| `clientBlacklisted` | string | no | Optional catalog filter (Client): Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | string | no | Optional catalog filter (Client): Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Optional catalog filter (Client): Lifetime orders >=. A whole number (1 to 12 digits). |
| `clientOrdersMax` | string (integer) | no | Optional catalog filter (Client): Lifetime orders <=. A whole number (1 to 12 digits). |
| `clientLtvMin` | string (integer) | no | Optional catalog filter (Client): Lifetime value >= (cents). A whole number (1 to 12 digits). |
| `clientLtvMax` | string (integer) | no | Optional catalog filter (Client): Lifetime value <= (cents). A whole number (1 to 12 digits). |
| `clientFirstFrom` | string (date-time or date) | no | Optional catalog filter (Client): First seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientFirstTo` | string (date-time or date) | no | Optional catalog filter (Client): First seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastFrom` | string (date-time or date) | no | Optional catalog filter (Client): Last seen from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `clientLastTo` | string (date-time or date) | no | Optional catalog filter (Client): Last seen to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `checkout` | CSV string | no | Unified filter: comma-separated checkout UUIDs at sale, or none for unattributed / legacy charges. Intersects all other filters, scope and date bounds. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `flow` | CSV string | no | Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. Account scoped. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `affiliate` | CSV string | no | Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs (or none) (an unknown value is a 400 naming it). Max 4000 characters. |
| `subscription` | CSV string | no | Optional catalog filter (Subscription): Subscription product ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `cycle` | CSV string | no | Optional catalog filter (Subscription): Charge cycle (0 = the straight sale). Comma-separated cycle numbers (0 to 999; 0 = the straight sale). Max 200 characters. |
| `cycleMin` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle >=. A whole number (1 to 6 digits). |
| `cycleMax` | string (integer) | no | Optional catalog filter (Subscription): Charge cycle <=. A whole number (1 to 6 digits). |
| `engine` | CSV string | no | Optional catalog filter (Subscription): subscription / legacy / external. Comma-separated, each value one of: subscription, legacy, external (an unknown value is a 400 naming it). Max 60 characters. |
| `subStatus` | CSV string | no | Optional catalog filter (Subscription): Sub status. Comma-separated, each value one of: active, paused, failed, cancelled, completed, expired (an unknown value is a 400 naming it). Max 400 characters. |
| `attachedBy` | CSV string | no | Optional catalog filter (Subscription): auto / manual / legacy / optin. Comma-separated, each value one of: auto, manual, legacy, optin (an unknown value is a 400 naming it). Max 60 characters. |
| `due` | string | no | Optional catalog filter (Subscription): Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Optional catalog filter (Subscription): End cause. Free text (CSV where the field is multi-valued), max 1000 characters. |
| `subCreatedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subCreatedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub created to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedFrom` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended from. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `subEndedTo` | string (date-time or date) | no | Optional catalog filter (Subscription): Sub ended to. An ISO instant or YYYY-MM-DD (a day read in tz). Max 40 characters. |
| `schedule` | CSV string | no | Optional catalog filter (Schedule): Schedule (day) ids. Comma-separated UUIDs (an unknown value is a 400 naming it). Max 4000 characters. |
| `scheduleStatus` | CSV string | no | Optional catalog filter (Schedule): Schedule status. Comma-separated, each value one of: scheduled, processing, partial, paused, done, cancelled (an unknown value is a 400 naming it). Max 400 characters. |
| `scheduleType` | CSV string | no | Optional catalog filter (Schedule): subscription / auto / manual. Comma-separated, each value one of: subscription, auto, manual (an unknown value is a 400 naming it). Max 60 characters. |
| `dayFrom` | string (date) | no | Optional catalog filter (Schedule): Schedule run day from (YYYY-MM-DD). YYYY-MM-DD. |
| `dayTo` | string (date) | no | Optional catalog filter (Schedule): Schedule run day to (YYYY-MM-DD). YYYY-MM-DD. |
| `entryStatus` | CSV string | no | Optional catalog filter (Schedule): Charge state of the schedule entry. Comma-separated, each value one of: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed (an unknown value is a 400 naming it). Max 400 characters. |
| `entryReason` | string | no | Optional catalog filter (Schedule): Charge reason (decline reason of the entry). Free text (CSV where the field is multi-valued), max 4000 characters. |
| `refund` | CSV string | no | Optional catalog filter (Refund): Refund event kind. Comma-separated, each value one of: refund, chargeback, rdr, ethoca (an unknown value is a 400 naming it). Max 100 characters. |
| `refundBasis` | string | no | Optional catalog filter (Refund): Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV string | no | Optional catalog filter (Refund): Refunded state flag. Comma-separated, each value one of: true, false (an unknown value is a 400 naming it). Max 20 characters. |
| `refundStatus` | CSV string | no | Optional catalog filter (Refund): Refund row status. Comma-separated, each value one of: approved, pending, declined, error, unknown, cancelled (an unknown value is a 400 naming it). Max 80 characters. |
| `refundTest` | string | no | Optional catalog filter (Refund): Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Optional catalog filter (Search): The page's identity search. Free text (CSV where the field is multi-valued), max 200 characters. |

**Response** `200`

```json
{
  "window": {
    "from": "2026-11-01T00:00:00.000Z",
    "to": "2026-11-02T00:00:00.000Z",
    "tz": "UTC",
    "asOf": "2026-11-02T00:01:00.000Z"
  },
  "basis": {
    "cohort": "Initial paid orders in the period, outcomes through asOf.",
    "eventRevenue": "Upsell events in the selected period.",
    "confirmed": "Committed intents or free fulfillments. Pre-intent rejections are not recorded."
  },
  "limits": {
    "maxDays": 366,
    "truncated": false
  },
  "overview": [],
  "pages": [],
  "flows": [],
  "stores": [],
  "payments": [],
  "daily": [],
  "skips": [],
  "threeDs": [],
  "latency": [],
  "diagnostics": {
    "midMismatches": 0,
    "currencyMismatches": 0,
    "unresolvedFinalizations": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `window` | object | Exact from/to/timezone and observation time asOf. Cohort outcomes can occur after the selected initial-capture window, through asOf. |
| `basis` | object | Definitions for cohort, eventRevenue, pages, prepared, confirmed, rates, currency, latency and providers. Keep these definitions with exports. |
| `overview\|pages\|flows\|stores\|payments\|daily` | array | Currency-separated rows: identity; initial/prepared/viewed/confirmed/declined/upsell/free/abandoned order counts; attempts and captured/failed/pending/unknown/closed unpaid payments; eventPayments; initialMinor, cohortUpsellMinor, eventGrossMinor, eventRefundMinor, eventChargebackMinor, eventNetMinor; initialAovMinor, combinedAovMinor and nullable rates aovUpliftPct, takeRatePct, viewToPaidPct, approvalRatePct. Money is a signed integer string in ISO currency minor units. Initial and combined AOV are null when the initial order denominator is zero. |
| `skips` | array | Recorded reason, action count and distinct order count. Historical skip reasons remain visible after a deployment fixes their cause. |
| `threeDs` | array | Provider, status, flow, binding counts, applied and liability-shift counts. Not the count of parallel authentication requests. |
| `latency` | array | Provider/currency, samples, avgMs, p50Ms, p95Ms, maxMs from intent creation to authoritative payment result. Includes authentication/reconciliation, not page-load time. |
| `diagnostics` | object | MID mismatches, currency mismatches and unresolved finalizations for the cohort. Effects can complete asynchronously. |
| `limits` | object | maxDays=366, truncated=false. Failures never silently produce partial revenue. |

**Errors**

- `400` {"error":"Invalid","details":...} for an unknown key, a malformed value, an unknown closed-vocabulary value, a reversed range (to is before from), hour without a valid tz or an unknown tz; {"error":"Invalid timezone"}; {"error":"Synchronous reports support at most 366 days. Use report jobs for larger ranges.","details":{"range":"Use a range of at most 366 days, or a report job."}} when the resolved window exceeds 366 days (one hour of tolerance); {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"} when a flow or affiliate id is not the account's.
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); {"error":"Select an account"} when no account is selected; Your subscription does not include this tool. (code subscription_module_required, module reports): the plan lacks the reports module.
- `503` Reporting pool saturated or database unavailable ({"error":"The database is temporarily unavailable - please retry in a moment."}, Retry-After: 1). Retry; never read it as zero revenue.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the read passes its 25-second budget (queue time included).

**Gotchas**

- Initial paid-order cohorts and event-dated upsell revenue use different time bases. Filters apply to the initial transaction for cohort metrics and each upsell transaction for event revenue. Tenant, owner and permitted ATRI scope apply.
- A session counts once even with multiple accepted pages or products. Page cohorts overlap and must not be summed. Never sum currencies; use their ISO minor-unit exponent, not a universal division by 100.
- Captured AOV includes tax and shipping. Combined AOV adds same-currency cohort upsells to the same initial-order denominator. Gross uplift is descriptive, not causal or net profit. Free additions are not paid conversions.
- Approval rate is captured / (captured + failed + unknown). Pending and closed unpaid attempts are excluded. Zero denominators are null. Net event revenue includes dated refunds and chargebacks/corrections, before fees, and can be negative.
- Views require recorded browser activity. Confirmations require a committed intent or free fulfillment. Rejections before intent creation are not recorded: zero attempts does not prove no clicks or request errors.
- Historical card provider attribution prefers immutable payment/transaction evidence, then the current gateway type of the original owned MID. It never uses a legacy card-dispatcher CRM label as the actual provider.
- All sections use one consistent snapshot, a maximum 366-day range and the bounded synchronous reporting pool. No customer names, emails, cards or session tokens are returned.
- Every key of the unified filter catalog is accepted (strict schema: an unknown query key is a 400) and applied to the report's transactions by the shared filter builder, with the same meaning as on the transactions list. Values come from GET /v1/filters/facets.

#### Products

The product breakdown, winners and pricing.

From `GET /v1/metrics/products` (`groupBy`, `winners=1`):

- Margin = netCents / grossCents; Refund rate = refundCount / approved; CB rate = chargebackCount / approved; Totals recomputed from the summed components (AR and subscription AR from `totals`).
- Pilot columns: Totals = sum of the spend; ROAS = sum(revenue) / sum(spend); cost per sale = sum(spend) / sum(sales); the reconciling row = `pilot.spend_cents - pilot.product_spend_cents`.
- Pricing and currency tab: `GET /v1/metrics/traffic` with dims `pricePoint,currency`; share and Total as in Reports > Traffic.

##### `GET /v1/metrics/products`

**Scope** `reports.read` - **Product breakdown (dashboard: totals, winners, ad spend)**

Dashboard product breakdown with totals, winners and ad spend; GET /v1/reports/products is the Reporting API's stable shape (products only). Per-product (or per-storefront) performance over a window: straight vs rebill charge counts and approval rates, the product's own approved volume, and a pro-rata share of the order-level finance columns (gross, fees, reserve, refunds, chargebacks, net). Backs the Product Breakdown panel and Reports > Products. v3.9.3: a row's straight / rebill classification is the shared rebillSql classifier (channel rebill% / legacy, or a rebill-named ATRI for an unknown channel) - the same one the dashboard cards' `split`, the Source breakdown and the /transactions `source` filter use, so a Straight count's drill-down must send `source=sale,recovery` (a recovery sale is a straight sale; `source=sale` alone opens fewer rows than the count). v3.9.4: the read refreshes TODAY's Pilot spend first (the same 60 s window / single-flight / 4 s budget as GET /v1/metrics - `pilot.refreshed_at` / `stale` / `refresh_reason`), and a product row's spend also matches by store alias + slug (a myshopify.com product URL). v3.9.9: every row also carries the rest of its Pilot detail - blended_roas, cost_per_sale_cents, net_after_ad_spend_cents - and the Ad Accounts / Campaigns of the row: the distinct TikTok ad accounts / campaigns ACTIVE on it over the range, the very campaigns its pilot_spend_cents comes from (folded by the spend's own matching; the links are stored by the sync, migration 169); the pilot block names them (links) and says whether they are complete (links_partial / days_unlinked), plus the reconciliation (unattributed_cents, unmatched_cents). The range's Pilot days come from ONE helper (the day of from -> the day of to - 1 s) and the live refresh is skipped when they do not hold the report tz's today. v3.9.9 (the stats reconciliation, D1 / D2): EVERY figure equals its /transactions drill-down. Refund / CB = the refund EVENTS of the window - successful, non-test refunds rows (db/txFilters REFUND_EVENT_SQL) NOT marked chargeback / marked chargeback, DATED BY THE REFUNDS ROW, on LIVE charges, counted per TRANSACTION, attributed to the refunded charge's product (its order's basket, pro-rata) / store, their amounts the refunds rows' own; the list opens them with `refund=refund` / `refund=chargeback` (a chargeback is never inside the refunds; a product refunded in the window without a sale in it still has its row). Volume = the CHARGED amount of the approved straight sales pro-rata over the basket lines (a basket whose lines carry no price - a wallet sale - shares by its lines' count); Net = the dashboard's Net (every fee, refunds, refund fees, chargebacks, chargeback fees). groupBy=store groups every live charge on the list's store bucket (the `storefront=` expression: own storefront, else the originating sale's - no basket needed); groupBy=product adds the reconciling `noBasket` row (the charges no basket names). `totals` are the account's figures (distinct transactions, exact money) - the dashboard's cards. The caller's ATRI view (user_trips grants) scopes the counted charges as the list does. `winners=1` adds the Winners tables' rows and their DISTINCT totals. v3.9.11: `source` (straight / subscription, or the raw values) restricts the whole report to that side - the rows, the reconciling rows, the totals and the Winners, the refund events' transactions included - and the refused charges' 3DS fees to that side's channel. v3.9.13 - every row, `noBasket` and `totals` carry `rebillUnits` (the dashboard tab's Subscription Units). The rows rank by straight volume, then subscription volume, then key, so a subscription-only product is no longer the first cut under the 500-row cap. The dashboard's Product breakdown fetches WITHOUT `source` and maps the tab's side from the straight / rebill* fields (Both = their sums, the same columns on every tab). v3.9.13 - exact cents: by product the money columns are allocated to the rows by largest remainder (db/productMetrics apportionSql, over every row before the 500-row cap), so sum of rows + the "(no product basket)" row = the totals exactly (+ the `rejections3ds` row on the 3DS fee and Net), each row within 1 cent of its own exact share; Net = gross - its parts, so sum of Net is exact too. A row's money can move by 1 cent against v3.9.12.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `hours` | integer, 1..8760; default `24` | no | Trailing window in hours, min 1, max 8760. Used only to derive `start` when `from` is absent: start = end - hours. Out of range -> 400. |
| `groupBy` | enum: product \| store; default `product` | no | enum: product\|store (default product) - v3.9.15: declared in the schema, any other value is a 400. v3.9.9 - store = the /transactions list's store bucket of EVERY live charge (the `storefront=` filter's expression, no basket needed; '(direct)' for an order without a storefront). |
| `winners` | enum: 1 | no | `1` adds `winners`: the Winners Straight / Subscription tables (no ancillary line such as Shipping Protection, traffic on that side, the top 25 by straight volume / by subscription approval rate) and their distinct counts. Any other value is a 400. |
| `side` | enum: straight \| subscription \| friendlies \| both | no | The dashboard tab of GET /v1/metrics: validated (any other value is a 400) and ignored by this route. |
| `from` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Window start, inclusive: an ISO instant (any offset) or a YYYY-MM-DD day read in `tz`. Works alone: end defaults to now. |
| `to` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40; default `now` | no | Window end, inclusive. Works alone: start = to - hours. `to` before `from` is a 400. |
| `tz` | string, max 64 (IANA timezone); default `account timezone` | no | Clock of calendar-day bounds and the `hour` filter. Unknown is a 400. |
| `hour` | CSV of integers 0..23, max 200 | no | Filter catalog, Date: CSV of hours 00-23 in tz (needs tz). Needs a valid tz: an hour without one is a 400 `hour needs a valid tz`. |
| `status` | CSV enum | no | Filter catalog, Transaction: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `source` | CSV enum, max 100 | no | Filter catalog, Transaction: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. An unknown value is a 400 naming it. |
| `pass` | CSV enum, max 40 | no | Filter catalog, Transaction: initial / cascade. Allowed values: initial, cascade. An unknown value is a 400 naming it. |
| `method` | CSV enum, max 40 | no | Filter catalog, Transaction: card / wallet / wire. Allowed values: card, wallet, wire. An unknown value is a 400 naming it. |
| `population` | CSV enum, max 40 | no | Filter catalog, Transaction: live / test / imported (reports: live only). Allowed values: live, test, imported. An unknown value is a 400 naming it. |
| `credentialMode` | CSV enum, max 20 | no | Filter catalog, Transaction: Wire: mit / cit. Allowed values: mit, cit. An unknown value is a 400 naming it. |
| `threeDs` | CSV enum | no | Filter catalog, Transaction: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. An unknown value is a 400 naming it. |
| `declineCategory` | string, max 1000 | no | Filter catalog, Transaction: Decline-engine category. |
| `declineSeverity` | CSV enum, max 40 | no | Filter catalog, Transaction: soft / hard. Allowed values: soft, hard. An unknown value is a 400 naming it. |
| `amountMin` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount >= (cents). |
| `amountMax` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount <= (cents). |
| `currency` | CSV of 3-letter codes, max 200 | no | Filter catalog, Transaction: ISO-4217 currency. |
| `gatewayTxnId` | string, max 4000 | no | Filter catalog, Transaction: Gateway transaction id (exact, CSV). |
| `authCode` | string, max 1000 | no | Filter catalog, Transaction: Auth code of any attempt (exact, CSV). |
| `descriptor` | string, max 128 | no | Filter catalog, Transaction: Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum | no | Filter catalog, Transaction: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. An unknown value is a 400 naming it. |
| `product` | string, max 4000 | no | Filter catalog, Transaction: Basket product name / slug / ref. |
| `productSlug` | string, max 4000 | no | Filter catalog, Transaction: Basket product slug. |
| `productKey` | string, max 4000 | no | Filter catalog, Transaction: Product per store: <host>\|<ref>. |
| `accountId` | CSV of MID uuids, wallet:<uuid>, wire:<uuid> or none, max 4000 | no | Filter catalog, Routing: Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string, max 100 | no | Filter catalog, Routing: a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Any category of the final MID (ids). |
| `primaryCategory` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Primary category of the final MID (ids). |
| `atri` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI reached (ids). |
| `atriFinal` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI the order ended on (ids). |
| `processor` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Processor ids, none. |
| `acquiringBank` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Acquiring bank ids, none. |
| `company` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Company ids, none. |
| `gatewayMcc` | string, max 1000 | no | Filter catalog, Routing: Final MID MCC. |
| `gatewayBin` | string, max 1000 | no | Filter catalog, Routing: Final MID acquirer BIN. |
| `brand` | string, max 200 | no | Filter catalog, Card: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string, max 100 | no | Filter catalog, Card: APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string, max 200 | no | Filter catalog, Card: Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string, max 200 | no | Filter catalog, Card: bin_info card type (or a wallet). |
| `cardLevel` | string, max 4000 | no | Filter catalog, Card: bin_info card level (or a wallet). |
| `issuer` | string, max 4000 | no | Filter catalog, Card: Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay, max 4000 | no | Filter catalog, Card: CSV of 6-digit BINs or a wallet label. |
| `first6` | string of 1..6 digits | no | Filter catalog, Card: Card prefix (1-6 digits). |
| `last4` | string of 1..4 digits | no | Filter catalog, Card: Card suffix (1-4 digits). |
| `country` | string, max 2000 | no | Filter catalog, Customer: Billing country (ISO-2, inherited from the sale). |
| `storefront` | string, max 4000 | no | Filter catalog, Customer: Store host bucket, (direct). May include __no_store__ for canonical standalone orders (no store), which is not a blank-URL test. |
| `traffic` | string, max 2000 | no | Filter catalog, Customer: Traffic source, (direct/organic). |
| `utmSource` | string, max 4000 | no | Filter catalog, Customer: UTM source (case-insensitive). |
| `utmCampaign` | string, max 4000 | no | Filter catalog, Customer: UTM campaign (case-insensitive). |
| `device` | string, max 200 | no | Filter catalog, Customer: Mobile / Tablet / Desktop. |
| `os` | string, max 200 | no | Filter catalog, Customer: Operating system. |
| `browser` | string, max 200 | no | Filter catalog, Customer: Browser. |
| `ipType` | CSV enum, max 40 | no | Filter catalog, Customer: IPv4 / IPv6. Allowed values: IPv4, IPv6. An unknown value is a 400 naming it. |
| `ip` | string, max 2000 | no | Filter catalog, Customer: CSV of client IPs. |
| `email` | string, max 200 | no | Filter catalog, Customer: E-mail contains. |
| `phone` | string, max 40 | no | Filter catalog, Customer: Phone contains. |
| `firstName` | string, max 120 | no | Filter catalog, Customer: First name contains. |
| `lastName` | string, max 120 | no | Filter catalog, Customer: Last name contains. |
| `customerEmail` | CSV of e-mails, max 4000 | no | Filter catalog, Client: Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum, max 200 | no | Filter catalog, Client: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. An unknown value is a 400 naming it. |
| `clientBlacklisted` | enum | no | Filter catalog, Client: Blacklisted (e-mail or card). Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientLiveSub` | enum | no | Filter catalog, Client: Has a live (active / paused) subscription. Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientOrdersMin` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders >=. |
| `clientOrdersMax` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders <=. |
| `clientLtvMin` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value >= (cents). |
| `clientLtvMax` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value <= (cents). |
| `clientFirstFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen from. |
| `clientFirstTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen to. |
| `clientLastFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen from. |
| `clientLastTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen to. |
| `checkout` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped.. Derived from the immutable purchase session version, not the current store assignment; unknown or foreign flow ids are a 400 (`Unknown flow filter`). |
| `affiliate` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids.. Account-owned disabled affiliates stay valid for history; malformed, unknown or foreign ids are a 400 (`Invalid affiliate filter` / `Unknown affiliate filter`), never an unfiltered answer. |
| `subscription` | CSV of uuids, max 4000 | no | Filter catalog, Subscription: Subscription product ids. |
| `cycle` | CSV of integers 0..999, max 200 | no | Filter catalog, Subscription: Charge cycle (0 = the straight sale). |
| `cycleMin` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle >=. |
| `cycleMax` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle <=. |
| `engine` | CSV enum, max 60 | no | Filter catalog, Subscription: subscription / legacy / external. Allowed values: subscription, legacy, external. An unknown value is a 400 naming it. |
| `subStatus` | CSV enum | no | Filter catalog, Subscription: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. An unknown value is a 400 naming it. |
| `attachedBy` | CSV enum, max 60 | no | Filter catalog, Subscription: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. An unknown value is a 400 naming it. |
| `due` | enum | no | Filter catalog, Subscription: Next charge: overdue / 24h / 7d. Allowed values: overdue, 24h, 7d. An unknown value is a 400 naming it. |
| `endCause` | string, max 1000 | no | Filter catalog, Subscription: End cause. |
| `subCreatedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created from. |
| `subCreatedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created to. |
| `subEndedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended from. |
| `subEndedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended to. |
| `schedule` | CSV of uuids, max 4000 | no | Filter catalog, Schedule: Schedule (day) ids. |
| `scheduleStatus` | CSV enum | no | Filter catalog, Schedule: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. An unknown value is a 400 naming it. |
| `scheduleType` | CSV enum, max 60 | no | Filter catalog, Schedule: subscription / auto / manual. Allowed values: subscription, auto, manual. An unknown value is a 400 naming it. |
| `dayFrom` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum | no | Filter catalog, Schedule: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. An unknown value is a 400 naming it. |
| `entryReason` | string, max 4000 | no | Filter catalog, Schedule: Charge reason (decline reason of the entry). |
| `refund` | CSV enum, max 100 | no | Filter catalog, Refund: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `refundBasis` | enum | no | Filter catalog, Refund: Refund event dated by refund (default) / charge. Allowed values: refund, charge. An unknown value is a 400 naming it. |
| `refunded` | CSV enum, max 20 | no | Filter catalog, Refund: Refunded state flag. Allowed values: true, false. An unknown value is a 400 naming it. |
| `refundStatus` | CSV enum, max 80 | no | Filter catalog, Refund: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. An unknown value is a 400 naming it. |
| `refundTest` | enum | no | Filter catalog, Refund: Test refunds: exclude (= absent) / include / only. Allowed values: exclude, include, only. An unknown value is a 400 naming it. |
| `q` | string, max 200 | no | Filter catalog, Search: The page's identity search. Accepted by the strict catalog; identity search of list pages. |

**Response**

```json
{
  "groupBy": "product",
  "products": [
    {
      "key": "shop.example.com|SKU-GLOW-30", "name": "Glow Serum 30ml", "slug": "glow-serum",
      "url": "https://shop.example.com/products/glow-serum", "storefrontUrl": "https://shop.example.com",
      "charges": 812, "approved": 301, "declined": 511, "completed": 812, "approvalRate": 0.3707, "volumeCents": 1198420,
      "rebillCharges": 190, "rebillApproved": 88, "rebillDeclined": 102, "rebillCompleted": 190, "rebillApprovalRate": 0.4632, "rebillVolumeCents": 352000,
      "grossCents": 1550420, "discountFeeCents": 46513, "transactionFeeCents": 12400, "reserveCents": 77521, "threeDsFeeCents": 1200,
      "refundCents": 42000, "refundCount": 9, "refundFeesCents": 1350, "chargebackCents": 8900, "chargebackCount": 2, "chargebackFeesCents": 3000,
      "netCents": 1357536, "units": 347, "rebillUnits": 96,
      "pilot_spend_cents": 510000, "straight_roas": 2.3499, "blended_roas": 3.0401, "cost_per_sale_cents": 1694, "net_after_ad_spend_cents": 847536,
      "pilot_accounts": 2, "pilot_campaigns": 5, "pilot_account_ids": ["7301"], "pilot_campaign_ids": ["1801"]
    },
    "... up to 500 rows"
  ],
  "noBasket": {
    "key": "__no_product_basket__", "name": "(no product basket)", "charges": 1, "approved": 0, "declined": 1, "rebillCharges": 5406,
    "rebillApproved": 989, "rebillVolumeCents": 3516011, "grossCents": 3516011, "refundCount": 692, "chargebackCount": 92, "...": "the row shape",
    "pilot_spend_cents": null, "straight_roas": null, "net_after_ad_spend_cents": 2803422
  },
  "totals": {
    "charges": 35990, "approved": 21145, "declined": 14845, "completed": 35990, "volumeCents": 88874967, "units": 42254,
    "rebillCharges": 23875, "rebillApproved": 4400, "rebillDeclined": 19474, "rebillCompleted": 23874, "rebillVolumeCents": 19542600, "rebillUnits": 4731,
    "approvalRate": 0.5875, "rebillApprovalRate": 0.1843, "grossCents": 108417567, "refundCount": 1356, "chargebackCount": 297, "...": "every money field, exact"
  },
  "winners": { "straight": { "keys": ["shop.example.com|SKU-GLOW-30", "..."], "charges": 33212, "approved": 19461, "declined": 13751, "completed": 33212 }, "rebill": { "keys": ["..."], "charges": 153, "approved": 68, "declined": 85, "completed": 153 } },
  "pilot": { "active": true, "reason": null, "spend_cents": 34024091, "product_spend_cents": 32866395, "...": "see pilot" }
}
```

| response field | type | description |
|---|---|---|
| `groupBy` | string | Echo of the resolved grouping: 'product' or 'store'. Check it - an unrecognised groupBy value is silently normalised to 'product' here rather than rejected. |
| `products` | array | Up to 500 rows, ordered by volumeCents desc, then (v3.9.13) rebillVolumeCents desc, then key. No pagination. v3.9.9 - by product the charges no basket names are NOT here: they are `noBasket`; sum of rows + noBasket = `totals`. v3.9.13 - the money adds up EXACTLY: by product each money column is allocated to the rows by largest remainder (db/productMetrics apportionSql), so sum of rows + noBasket = `totals` to the cent (+ `rejections3ds` on threeDsFeeCents / netCents) and each row is within 1 cent of its own exact pro-rata share; netCents = grossCents - its parts, so sum of Net is exact too. The allocation covers every row BEFORE the 500-row cap: the returned rows add up only when none is cut. |
| `products[].key` | string | Grouping identity - the /transactions filter VALUE of the row (v3.9.9). product: `<store host>\|<product ref>` (txFilters productKeySql - the list's `productKey`; a line with no identity reads `<host>\|(unknown)`, the list's own value). store: the list's store bucket - the host of the charge's storefront (else its originating sale's), '(direct)' without one (`storefront=`). |
| `products[].name` | string \| null | Product name (the window's lines, else the account's basket history). By store: the host. |
| `products[].slug` | string \| null | Product slug. ALWAYS null in store mode. |
| `products[].url` | string \| null | The product page on THIS store. By store: https://<host> (null for '(direct)'). |
| `products[].storefrontUrl` | string \| null | By product: the basket lines' storefront_url (max). By store: https://<host> (null for '(direct)'). |
| `products[].charges` | number | DISTINCT straight (not rebillSql) LIVE charges created in the window whose order's basket names the row (by store: of the store bucket). `productKey=<key>&source=sale,recovery` opens exactly them. |
| `products[].approved` | number | Distinct straight transactions with status='approved'. |
| `products[].declined` | number | Distinct straight transactions that are declines under v3.9 section 1: status 'declined' or 'error' (TXN_DECLINED_SQL - a technical error is a decline). |
| `products[].approvalRate` | number (ratio 0..1) | approved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out, over the DISTINCT straight transactions of the row). 0 when the base is 0 - never approved / (approved + declined). |
| `products[].volumeCents` | integer cents | v3.9.9 (D2) - the CHARGED amount of the row's approved straight sales, pro-rata by the product's share of its order's basket (by price; a basket whose lines carry no price - a wallet sale - by its lines' count). It was the basket's line totals ($11,070 above the charged straight volume over September 2026). By store: the charges' amounts (share 1). |
| `products[].rebillCharges` | number | Distinct rebill transactions attributed to this product through the original sale's order_id. |
| `products[].rebillApproved` | number | Approved rebill transactions. |
| `products[].rebillDeclined` | number | Rebill transactions that are v3.9 section 1 declines (status 'declined' or 'error'). |
| `products[].rebillApprovalRate` | number (ratio 0..1) | rebillApproved / rebill completed - the same v3.9 section 1 base over the rebill transactions of the row. |
| `products[].rebillVolumeCents` | integer cents | Approved subscription amount x the same share (whole by store). |
| `products[].grossCents` | integer cents | Approved amount (straight + subscription) x the share. sum of rows + noBasket = totals.grossCents = the dashboard's Gross volume - v3.9.13: exactly, to the cent (largest-remainder allocation over the rows). |
| `products[].discountFeeCents` | integer cents | v3.9.6 live fees: the order's discount at its gateway's CURRENT discount_fee_bps (approved orders only - 0 on a decline) x basket share; never the deprecated transactions.discount_fee_cents snapshot. |
| `products[].transactionFeeCents` | integer cents | v3.9.6 live fees: the order's attempts x the attempting MIDs' CURRENT flat fee (every non-skipped authorization, declined ones included) + the wallet provider's per-charge fee on a wallet order, x basket share - the SAME per-attempt definition as /v1/metrics finance.transactionFeeCents (the stored capture-based basis is gone). |
| `products[].reserveCents` | integer cents | v3.9.6 live fees: the order's reserve at its gateway's CURRENT reserve_rate_bps (approved orders only) x basket share. |
| `products[].threeDsFeeCents` | integer cents | v3.9.6 - the 3DS authentication fee of the order (the integration's CURRENT attemptFeeUsd when the charge ran 3DS with a provider) x basket share. |
| `products[].refundCents` | integer cents | v3.9.9 (D1) - the refunds of the window (successful, non-test refunds rows not marked chargeback, DATED BY THE REFUND) on the row's charges - of any date -, their own amounts x the share. |
| `products[].refundCount` | number | v3.9.9 (D1) - the TRANSACTIONS refunded in the window (a chargeback never counts here) - `refund=refund` on /transactions, dated by the refunds row. By product a charge counts on each of its products' rows: the Total is totals.refundCount (distinct). |
| `products[].chargebackCents` | integer cents | v3.9.9 (D1) - the chargebacks of the window (refunds rows marked is_chargeback, dated by that row), their own amounts x the share (it was the charge's amount of the window's sales flagged charged_back). |
| `products[].chargebackCount` | number | v3.9.9 (D1) - the TRANSACTIONS charged back in the window - `refund=chargeback`. |
| `products[].netCents` | integer cents | v3.9.9 (D2) - the dashboard's Net: grossCents - discount - transaction - 3DS - reserve - refunds - refund fees - chargebacks - chargeback fees, from the row's own integer figures (it did not deduct refunds / chargebacks). v3.9.13 - those figures are the largest-remainder allocation, so sum of rows + noBasket = totals.netCents exactly (+ `rejections3ds`); against v3.9.12 a row's Net moves by the sum of its parts' moves (each at most 1 cent). |
| `products[].units` | number | Physical units (sum of quantity) on APPROVED STRAIGHT sales only. DISPLAY ONLY - it never scales any count, rate or volume above, and it excludes rebill units. v3.9.13 - the subscription side has its own field, `rebillUnits`; Units under Both = units + rebillUnits. |
| `products[].rebillUnits` | number | v3.9.13 - the `units` expression over the APPROVED SUBSCRIPTION charges: the basket quantity of the order's lines (a subscription charge reuses its sale's order_id). DISPLAY ONLY, like `units`. 0 on `noBasket` (no basket). The dashboard's Units column under the Subscription tab. The partner /v1/reports/products projects it out. |
| `totals.approvalRate` | number (ratio 0..1) | v3.9 section 1 - approved / completed over the DISTINCT straight orders of the window (the footer's rate; never re-derive it from approved + declined). |
| `totals.rebillApprovalRate` | number (ratio 0..1) | v3.9 section 1 - rebillApproved / rebill completed over the DISTINCT rebill orders of the window. |
| `products[].pilot_spend_cents` | integer \| null | v3.9.3 Pilot - the Pilot spend attributed to the row, at DESTINATION granularity first (D4, v3.9.3 review): groupBy=product -> sum of Pilot's per-landing-URL spend whose key equals the row's `url` normalised (lower-cased host, no scheme / www. / query / trailing slash) - a campaign split 70 / 30 over two URLs lands on BOTH rows with Pilot's figures -, plus the URL-less campaigns whose effective target is that URL; groupBy=store -> the row's host through the Store table's alias fold (pay.<shop> / www.<shop> receive the spend of <shop>; the row with the most volume when several). null when the Pilot integration is inactive, the row has no url, nothing is mapped to it or the spend is 0. Read from pilot_spend_daily for the same window (calendar days in `tz`), ONE statement; a failed read answers pilot { active: true, reason: 'Pilot read failed: <code>' } and null rows. v3.9.4 (docs/PILOT.md section 4.3): groupBy=product matches the row's `url` normalised (percent-decoded) EXACTLY first; else, for a landing URL that is a product page (/products/<slug>), the rows whose STORE (storefrontUrl) shares the landing URL's registrable host and whose slug is the same - a Shopify product URL the checkout stores on its myshopify.com host (frp05g-us.myshopify.com/products/volt-vogue) still receives the ads landing on the shop's own domain (hoomagoods.com/products/volt-vogue) sold on the alias pay.hoomagoods.com; several rows on one identity -> the one with the most volume. A store-level landing page (/collections/all) reaches the Store row only. Pilot's real byProduct keys are `host::slug` (the landing URL is the stored name) - read as URLs they matched nothing before v3.9.4. |
| `products[].straight_roas` | number \| null | v3.9.3 Pilot - volumeCents / pilot_spend_cents, 4 decimals; null without spend. v3.9.9 - volumeCents is the charged amount, so the Total (sum of revenue of every row incl. the reconciling ones / sum of spend incl. the spend on no row, dashboard side) is the Straight ROAS card. |
| `pilot` | object | v3.9.3 Pilot - { active, reason, spend_cents (the range's total, ignored campaigns excluded), product_spend_cents (sum of products[].pilot_spend_cents - the table's spend total), synced_through, timezone }; the same semantics as GET /v1/metrics `pilot`. v3.9.4 - the live refresh (docs/PILOT.md section 3.1): the read re-reads TODAY (+ yesterday before 06:00 in the report tz) from Pilot's /api/live-report/day BEFORE the side tables are read - at most once per 60 s per account (the stored synced_at of today's total rows is the clock, shared by every instance), one refresh in flight per account, a 4 s budget past which the stored numbers are served and the refresh completes in the background; never a failure of the read. Three more fields: refreshed_at: ISO \| null (the account's last live read of today / yesterday - the stored synced_at; null before the first, or while inactive), stale: boolean (this call did NOT refresh within the window: the budget passed, a Pilot error, a sync pass on the account - or no refresh was run; false while inactive: nothing to refresh), refresh_reason: string \| null ('Pilot did not answer within 4000 ms - refreshing in the background' \| 'UNAUTHENTICATED (401)' and the other typed Pilot codes \| 'a sync pass is on the account' \| the migration-163 sentence; null when refreshed or already fresh). `reason` keeps answering "why N/A"; `stale` answers "were these figures refreshed from Pilot just now". The same 60 s window as GET /v1/metrics: a dashboard load that already refreshed answers fresh without a Pilot call. |
| `products[].blended_roas` | number \| null | v3.9.9 Pilot - (volumeCents + rebillVolumeCents) / pilot_spend_cents, 4 decimals: the row's straight + subscription revenue over its spend (the Blended ROAS card's numerator); null without spend. The Total row recomputes sum of the matched rows' revenue / sum of their spend (dashboard side). |
| `products[].cost_per_sale_cents` | integer \| null | v3.9.9 Pilot - pilot_spend_cents / approved (the row's approved straight sales), rounded to the cent; null without spend or without a sale. |
| `products[].net_after_ad_spend_cents` | integer \| null | v3.9.9 Pilot - netCents - pilot_spend_cents (the net itself on a row with no attributed spend) while the range holds Pilot data (pilot.active and pilot.reason null); null otherwise - the Financial report's store rule. |
| `products[].pilot_campaigns` | integer \| null | v3.9.9 Pilot - the number of distinct campaigns ACTIVE on the row over the range: the campaigns Pilot lists under the row's destination(s) on the days both spent (a campaign's own row of that day with spend > 0), plus the campaigns no destination names whose effective target is the row - exactly the campaigns its pilot_spend_cents comes from (a manual target moves a campaign with its spend). null when the row has no spend (and while migration 169 is missing). A lower bound while pilot.links_partial. |
| `products[].pilot_accounts` | integer \| null | v3.9.9 Pilot - the number of distinct TikTok ad accounts (advertiser ids) of those campaigns; null with the spend. |
| `products[].pilot_campaign_ids` | string[] \| null | v3.9.9 Pilot - the keys behind pilot_campaigns, most range spend first: the TikTok campaign id, or `name:<advertiser id>:<lower-cased name>` for a name Pilot listed that matched no campaign id that day. Named in pilot.links.campaigns. A Total of the column is the DISTINCT count over the rows, never their sum. |
| `products[].pilot_account_ids` | string[] \| null | v3.9.9 Pilot - the advertiser ids behind pilot_accounts, most range spend first; named in pilot.links.accounts. |
| `pilot.unattributed_cents` | integer | v3.9.9 Pilot - spend of campaigns with no bucket (no effective target, not named by a destination) + named campaigns' spend their destinations do not cover (URL-less ads). |
| `pilot.unmatched_cents` | integer | v3.9.9 Pilot - attributed spend that no row of THIS table carries (a store-level landing page on the product grouping, a URL / host with no row in the range). spend_cents - product_spend_cents = unattributed_cents + unmatched_cents within Pilot's own rounding: Reports > Products shows it as its reconciling row so the Pilot Spend Total equals the card. |
| `pilot.links` | object | v3.9.9 Pilot - { campaigns: { <key>: { name, account_id, spend_cents } }, accounts: { <advertiser id>: { name, spend_cents } } }: the names behind the rows' pilot_campaign_ids / pilot_account_ids (only the keys some row carries); spend_cents = the range's spend (null for a name-only campaign). |
| `pilot.days_unlinked` | integer | v3.9.9 Pilot - synced days of the range whose campaign links are not stored yet (written before v3.9.9 and not relinked yet - the hourly sync relinks 15 per pass, newest first; every synced day while migration 169 is missing). |
| `pilot.links_partial` | boolean | v3.9.9 Pilot - true while days_unlinked > 0 or migration 169 is missing: every count is then a LOWER bound (the dashboard reads it ">= n"), never a silently low number. |
| `products[].completed` | number | v3.9.9 - the straight AR base (live and completed) of the row; approvalRate = approved / completed. |
| `products[].rebillCompleted` | number | v3.9.9 - the subscription AR base of the row. |
| `products[].refundFeesCents` | integer cents | v3.9.9 - the refunds' fees (the refunded charge's gateway, CURRENT per-brand fee, db/fees gatewayRefundFeeSql per refunds row) x the share. |
| `products[].chargebackFeesCents` | integer cents | v3.9.9 - the chargebacks' fees x the share. |
| `noBasket` | object \| null | v3.9.9 (D2) - groupBy=product: the reconciling row (key `__no_product_basket__`, name "(no product basket)"): the window's live charges and refund events whose order no basket line of the account names (orphan rebills, rebills of sales older than the basket capture), in the row shape (+ its Pilot fields: no spend). No /transactions filter reads "no basket": its counts are plain text. null by store and when empty. |
| `winners` | object | v3.9.9 (D2) - with winners=1: { straight, rebill } each { keys: the rows in rank order, charges, approved, declined, completed: DISTINCT over the orders whose basket names ANY of the keys - what `productKey=<the keys>` opens (a charge carrying two winning products is ONE sale) }. |
| `totals.charges` | number | Every live straight charge of the window (with or without a basket) - the dashboard's Straight charges. |
| `totals.approved / declined / completed` | number | The straight halves of the Success / Declines cards and the AR base. |
| `totals.volumeCents` | number | v3.9.9 - sum of the approved straight amounts (exact) = the dashboard's Straight gross. |
| `totals.rebill*` | number | The subscription charges' counts and approved amount (the Subscription half). |
| `totals.rebillUnits` | number | v3.9.13 - the units of the window's approved subscription charges, each charge's basket counted once (the account's figure, like totals.units on the straight side). |
| `totals.grossCents ... chargebackFeesCents, netCents` | number | v3.9.9 - the Breakdown's money Total: per transaction, exact. v3.9.13 - sum of rows + noBasket (+ `rejections3ds` on threeDsFeeCents / netCents) = these EXACTLY, to the cent: the rows' money is allocated by largest remainder (it differed by the rows' own rounding, a few cents). |
| `totals.refundCount / chargebackCount` | number | v3.9.9 (D1) - the distinct refunded / charged-back transactions of the window = the dashboard's Refunds / Chargebacks cards = `refund=refund` / `refund=chargeback`. |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: an unknown parameter (strict catalog; `bucket` and `atriView` are not parameters here), an unknown closed-vocabulary value, groupBy outside product | store, winners other than 1, hours outside 1..8760, a malformed from / to, an unknown tz, a reversed range pair, a value over its max length; `Invalid report timezone` when the account's stored timezone is invalid. `Synchronous reports support at most 400 days. Use report jobs for larger ranges.` when the resolved window is longer than 400 days (one hour of tolerance); use POST /v1/metrics/jobs with kind=products. The gate also refuses a malformed or foreign `affiliate` / `flow` filter (`Invalid affiliate filter`, `Unknown affiliate filter`, `Invalid flow filter`, `Unknown flow filter`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). The database is temporarily unavailable (Retry-After: 1) when this API process already runs its 4 reporting reads and 40 more are waiting.
- `504` The request took too long and was cancelled (the 25-second budget, queue time included, was exceeded); retry, narrow the range or use POST /v1/metrics/jobs with kind=products.

**Gotchas**

- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- v3.9.15 - `groupBy`, `winners` and `side` are declared now (they were read outside the schema); `side` is accepted and ignored (the dashboard's context).
- v3.9.15 - every catalog key applies (pickFilters: status, atri, accountId, country, brand, ... - the same clauses as the /transactions list), on the window's charges, the refund events' transactions and the Winners statement. `bucket` and `atriView` are not parameters of this route: a 400.
- v3.9.15 - `groupBy` is validated (product | store; anything else is a 400); read `groupBy` back off the response.
- v3.9.9 (D1) - Refunds and chargebacks are EVENTS of the window (dated by the refunds row), not the window's sales later flagged refunded: a row can show refunds with 0 charges (a sale of an earlier day refunded now). Link them with /transactions `refund=refund` / `refund=chargeback` (their from / to then read the refund date) - never `refunded=true` (the state flag, chargebacks included, charge date) nor `status=chargeback`.
- v3.9.9 - the refund / CB RATES (dashboard side) are events of the period / approved charges of the period (straight + subscription), not a cohort propensity.
- By product a multi-product order sits on each of its products' rows: counts do not sum across rows - use `totals` (distinct). Money is pro-rata and does add up: + noBasket = totals EXACTLY (v3.9.13 - largest-remainder allocation; each row within 1 cent of its own exact share). Sum the returned integer cents; never re-derive a row from the shares.
- v3.9.13 - exact cents: by product each money column (volumeCents, rebillVolumeCents, grossCents, every fee, refundCents, refundFeesCents, chargebackCents, chargebackFeesCents) is summed UNROUNDED per row, then allocated to integer cents over every row at once: each row takes the floor of its exact share, the rows with the largest fractions (ties by key) one cent more, as many as the column's total needs. A row's money column can therefore differ by 1 cent from v3.9.12 (each row rounded on its own, a few cents off in total: -2 cents Volume on 2026-09-26), its netCents by the sum of its parts' moves. By store nothing changes (whole charges, share 1).
- v3.9.9 - `totals` are the account's figures, not the sum of the returned rows: they include the noBasket charges (product view) and every charge of the window.
- Window resolution differs from /v1/metrics: end = to ?? now, start = from ?? (end - hours).
- Hard cap of 500 rows (default limit), ordered by approved straight volume desc, then (v3.9.13) approved subscription volume desc, then key; no pagination.
- Only basket lines captured since migration 075 exist; before that every charge lands on the noBasket row (by product) - never lost from the totals any more.
- `units` and (v3.9.13) `rebillUnits` are the only quantity-based numbers (approved straight / approved subscription lines, display only).
- Money fields are integer cents, every *Rate a 0..1 ratio; figures arrive as JSON numbers.
- The rebill classification is the shared rebillSql classifier (v3.9.3) - the dashboard cards' split and the /transactions `source` filter agree with it.
- v3.9.11 - under `source` one side is gone from every row: source=straight zeroes the rebill* fields, source=subscription the straight ones (charges / approved / declined / completed / volumeCents / units) - the dashboard then hides that side's columns (and, under Subscription, the Pilot block: the ad spend buys the first sale). The money fields follow the filter. A drill-down sends the column's own side INTERSECTED with the filter (a Straight count under source=sale: source=sale).
- Friendlies are excluded from ordinary approval rates, gross/net figures and Pilot ROAS. Both covers Straight and Subscription. Friendlies are shown through their own metrics and columns.
- friendliesApprovalRate is null. Friendlies counts, approved volume and attempt costs remain separate from ordinary product financial totals.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- When tz is omitted, this report uses the effective account timezone, matching background report preparation. Trailing-hour windows keep that timezone for their labels and calendar-dependent calculations.
- Exception to the Friendlies exclusion: with the unified filter source=friendlies (exactly that value) on an account whose Friendlies integration is active, the money columns - grossCents, discount, transaction / reserve / 3DS fees, refunds, chargebacks and their fees - describe the Friendlies sales instead of the ordinary ones. The ordinary counts (charges, approved, volumeCents, units) are then 0 and the Friendlies counts stay in the friendlies* columns. Without the integration, Friendlies-tagged transactions are excluded from every figure.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. A window longer than 400 days is refused with 400. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=products for a longer range.

#### Affiliates

The per-affiliate report.

- From `GET /v1/affiliates/report` (`groupBy=affiliate`): Approval rate = approved / transactions; Refund rate = refundedTransactions / approved; Chargeback rate = chargebackTransactions / approved; AOV = (initial + upsell revenue) / initial paid orders, rebills excluded. Totals sum the counts per currency (an affiliate appears once per currency).

##### `GET /v1/affiliates/report`

**Scope** `reports.read` - **Read the per-affiliate report**

Affiliate-centred report over canonical V5 payments: transaction counts, cohort refund and chargeback incidence, event-dated revenue (initial, upsell, rebill), refunds, chargebacks, signed affiliate cuts and net, one row per affiliate (or checkout / store) and currency, plus the same rows per day.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | ISO-8601 instant or YYYY-MM-DD | **yes** | Inclusive start. A bare day is read in tz (its first millisecond). |
| `to` | ISO-8601 instant or YYYY-MM-DD | **yes** | Inclusive end. A bare day is read in tz (its last millisecond). At most 366 days after from. |
| `tz` | IANA timezone, at most 64 characters; default `the account timezone` | no | Clock used for bare days and for the `day` of the daily rows. |
| `groupBy` | affiliate \| checkout \| store; default `affiliate` | no | Second grouping axis next to the affiliate: none (affiliate), the checkout at sale, or the store (No store for standalone). |
| `affiliate` | CSV of affiliate UUIDs and/or none | no | Affiliates from the immutable payment attribution; none selects payments without an affiliate. Unknown or foreign IDs are rejected. |
| `flow` | CSV of flow UUIDs and/or none | no | Flows from the immutable checkout session version; none selects direct checkout. Unknown or foreign IDs are rejected. |
| `checkout` | CSV of checkout UUIDs and/or none | no | Checkouts at sale; none selects unattributed or legacy payments. |
| `storefront` | CSV of store hosts, or __no_store__ | no | Store host bucket; __no_store__ selects standalone payments without a store. |
| `currency` | CSV of 3-letter currency codes | no | Original transaction currencies. Nothing is converted. |
| `hour` | CSV of integers 0..23, max 200 | no | Filter catalog, Date: CSV of hours 00-23 in tz (needs tz). Needs a valid tz: an hour without one is a 400 `hour needs a valid tz`. |
| `status` | CSV enum | no | Filter catalog, Transaction: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `source` | CSV enum, max 100 | no | Filter catalog, Transaction: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. An unknown value is a 400 naming it. |
| `pass` | CSV enum, max 40 | no | Filter catalog, Transaction: initial / cascade. Allowed values: initial, cascade. An unknown value is a 400 naming it. |
| `method` | CSV enum, max 40 | no | Filter catalog, Transaction: card / wallet / wire. Allowed values: card, wallet, wire. An unknown value is a 400 naming it. |
| `population` | CSV enum, max 40 | no | Filter catalog, Transaction: live / test / imported (reports: live only). Allowed values: live, test, imported. An unknown value is a 400 naming it. |
| `credentialMode` | CSV enum, max 20 | no | Filter catalog, Transaction: Wire: mit / cit. Allowed values: mit, cit. An unknown value is a 400 naming it. |
| `threeDs` | CSV enum | no | Filter catalog, Transaction: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. An unknown value is a 400 naming it. |
| `declineCategory` | string, max 1000 | no | Filter catalog, Transaction: Decline-engine category. |
| `declineSeverity` | CSV enum, max 40 | no | Filter catalog, Transaction: soft / hard. Allowed values: soft, hard. An unknown value is a 400 naming it. |
| `amountMin` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount >= (cents). |
| `amountMax` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount <= (cents). |
| `gatewayTxnId` | string, max 4000 | no | Filter catalog, Transaction: Gateway transaction id (exact, CSV). |
| `authCode` | string, max 1000 | no | Filter catalog, Transaction: Auth code of any attempt (exact, CSV). |
| `descriptor` | string, max 128 | no | Filter catalog, Transaction: Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum | no | Filter catalog, Transaction: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. An unknown value is a 400 naming it. |
| `product` | string, max 4000 | no | Filter catalog, Transaction: Basket product name / slug / ref. |
| `productSlug` | string, max 4000 | no | Filter catalog, Transaction: Basket product slug. |
| `productKey` | string, max 4000 | no | Filter catalog, Transaction: Product per store: <host>\|<ref>. |
| `accountId` | CSV of MID uuids, wallet:<uuid>, wire:<uuid> or none, max 4000 | no | Filter catalog, Routing: Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string, max 100 | no | Filter catalog, Routing: a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Any category of the final MID (ids). |
| `primaryCategory` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Primary category of the final MID (ids). |
| `atri` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI reached (ids). |
| `atriFinal` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI the order ended on (ids). |
| `processor` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Processor ids, none. |
| `acquiringBank` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Acquiring bank ids, none. |
| `company` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Company ids, none. |
| `gatewayMcc` | string, max 1000 | no | Filter catalog, Routing: Final MID MCC. |
| `gatewayBin` | string, max 1000 | no | Filter catalog, Routing: Final MID acquirer BIN. |
| `brand` | string, max 200 | no | Filter catalog, Card: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string, max 100 | no | Filter catalog, Card: APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string, max 200 | no | Filter catalog, Card: Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string, max 200 | no | Filter catalog, Card: bin_info card type (or a wallet). |
| `cardLevel` | string, max 4000 | no | Filter catalog, Card: bin_info card level (or a wallet). |
| `issuer` | string, max 4000 | no | Filter catalog, Card: Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay, max 4000 | no | Filter catalog, Card: CSV of 6-digit BINs or a wallet label. |
| `first6` | string of 1..6 digits | no | Filter catalog, Card: Card prefix (1-6 digits). |
| `last4` | string of 1..4 digits | no | Filter catalog, Card: Card suffix (1-4 digits). |
| `country` | string, max 2000 | no | Filter catalog, Customer: Billing country (ISO-2, inherited from the sale). |
| `traffic` | string, max 2000 | no | Filter catalog, Customer: Traffic source, (direct/organic). |
| `utmSource` | string, max 4000 | no | Filter catalog, Customer: UTM source (case-insensitive). |
| `utmCampaign` | string, max 4000 | no | Filter catalog, Customer: UTM campaign (case-insensitive). |
| `device` | string, max 200 | no | Filter catalog, Customer: Mobile / Tablet / Desktop. |
| `os` | string, max 200 | no | Filter catalog, Customer: Operating system. |
| `browser` | string, max 200 | no | Filter catalog, Customer: Browser. |
| `ipType` | CSV enum, max 40 | no | Filter catalog, Customer: IPv4 / IPv6. Allowed values: IPv4, IPv6. An unknown value is a 400 naming it. |
| `ip` | string, max 2000 | no | Filter catalog, Customer: CSV of client IPs. |
| `email` | string, max 200 | no | Filter catalog, Customer: E-mail contains. |
| `phone` | string, max 40 | no | Filter catalog, Customer: Phone contains. |
| `firstName` | string, max 120 | no | Filter catalog, Customer: First name contains. |
| `lastName` | string, max 120 | no | Filter catalog, Customer: Last name contains. |
| `customerEmail` | CSV of e-mails, max 4000 | no | Filter catalog, Client: Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum, max 200 | no | Filter catalog, Client: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. An unknown value is a 400 naming it. |
| `clientBlacklisted` | enum | no | Filter catalog, Client: Blacklisted (e-mail or card). Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientLiveSub` | enum | no | Filter catalog, Client: Has a live (active / paused) subscription. Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientOrdersMin` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders >=. |
| `clientOrdersMax` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders <=. |
| `clientLtvMin` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value >= (cents). |
| `clientLtvMax` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value <= (cents). |
| `clientFirstFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen from. |
| `clientFirstTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen to. |
| `clientLastFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen from. |
| `clientLastTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen to. |
| `subscription` | CSV of uuids, max 4000 | no | Filter catalog, Subscription: Subscription product ids. |
| `cycle` | CSV of integers 0..999, max 200 | no | Filter catalog, Subscription: Charge cycle (0 = the straight sale). |
| `cycleMin` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle >=. |
| `cycleMax` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle <=. |
| `engine` | CSV enum, max 60 | no | Filter catalog, Subscription: subscription / legacy / external. Allowed values: subscription, legacy, external. An unknown value is a 400 naming it. |
| `subStatus` | CSV enum | no | Filter catalog, Subscription: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. An unknown value is a 400 naming it. |
| `attachedBy` | CSV enum, max 60 | no | Filter catalog, Subscription: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. An unknown value is a 400 naming it. |
| `due` | enum | no | Filter catalog, Subscription: Next charge: overdue / 24h / 7d. Allowed values: overdue, 24h, 7d. An unknown value is a 400 naming it. |
| `endCause` | string, max 1000 | no | Filter catalog, Subscription: End cause. |
| `subCreatedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created from. |
| `subCreatedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created to. |
| `subEndedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended from. |
| `subEndedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended to. |
| `schedule` | CSV of uuids, max 4000 | no | Filter catalog, Schedule: Schedule (day) ids. |
| `scheduleStatus` | CSV enum | no | Filter catalog, Schedule: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. An unknown value is a 400 naming it. |
| `scheduleType` | CSV enum, max 60 | no | Filter catalog, Schedule: subscription / auto / manual. Allowed values: subscription, auto, manual. An unknown value is a 400 naming it. |
| `dayFrom` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum | no | Filter catalog, Schedule: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. An unknown value is a 400 naming it. |
| `entryReason` | string, max 4000 | no | Filter catalog, Schedule: Charge reason (decline reason of the entry). |
| `refund` | CSV enum, max 100 | no | Filter catalog, Refund: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `refundBasis` | enum | no | Filter catalog, Refund: Refund event dated by refund (default) / charge. Allowed values: refund, charge. An unknown value is a 400 naming it. |
| `refunded` | CSV enum, max 20 | no | Filter catalog, Refund: Refunded state flag. Allowed values: true, false. An unknown value is a 400 naming it. |
| `refundStatus` | CSV enum, max 80 | no | Filter catalog, Refund: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. An unknown value is a 400 naming it. |
| `refundTest` | enum | no | Filter catalog, Refund: Test refunds: exclude (= absent) / include / only. Allowed values: exclude, include, only. An unknown value is a 400 naming it. |
| `q` | string, max 200 | no | Filter catalog, Search: The page's identity search. Accepted by the strict catalog; identity search of list pages. |

**Response**

```json
{
  "groupBy": "affiliate",
  "rows": [
    {
      "affiliateId": "11111111-1111-4111-8111-111111111111",
      "name": "Example Partner",
      "publicId": "partner-42",
      "assetId": null,
      "assetName": null,
      "assetFilter": null,
      "currency": "USD",
      "day": null,
      "transactions": 4,
      "approved": 3,
      "declined": 1,
      "unknown": 0,
      "orders": 1,
      "refundedTransactions": 1,
      "chargebackTransactions": 0,
      "initialMinor": "5499",
      "upsellMinor": "2900",
      "rebillMinor": "1000",
      "grossMinor": "9399",
      "refundMinor": "1500",
      "chargebackMinor": "0",
      "cutAccruedMinor": "2520",
      "cutReversedMinor": "-450",
      "cutCorrectionMinor": "75",
      "cutsMinor": "2145",
      "netMinor": "5754"
    }
  ],
  "days": [
    {
      "affiliateId": "11111111-1111-4111-8111-111111111111",
      "name": "Example Partner",
      "publicId": "partner-42",
      "assetId": null,
      "assetName": null,
      "assetFilter": null,
      "currency": "USD",
      "day": "2026-10-14",
      "transactions": 4,
      "approved": 3,
      "declined": 1,
      "unknown": 0,
      "orders": 1,
      "refundedTransactions": 1,
      "chargebackTransactions": 0,
      "initialMinor": "5499",
      "upsellMinor": "2900",
      "rebillMinor": "1000",
      "grossMinor": "9399",
      "refundMinor": "1500",
      "chargebackMinor": "0",
      "cutAccruedMinor": "2520",
      "cutReversedMinor": "-450",
      "cutCorrectionMinor": "75",
      "cutsMinor": "2145",
      "netMinor": "5754"
    }
  ],
  "from": "2026-10-01T00:00:00.000Z",
  "to": "2026-10-31T23:59:59.999Z",
  "timezone": "UTC",
  "basis": "Canonical V5 payments only. Amounts use event dates; initial, upsell and rebill captures. Net after refunds, chargebacks and affiliate cuts, before processing fees. No currency conversion.",
  "rateBasis": "Refund and chargeback rates count unique captured, approved transactions created in the selected period, with a positive reversal recorded by period end, divided by approved transactions in that same cohort. Partial reversals count once. Chargeback corrections do not erase historical incidence. Totals use summed counts, separately by currency."
}
```

| response field | type | description |
|---|---|---|
| `groupBy` | string | Echo of the grouping. |
| `rows` | object[] | Period rows (day null). |
| `days` | object[] | Daily rows (day YYYY-MM-DD in tz). |
| `rows[].affiliateId / name / publicId` | uuid \| null, string, string \| null | Affiliate identity; null ID with name No affiliate for unattributed payments. |
| `rows[].assetId / assetName / assetFilter` | string \| null | Checkout or store of the row for groupBy checkout or store (assetFilter is the value to pass back as the checkout or storefront filter); null for groupBy affiliate. |
| `rows[].currency` | string | Transaction currency of the row. |
| `rows[].transactions / approved / declined / unknown` | integer | Transactions created in the window and their outcome (declined includes errors). |
| `rows[].orders` | integer | Distinct initial orders captured in the window. |
| `rows[].refundedTransactions / chargebackTransactions` | integer | Cohort incidence: approved transactions of the window with a positive refund or chargeback by period end, each counted once. |
| `rows[].initialMinor / upsellMinor / rebillMinor / grossMinor` | string | Captured amounts by kind and their sum. |
| `rows[].refundMinor / chargebackMinor` | string | Reversals dated in the window (chargeback net of corrections). |
| `rows[].cutAccruedMinor / cutReversedMinor / cutCorrectionMinor / cutsMinor` | string | Cut ledger by kind and the signed total. |
| `rows[].netMinor` | string | Gross minus refunds, chargebacks and cuts. |
| `from / to / timezone` | string | The window actually read and the clock. |
| `basis / rateBasis` | string | Plain-language definitions of the amounts and of the incidence counts. |

**Errors**

- `400` `Select at most 366 days`; `Invalid affiliate filter`, `Unknown affiliate filter`, `Invalid flow filter` or `Unknown flow filter` for a malformed, unknown or foreign affiliate or flow ID. `Invalid request` with `details.issues` (one {path, code, message} per problem) when the query fails validation: missing from or to, unknown key, unknown value of a closed vocabulary, unknown tz, reversed pair.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module; `Forbidden` when the request carries an affiliate portal cookie.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).
- `504` `The request took too long and was cancelled` (the database timeout message, which goes on to advise a narrower range) when the read passes its 25-second budget, which includes the wait for a reporting connection. Retry or narrow the range.

**Gotchas**

- Rows are ordered by affiliate name, then currency. `rows` holds the period totals (day null); `days` holds the same grouping per calendar day in tz.
- Every *Minor amount is a signed integer string in minor units. netMinor = grossMinor - refundMinor - chargebackMinor - cutsMinor, before processing fees. Currencies are never added together.
- Transaction counts use creation time; captures, reversals and cuts use their own event dates, so an old sale refunded in the window still contributes its refund.
- Only canonical V5 payments are included; tests, imports and pre-gateway refusals are excluded. Payments without an affiliate appear as name `No affiliate`.
- The report returns raw counts only. Rates are yours to compute: approval = approved / transactions, refund rate = refundedTransactions / approved, chargeback rate = chargebackTransactions / approved; for totals, sum the counts per currency first and never average row rates. A rate with approved = 0 is undefined.
- Money follows the caller's tenancy and ATRI grants. The read runs on the reporting pool in one read-only snapshot with a 25-second budget (504 past it).

#### Traffic

The traffic report by dimension (acquisition, devices, geography, time), also used by the Gateways, BINs and Products report tabs.

- Share = row charges / table total; table Total = sum of the rows + `tail`. The API returns per-row rates, `excluded`, `tail` and the window `summary`.

##### `GET /v1/metrics/traffic`

**Scope** `reports.read` - **Traffic report by dimension**

Reports > Traffic: every dimension of one [from, to] window cut from the same live rows in one statement (source, traffic source, storefront, device, browser, OS, IP type, hour, card brand, funding, level, issuer, BIN, gateway, gateway type, category, ATRI, processor, acquiring bank, company, gateway MCC and BIN, 3DS, country, price point, checkout, subscription product, currency), each row with orders, approved, declined, completed, refund and chargeback events, gross volume and the derived rates, plus the window summary. Every filter of GET /v1/transactions narrows the whole report, and each row's key is the filter value that reproduces it in GET /v1/transactions. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | **yes** | Window start, inclusive. A bare day is read in tz (its first millisecond). |
| `to` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | **yes** | Window end, inclusive. A bare day is read in tz (its last millisecond). At most 400 days after from. |
| `tz` | string (IANA timezone, max 64) | no | Timezone the days of from / to, the Hour dimension and the hour filter are read in. Defaults to the account timezone. |
| `dims` | CSV string (max 500) | no | Dimensions to compute, any of: source, traffic, storefront, device, browser, os, ipType, hour, brand, funding, level, issuer, bin, gateway, gatewayType, category, atri, processor, acquiringBank, company, gatewayMcc, gatewayBin, threeDs, geo, pricePoint, checkout, subscription, currency. Omitted or empty = all of them. |
| `hour` | CSV of hours 0-23 (max 200) | no | CSV of hours 00-23 in tz (needs tz). Requires a valid tz. |
| `status` | CSV enum: approved \| failed \| declined \| error \| unknown \| pending \| duplicate \| completed \| chargeback \| rdr \| ethoca | no | Charge status (failed = declined + error, completed = with an outcome). |
| `source` | CSV enum: sale \| rebill \| recovery \| pre-auth \| friendlies \| straight \| subscription \| upsell | no | straight (sale + recovery) / subscription (rebill), or the raw buckets. |
| `pass` | CSV enum: initial \| cascade | no | initial / cascade. |
| `method` | CSV enum: card \| wallet \| wire | no | card / wallet / wire. |
| `population` | CSV enum: live \| test \| imported | no | live / test / imported (reports: live only). |
| `credentialMode` | CSV enum: mit \| cit | no | Wire: mit / cit. |
| `threeDs` | CSV enum: applied \| applied-other \| attempted \| reserved \| holdout \| excluded \| rule \| none \| not-run \| frictionless \| challenge \| attempt \| data-only | no | 3DS outcome. |
| `declineCategory` | CSV string (max 1000) | no | Decline-engine category. |
| `declineSeverity` | CSV enum: soft \| hard | no | soft / hard. |
| `amountMin` | integer string, cents (1-12 digits) | no | Amount >= (cents). |
| `amountMax` | integer string, cents (1-12 digits) | no | Amount <= (cents). Must not be below amountMin. |
| `currency` | CSV of 3-letter codes (max 200) | no | ISO-4217 currency. |
| `gatewayTxnId` | CSV string (max 4000) | no | Gateway transaction id (exact, CSV). |
| `authCode` | CSV string (max 1000) | no | Auth code of any attempt (exact, CSV). |
| `descriptor` | string (max 128) | no | Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum: 1. < $25 \| 2. $25-49 \| 3. $50-74 \| 4. $75-99 \| 5. $100-149 \| 6. $150-199 \| 7. $200+ | no | Price bucket. |
| `product` | CSV string (max 4000) | no | Basket product name / slug / ref. |
| `productSlug` | CSV string (max 4000) | no | Basket product slug. |
| `productKey` | CSV string (max 4000) | no | Product per store: <host>\|<ref>. |
| `accountId` | CSV of gateway UUIDs, wallet:<uuid>, wire:<uuid> or none (max 4000) | no | Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of UUIDs | no | Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | CSV string (max 100) | no | a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of UUIDs | no | Any category of the final MID (ids). |
| `primaryCategory` | CSV of UUIDs | no | Primary category of the final MID (ids). |
| `atri` | CSV of UUIDs | no | ATRI reached (ids). |
| `atriFinal` | CSV of UUIDs | no | ATRI the order ended on (ids). |
| `processor` | CSV of UUIDs or none | no | Processor ids, none. |
| `acquiringBank` | CSV of UUIDs or none | no | Acquiring bank ids, none. |
| `company` | CSV of UUIDs or none | no | Company ids, none. |
| `gatewayMcc` | CSV string (max 1000) | no | Final MID MCC. |
| `gatewayBin` | CSV string (max 1000) | no | Final MID acquirer BIN. |
| `brand` | CSV string (max 200) | no | Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | CSV string (max 100) | no | APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | CSV string (max 200) | no | Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | CSV string (max 200) | no | bin_info card type (or a wallet). |
| `cardLevel` | CSV string (max 4000) | no | bin_info card level (or a wallet). |
| `issuer` | CSV string, RFC 4180 quoting (max 4000) | no | Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay (max 4000) | no | CSV of 6-digit BINs or a wallet label. |
| `first6` | string (1-6 digits) | no | Card prefix (1-6 digits). |
| `last4` | string (1-4 digits) | no | Card suffix (1-4 digits). |
| `country` | CSV of ISO-2 codes (max 2000) | no | Billing country (ISO-2, inherited from the sale). |
| `storefront` | CSV string (max 4000) | no | Store host bucket, (direct). |
| `traffic` | CSV string (max 2000) | no | Traffic source, (direct/organic). |
| `utmSource` | CSV string (max 4000) | no | UTM source (case-insensitive). |
| `utmCampaign` | CSV string (max 4000) | no | UTM campaign (case-insensitive). |
| `device` | CSV string (max 200) | no | Mobile / Tablet / Desktop. |
| `os` | CSV string (max 200) | no | Operating system. |
| `browser` | CSV string (max 200) | no | Browser. |
| `ipType` | CSV enum: IPv4 \| IPv6 | no | IPv4 / IPv6. |
| `ip` | CSV string (max 2000) | no | CSV of client IPs. |
| `email` | string (max 200) | no | E-mail contains. |
| `phone` | string (max 40) | no | Phone contains. |
| `firstName` | string (max 120) | no | First name contains. |
| `lastName` | string (max 120) | no | Last name contains. |
| `customerEmail` | CSV of e-mails (max 4000) | no | Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum: with-ready \| without-ready \| single \| double \| ready-for-rebill | no | Customer authentication inventory now; single/double count proofs obtained, including used proofs. |
| `clientBlacklisted` | enum: true \| false | no | Blacklisted (e-mail or card). |
| `clientLiveSub` | enum: true \| false | no | Has a live (active / paused) subscription. |
| `clientOrdersMin` | integer string (1-12 digits) | no | Lifetime orders >=. |
| `clientOrdersMax` | integer string (1-12 digits) | no | Lifetime orders <=. Must not be below clientOrdersMin. |
| `clientLtvMin` | integer string, cents (1-12 digits) | no | Lifetime value >= (cents). |
| `clientLtvMax` | integer string, cents (1-12 digits) | no | Lifetime value <= (cents). Must not be below clientLtvMin. |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen from. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | First seen to. |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen from. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Last seen to. |
| `checkout` | CSV of UUIDs or none | no | Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of UUIDs or none | no | Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. |
| `affiliate` | CSV of UUIDs or none | no | Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. |
| `subscription` | CSV of UUIDs | no | Subscription product ids. |
| `cycle` | CSV of integers 0-999 (max 200) | no | Charge cycle (0 = the straight sale). |
| `cycleMin` | integer string (1-6 digits) | no | Charge cycle >=. |
| `cycleMax` | integer string (1-6 digits) | no | Charge cycle <=. Must not be below cycleMin. |
| `engine` | CSV enum: subscription \| legacy \| external | no | subscription / legacy / external. |
| `subStatus` | CSV enum: active \| paused \| failed \| cancelled \| completed \| expired | no | Sub status. |
| `attachedBy` | CSV enum: auto \| manual \| legacy \| optin | no | auto / manual / legacy / optin. |
| `due` | enum: overdue \| 24h \| 7d | no | Next charge: overdue / 24h / 7d. |
| `endCause` | CSV string (max 1000) | no | End cause. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created from. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub created to. |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended from. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD, max 40) | no | Sub ended to. |
| `schedule` | CSV of UUIDs | no | Schedule (day) ids. |
| `scheduleStatus` | CSV enum: scheduled \| processing \| partial \| paused \| done \| cancelled | no | Schedule status. |
| `scheduleType` | CSV enum: subscription \| auto \| manual | no | subscription / auto / manual. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum: scheduled \| processing \| rebill_success \| declined \| blocked \| rebill_failed \| rejected \| cancelled \| missed | no | Charge state of the schedule entry. |
| `entryReason` | CSV string (max 4000) | no | Charge reason (decline reason of the entry). |
| `refund` | CSV enum: refund \| chargeback \| rdr \| ethoca | no | Refund event kind. |
| `refundBasis` | enum: refund \| charge | no | Refund event dated by refund (default) / charge. |
| `refunded` | CSV enum: true \| false | no | Refunded state flag. |
| `refundStatus` | CSV enum: approved \| pending \| declined \| error \| unknown \| cancelled | no | Refund row status. |
| `refundTest` | enum: exclude \| include \| only | no | Test refunds: exclude (= absent) / include / only. |
| `q` | string (max 200) | no | The page's identity search. |

**Response**

```json
{
  "byDimension": {
    "device": [
      {
        "key": "Mobile",
        "name": "Mobile",
        "charges": 8412,
        "approved": 5137,
        "declined": 3180,
        "completed": 8317,
        "refunds": 143,
        "chargebacks": 21,
        "grossCents": 24918700,
        "approvalRate": 0.6177,
        "refundRate": 0.0278,
        "chargebackRate": 0.0041,
        "aovCents": 4851
      },
      {
        "key": "Desktop",
        "name": "Desktop",
        "charges": 3106,
        "approved": 2188,
        "declined": 902,
        "completed": 3090,
        "refunds": 41,
        "chargebacks": 6,
        "grossCents": 11842300,
        "approvalRate": 0.7081,
        "refundRate": 0.0187,
        "chargebackRate": 0.0027,
        "aovCents": 5412
      },
      {
        "key": "Tablet",
        "name": "Tablet",
        "charges": 274,
        "approved": 181,
        "declined": 90,
        "completed": 271,
        "refunds": 4,
        "chargebacks": 1,
        "grossCents": 981400,
        "approvalRate": 0.6679,
        "refundRate": 0.0221,
        "chargebackRate": 0.0055,
        "aovCents": 5422
      }
    ],
    "hour": [
      {
        "key": "14",
        "name": "14",
        "charges": 812,
        "approved": 540,
        "declined": 262,
        "completed": 806,
        "refunds": 12,
        "chargebacks": 2,
        "grossCents": 2619000,
        "approvalRate": 0.67,
        "refundRate": 0.0222,
        "chargebackRate": 0.0037,
        "aovCents": 4850
      },
      "... one row per hour with orders ('00'...'23'), charges desc"
    ],
    "gateway": [
      {
        "key": "3f2b91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
        "name": "ALPHA-01",
        "charges": 4102,
        "approved": 2711,
        "declined": 1360,
        "completed": 4071,
        "refunds": 66,
        "chargebacks": 9,
        "grossCents": 13110400,
        "approvalRate": 0.6659,
        "refundRate": 0.0243,
        "chargebackRate": 0.0033,
        "aovCents": 4836
      },
      "... key = the MID id (the accountId filter value), name = its name"
    ]
  },
  "excluded": {
    "device": 1204,
    "hour": 0,
    "gateway": 402
  },
  "summary": {
    "charges": 12996,
    "approved": 8206,
    "declined": 4652,
    "completed": 12868,
    "approvalRate": 0.6377,
    "grossCents": 40822400,
    "aovCents": 4975,
    "refunds": 197,
    "refundRate": 0.024,
    "chargebacks": 30,
    "chargebackRate": 0.0037
  },
  "tz": "America/New_York",
  "excludedEvents": { "device": { "refunds": 12, "chargebacks": 3 } },
  "tail": { "issuer": { "key": "", "name": "", "rows": 1463, "charges": 11240, "approved": 4402, "declined": 6712, "completed": 11190, "refunds": 164, "chargebacks": 31, "grossCents": 16452300, "approvalRate": 0.3934, "refundRate": 0.0373, "chargebackRate": 0.007, "aovCents": 3737 } }
}
```

| response field | type | description |
|---|---|---|
| `byDimension` | object | One array per REQUESTED dimension key (`dims`, else all 25) - a dimension you did not ask for is absent. Each array holds the top rows of that breakdown ordered by charges desc then key, capped per dimension: issuer 50, level 25, bin 100, every other 30 - v3.9.9: the rows beyond the cap are folded into `tail[dim]`, so sum of rows + tail + excluded = summary. |
| `byDimension.<dim>[].key` | string | The /transactions filter VALUE that reproduces the row under the dimension's filter param (see `dims`): an id (uuid) for gateway (accountId), category, atri, processor, acquiringBank, company; the label itself otherwise - sale / rebill / recovery for `source`, a two-digit hour ('00'..'23'), a price bucket label ('1. < $25'), an upper-cased country code, a 3DS stamp, a six-digit BIN, a store host, a traffic bucket ('(direct/organic)'), a device / OS / browser / funding / brand label, an issuer name (quote it in the CSV when it contains a comma), a card level, an MCC, an acquirer BIN, a gateway type. v3.9.8 item 1 - in the card dimensions (brand, funding, level, issuer, bin) a wallet charge's key is its wallet, 'Apple Pay' / 'Google Pay', and that value is the filter that reproduces the row. v3.9.9 - gateway: the MID id (`accountId`), else a wallet charge's `wallet:<provider id>:<Apple Pay \| Google Pay \| Wallet>` (its wallet provider x wallet, the Payment report's wallet rows - reproduced by `accountId=wallet:<id>&brand=<wallet>`; the catch-all `Wallet` kind has no exact filter); category: the MID's PRIMARY category (`primaryCategory`, not `category`); atri: the ATRI the order ENDED on (`atriFinal`, not the cascade-aware `atri`). |
| `byDimension.<dim>[].name` | string | What the row displays: the gateway / category / ATRI / processor / acquiring bank / company NAME for an id dimension; equals `key` otherwise. v3.9.9 - a wallet gateway row reads "<provider name> - <wallet>". |
| `byDimension.<dim>[].charges` | integer | LIVE orders in the bucket (TXN_LIVE: no test card, no CSV import, no 3DS park; a pre-MID rejection was never a row), ALL statuses (pending / unknown / duplicate included). v3.9.9: created in [from, to] - a transaction the window reaches only through a refund / chargeback event (an older sale) counts 0 here. |
| `byDimension.<dim>[].approved` | integer | Orders with status 'approved' (TXN_APPROVED - the builder never reads is_success). |
| `byDimension.<dim>[].declined` | integer | declines: status 'declined' (a MID verdict) or 'error' (a technical error) - TXN_DECLINED. approved + declined can be LESS than charges. |
| `byDimension.<dim>[].completed` | integer | - the approval rate's base (APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). Friendlies sales are left out. What a Total row sums. |
| `byDimension.<dim>[].refunds` | integer | v3.9.9 - the window's refund / chargeback EVENTS, the dashboard's Refunds / Chargebacks cards' basis: `refunds` = the transactions of the bucket with a successful, non-test refunds row NOT marked chargeback dated in [from, to] (the refund date - the refunded charge may be older than the window, it is attributed to ITS dimension values), `chargebacks` = the same row marked chargeback; per transaction; a chargeback is never a refund. The /transactions drill-down is `refund=refund` / `refund=chargeback` (+ the row's params, `population=live`). Every charge figure (charges, approved, declined, completed, grossCents) reads the window's charges only, so a bucket can hold events and no charge. |
| `byDimension.<dim>[].chargebacks` | integer | v3.9.9 - the window's CHARGEBACK events (a successful, non-test refunds row marked chargeback dated in [from, to]), per transaction, attributed to the charged-back transaction's dimension values; `refund=chargeback` reproduces it. |
| `byDimension.<dim>[].grossCents` | integer | Sum of amount_cents over APPROVED orders only (Friendlies sales included when the integration is active). Integer CENTS (a Postgres bigint converted to a JS number). |
| `byDimension.<dim>[].approvalApproved / approvalGrossCents` | integer | The approved count and the approved gross (integer cents) WITHOUT the Friendlies sales: the base of every rate and of the AOV. Equal to approved / grossCents without the Friendlies integration. |
| `byDimension.<dim>[].friendliesSales / friendliesAmountCents / friendliesAmountCurrency / friendliesCostCents` | integer \| string \| null | The Friendlies part of the row: approved Friendlies sales, their amount (null when they span several currencies) and its currency, and their cost (null while a Friendlies cost is unknown). 0 without the Friendlies integration. |
| `byDimension.<dim>[].approvalRate` | number | approvalApproved / completed as a 0..1 ratio (NOT a percentage); Friendlies sales are in neither term. 0 when completed = 0. |
| `byDimension.<dim>[].refundRate` | number | refunds / approvalApproved, 0..1 - v3.9.9: refund events of the period divided by the ordinary approved sales of the period (can exceed 1 on a small bucket). 0 when approvalApproved = 0 (the dashboard shows a dash). |
| `byDimension.<dim>[].chargebackRate` | number | chargebacks / approvalApproved, 0..1 - v3.9.9: chargeback events of the period divided by the ordinary approved sales of the period. 0 when approvalApproved = 0. |
| `byDimension.<dim>[].aovCents` | integer | Average order value in integer CENTS = round(approvalGrossCents / approvalApproved), Friendlies sales left out. 0 when approvalApproved = 0. |
| `excluded` | object | One integer per requested dimension: the LIVE orders of the filtered window WITHOUT a value for that dimension - never a row (no-Unknown rule; the dashboard's '<n> orders without <dimension>' footnote). summary.charges - excluded[dim] = sum of charges of that dimension's rows + its `tail`. Typical: a card without a BIN (issuer / level / bin / funding unless card_funding is stored; v3.9.8 item 1 - never a wallet charge: in brand / funding / level / issuer / bin it is a row of its own, 'Apple Pay' / 'Google Pay'), a subscription charge whose originating sale carried no user agent has no device / browser / OS, a charge that ended on no MID has no gateway / MCC / acquirer BIN. v3.9.9 - gateway: a charge on neither a MID nor a wallet provider (the list's `accountId=none`); brand: a card of no recognised network (`brand=Other`). |
| `excludedEvents` | object | v3.9.9 - one `{ refunds, chargebacks }` per requested dimension: the refund / chargeback EVENTS of the transactions without a value for it (the NULL group of `excluded`) - the dashboard's note carries them, so a table's Total + its note = the summary's events = the dashboard cards. |
| `tail` | object | v3.9.9 - per CAPPED dimension (absent when nothing was cut): the rows beyond the cap folded into ONE reconciling row - `{ key: '', name: '', rows, charges, approved, declined, completed, refunds, chargebacks, grossCents, approvalApproved, approvalGrossCents, the friendlies* fields, approvalRate, refundRate, chargebackRate, aovCents }` (`rows` = the rows folded). No filter reproduces it (the dashboard's plain "Other (n)" row); the table's Total and Share read the rows + the tail. |
| `summary` | object | The whole filtered window (independent of `dims`): charges, approved, declined, completed, approvalApproved, approvalGrossCents, the friendlies* fields, approvalRate, grossCents, aovCents, refunds, refundRate, chargebacks, chargebackRate - same definitions as a row. v3.9.9 - refunds / chargebacks = the window's events: the dashboard's Refunds / Chargebacks cards for the same scope. |
| `tz` | string | The timezone the Hour dimension and the `hour` filter were read in (the `tz` sent, else the account's). |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when from or to is missing or malformed, a parameter is unknown, a value is outside its vocabulary, a range pair is reversed, hour is sent without a valid tz, tz is not an IANA zone (`details.tz`), or dims names an unknown dimension (`details.dims`). `{"error":"Synchronous reports support at most 400 days. Use report jobs for larger ranges."}` when the window is longer than 400 days or to is before from. `{"error":"Unknown flow filter"}` or `{"error":"Unknown affiliate filter"}` when flow or affiliate names an id that is not one of the account's.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"}` when the account's plan does not include the reports module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.
- `503` `{"error":"The database is temporarily unavailable ... please retry in a moment."}` (with Retry-After: 1) when the reporting pool cannot be reached.
- `504` `{"error":"The request took too long and was cancelled ... narrow the range and retry."}` when the read passes its 25-second budget (queue time included).

**Gotchas**

- Filters use the one unified catalog shared by the transactions list, the reports and the bulk tools: the query is strict (an unknown parameter is a 400 that names it), a closed vocabulary rejects unknown values, CSV values are OR-ed inside a key and keys are AND-ed, range pairs (from/to, amountMin/amountMax, cycleMin/cycleMax, clientOrdersMin/Max, clientLtvMin/Max, the sub and client date pairs, dayFrom/dayTo) must be ordered, and hour needs a valid tz.
- from / to are inclusive on both ends: two back-to-back instant windows sharing a boundary count a row on it twice. Send the tz you built the day bounds with.
- No Unknown / Other row: orders without a value for a dimension are left out of that table and counted in excluded[dim] (their events in excludedEvents[dim]); rows beyond a table cap (issuer 50, level 25, bin 100, others 30, by charges) are folded into tail[dim]. Rows + tail + excluded = summary.
- Every *Rate is a 0..1 ratio. approvalRate = approved ordinary sales / completed; refundRate and chargebackRate = the window's events over its approved ordinary sales. Friendlies sales count in charges, approved, gross and events but not in completed or any rate.
- Money is integer cents in grossCents; grossCurrencies lists the currencies behind it (two or more means the cents add unlike units: do not label them one currency).
- A rebill carries no browser context of its own: its device, IP, country, storefront and traffic source are those of the originating sale.
- The read runs in one read-only snapshot on the reporting pool with a 25-second budget. For longer windows or heavy exports use the report jobs (POST /v1/metrics/jobs).

#### Recovery

The cart recovery funnel report.

- KPI cards from `GET /v1/recovery/report` (`totals`): Opened % = opened / relanced; Tapped the link % = clicked / relanced; Recovery rate = recovered / relanced; Clicked the relance % = recovered_clicked / recovered; SMS credited = recovered_via.sms + recovered_via.both, e-mail credited = recovered_via.email + recovered_via.both.
- Templates: Conversion = carts_recovered / sent. Audience: Recovery rate = recovered / carts. Totals of Touches, Templates and Failed sends are summed in the browser (By day and By shop totals are the API `totals`).
- The export holds the active tab's table only.

##### `GET /v1/recovery/report`

**Scope** `recovery.read` - **Get the cart-recovery funnel report**

Reports -> Cart recovery: the account's abandoned-cart funnel over a window of the DISPLAY TIMEZONE's days (v3.9.9 - they were UTC days), optionally for one store. Two kinds of figures, never mixed: the RECOVERY LEDGER (the carts the checkout handed off, the SMS / e-mail relances, the carts relanced, the opens and taps after a relance, the discount offered, the breakdowns per touch of the ladder and per template, and what the sends cost) is cocoapi's own cart record, not transactions, each figure dated by its own event; the RECOVERED SALES are the /transactions list's own `source=recovery` rows (a live, approved straight sale the checkout stamped as won by a relance) in the caller's tenancy and ATRI view, their money the CHARGED amount. The totals are the sums of the by_day and by_shop rows, so a KPI always equals both tables' Total.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD); default `to - 29 days` | no | ISO instant (the dashboard sends the display timezone's day start, lib/dayRange dayBoundsUtc) or a bare day YYYY-MM-DD read in `tz`; inclusive. |
| `to` | string (ISO 8601 instant or YYYY-MM-DD); default `today in `tz`` | no | ISO instant (the day end, 23:59:59.999 local) or a bare day read in `tz` (the whole day); inclusive. |
| `tz` | string; default `the account's display timezone` | no | IANA timezone the days are cut in (the by_day rows, bare from / to). v3.9.9. Max 64 characters; an unknown zone answers 400. |
| `shop_id` | string | no | Legacy: a checkout shop id, read as its shop's storefront host (404 when the account holds no cart of it). Max 64 characters. |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: store host bucket(s), CSV, matched on the bare lowercased host; __no_store__ selects canonical standalone orders. Applies to the ledger (carts, sends) and to the recovered sales. When it names exactly one host, the answer echoes it as store. Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "from": "2026-09-26T04:00:00.000Z",
  "to": "2026-09-27T03:59:59.999Z",
  "tz": "America/New_York",
  "store": null,
  "totals": {
    "carts": 3286,
    "cart_value_cents": 11076617,
    "pending": 8,
    "done": 3277,
    "frozen": 1,
    "relanced": 41,
    "recovered": 2,
    "recovered_cents": 15596,
    "recovered_via": {
      "sms": 0,
      "email": 0,
      "both": 2
    },
    "recovery_rate": 0.0488,
    "recovered_clicked": 1,
    "discount_cents": 41200,
    "opened": 22,
    "clicked": 9,
    "cost_cents": 118,
    "billable_units": 52,
    "unpriced_sends": 0,
    "cost_known": true
  },
  "channels": [
    {
      "channel": "email",
      "sent": 39,
      "failed": 0,
      "computed": 0,
      "skipped": 1,
      "carts_relanced": 36,
      "recovered": 2,
      "recovered_cents": 15596,
      "cost_cents": 39,
      "billable_units": 39,
      "unpriced_sends": 0
    },
    {
      "channel": "sms",
      "sent": 9,
      "failed": 0,
      "computed": 0,
      "skipped": 4,
      "carts_relanced": 9,
      "recovered": 2,
      "recovered_cents": 15596,
      "cost_cents": 79,
      "billable_units": 13,
      "unpriced_sends": 0
    }
  ],
  "skip_reasons": [
    {
      "channel": "sms",
      "reason": "quiet_hours",
      "n": 4
    },
    {
      "channel": "email",
      "reason": "unsubscribed",
      "n": 1
    }
  ],
  "by_day": [
    {
      "day": "2026-09-26",
      "carts": 3286,
      "sms_sent": 9,
      "email_sent": 39,
      "recovered": 2,
      "recovered_cents": 15596,
      "cost_cents": 118,
      "billable_units": 52,
      "unpriced_sends": 0
    }
  ],
  "by_shop": [
    {
      "store": "shop.example",
      "shop_name": "Acme Store",
      "carts": 2410,
      "sms_sent": 6,
      "email_sent": 27,
      "recovered": 1,
      "recovered_cents": 6798,
      "cost_cents": 77,
      "billable_units": 35,
      "unpriced_sends": 0
    },
    {
      "store": "other.example",
      "shop_name": "Other Store",
      "carts": 876,
      "sms_sent": 3,
      "email_sent": 12,
      "recovered": 1,
      "recovered_cents": 8798,
      "cost_cents": 41,
      "billable_units": 17,
      "unpriced_sends": 0
    }
  ],
  "by_touch": [
    {
      "channel": "email",
      "touch": 1,
      "sent": 30,
      "skipped": 1,
      "carts_recovered": 2,
      "recovered_cents": 15596,
      "discount_cents": 31700
    },
    {
      "channel": "email",
      "touch": 2,
      "sent": 9,
      "skipped": 0,
      "carts_recovered": 1,
      "recovered_cents": 6798,
      "discount_cents": 9500
    },
    {
      "channel": "sms",
      "touch": 1,
      "sent": 9,
      "skipped": 4,
      "carts_recovered": 2,
      "recovered_cents": 15596,
      "discount_cents": 0
    }
  ],
  "by_template": [
    {
      "template_id": null,
      "template_name": "built-in default",
      "channel": "email",
      "sent": 39,
      "carts_recovered": 2,
      "recovered_cents": 15596
    },
    {
      "template_id": "3c1d2e4f-0000-4000-8000-000000000001",
      "template_name": "Short SMS",
      "channel": "sms",
      "sent": 9,
      "carts_recovered": 2,
      "recovered_cents": 15596
    }
  ],
  "by_audience": [
    {
      "language": "en",
      "channel": "email",
      "currency": "USD",
      "sent": 39,
      "carts": 36,
      "recovered": 2,
      "recovered_cents": 15596,
      "discount_cents": 41200
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `from / to / tz / store` | string | The window read (ISO instants), the timezone of its days, the store (host) - echoed. |
| `totals.carts / cart_value_cents` | integer / integer\|null | Ledger: carts handed off in the window (created_at, the first hand-off of the cart, written once) and their subtotal. cart_value_cents is null when the carts mix currencies (see moneyCurrencies). |
| `totals.pending / done / frozen` | integer | Ledger: those carts by current status. |
| `totals.relanced` | integer | Ledger: distinct carts that received at least one SENT relance in the window (send created_at). |
| `totals.recovered / recovered_cents` | integer / integer\|null | Transactions: the recovered sales = GET /v1/transactions?source=recovery&status=approved&population=live&from&to(&storefront): its total and the sum of its amounts (null when they mix currencies). |
| `totals.recovered_via` | object | The recovered sales by the checkout's stamp: sms / email / both (a partition of recovered). |
| `totals.recovery_rate` | number | recovered / relanced (0 when nothing was relanced). |
| `totals.recovered_clicked` | integer | Of the recovered sales, those whose recovery stamp says the buyer clicked the relance link; the others arrived view-through. |
| `totals.discount_cents` | integer\|null | The money offered away: on every SENT relance of the window, the cart subtotal minus the price it was offered, summed. Offered, not redeemed. null when the sends mix currencies. |
| `totals.opened / clicked` | integer | Of the carts relanced in the window: those that opened a relance e-mail (open pixel) and those that tapped a relance link, each counted only when the open or the tap happened after a send of the window. |
| `totals.cost_cents / billable_units / unpriced_sends / cost_known` | integer / integer / integer / boolean | What the SENT relances of the window cost at today's sender rates (the per-send cost only: monthly sender subscriptions are not apportioned here), the units billed (SMS segments, e-mails) and the sends no rate covers. With unpriced_sends above 0 the cost is a lower bound. cost_known false = the database has no sender cost data yet: every cost reads 0 and means unknown, not free. |
| `channels` | array | Per channel: sent, failed, computed (shadow), skipped (ledger), carts_relanced (distinct carts with a SENT send), recovered / recovered_cents (the recovered sales stamped with this channel or both), cost_cents, billable_units, unpriced_sends. Rows of standalone (V5) flows may add pending and unknown send counts. |
| `skip_reasons` | array | Every {channel, reason, n} of the window's skipped / failed sends (reason = skip_reason, else the first 60 chars of the error, else "failed") - sum of n = the channels' failed + skipped. |
| `by_day` | array | One row per day of the window in `tz` (zeros included): carts, sms_sent, email_sent, recovered, recovered_cents, cost_cents, billable_units, unpriced_sends. Their sums are the totals. |
| `by_shop` | array | One row per storefront host (the domain of the shop; '(no domain)' for a shop without one), every host with a cart, a sent relance or a recovered sale in the window, with the columns of by_day. Standalone (V5) flows without a store are grouped under store '__no_store__', shop_name 'No store'. |
| `by_touch[]` | array | One row per channel and touch number of the ladder: sent, skipped (skipped and failed sends), carts_recovered (carts that RECEIVED this touch and were recovered later), recovered_cents (their subtotals), discount_cents (offered on the sent sends of the touch). The rows overlap on purpose: a cart recovered after the third e-mail received the first two and is counted on all three. Standalone rows may add pending and unknown. |
| `by_template[]` | array | One row per template actually used at send time, most sent first: template_id (null = the built-in wording of the engine for that locale), template_name ('built-in default' when none), channel, sent, carts_recovered, recovered_cents. |
| `by_audience[]` | array | Sent messages grouped by language, channel and currency: sent, carts, recovered, recovered_cents, discount_cents. Repeat sends count once per cart within a group. recovered_cents uses cart subtotal (not the final payment). discount_cents sums discounts offered in those sends, not redeemed discounts. Date uses send.created_at; owner scope applies. |
| `moneyCurrencies / moneyUnavailableReasons` | object | On totals and on every row that carries money: per amount key (cart_value_cents, recovered_cents, discount_cents) the currencies that were summed, and mixed_currencies or unknown_currency when that amount is null because it cannot be summed. |

**Errors**

- `400` {"error":"bad range","details":<zod flatten()>} for an unknown parameter or an invalid filter value; {"error":"Invalid","details":{"tz":"not a known IANA timezone"}}; {"error":"bad range"} when from / to cannot form a window (reversed, malformed, or longer than the report allows).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan lacks the reports module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Unknown shop"} when shop_id names no cart of the account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Strict query: every key of the unified filter catalog is accepted (listed in params); an unknown parameter is a 400 "bad range" with details.
- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- v3.9.15 - BREAKING: `store` is retired (a 400): the catalog's `storefront` (a CSV of hosts) filters the ledger and the sales; the echoed `store` is the shop_id's host, else the storefront filter's when it names one host.
- v3.9.9 - the days are the display timezone's (they were UTC days): the dashboard sends each day's bounds as instants plus `tz`, and every by_day row is a day of `tz`.
- Each ledger figure is dated by its own event, written once: a cart by its first hand-off (created_at - it was last_event_at, which the checkout's refreshes move, so a past day's count changed as it was read), a send by created_at; a recovered sale by the sale's created_at. A past window's figures are final.
- totals = the sum of by_day = the sum of by_shop for carts, sends, recovered sales and costs (the same rows, merged by the API); relanced, opened, clicked, recovered_clicked and discount_cents are totals only (relanced, opened and clicked are distinct cart counts).
- channels[].recovered credits a sale stamped 'both' to each channel: they overlap by totals.recovered_via.both.
- A malformed from / to / tz is a 400 (it used to fall back silently to the default range).
- One cart may appear in multiple channels; audience rows have no additive grand total. Compare recovery rates within groups and never sum different currencies. Missing target price contributes zero offered discount.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- The "converted without a relance" figures (totals.converted / converted_cents and the converted columns of by_day and by_shop) were removed on 2026-10-26: a cart that ordered before any relance was a buyer checking out, not an abandoned cart.

#### Subscriptions

The Subscriptions report page reads GET /v1/metrics/segments?mode=rebill (Reports > Refunds); the per-day subscription report is here.

- The page itself reads `GET /v1/metrics/segments?mode=rebill` (Reports > Refunds). Its figures are computed as described there.

##### `GET /v1/subscription/reports`

**Scope** `subscriptions.read` - **Per-day subscription report**

Returns the per-CHARGE-day performance of the account's subscription-engine charges (v3.9.9, F5 / F6: the day of `tz` - the account's display timezone by default - the /transactions list files the charge on: its transaction's creation, else the decision instant of a blocked entry; never the run day, which is a labelled column): charges (success + declined = the list's engine=subscription,legacy rows of the day), success, declined (a failed charge WITH a transaction row: the MID's decline or a technical error - the list's status=failed,pending,unknown), blocked (a refusal before any MID or an entry that left no transaction row - no list row, its own figure), rejected (BIN scrub / duplicate card, no row either), approved volume and the run days, optionally restricted to charges whose original sale came from given storefront hosts, plus the list of the account's storefront hosts (last 180 days) for the filter. Test charges excluded.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (YYYY-MM-DD) | **yes** | First charge day (YYYY-MM-DD, a day of `tz`), inclusive. Required. |
| `to` | string (YYYY-MM-DD) | **yes** | Last charge day inclusive (YYYY-MM-DD, a day of `tz`). Required; before `from` -> 400. |
| `tz` | string; default `the account's display timezone` | no | IANA timezone of the charge days (a catalog key); absent = the account's display timezone. An unknown zone is a 400. |
| `hour` | string (CSV) | no | Filter catalog (Date): CSV of hours 00-23 in tz (needs tz). |
| `status` | csv enum: approved\|failed\|declined\|error\|unknown\|pending\|duplicate\|completed\|chargeback\|rdr\|ethoca | no | Filter catalog (Transaction): Charge status (failed = declined + error, completed = with an outcome). Comma-separated; an unknown value is a 400 naming it. |
| `source` | csv enum: sale\|rebill\|recovery\|pre-auth\|friendlies\|straight\|subscription\|upsell | no | Filter catalog (Transaction): straight (sale + recovery) / subscription (rebill), or the raw buckets. Comma-separated; an unknown value is a 400 naming it. |
| `pass` | csv enum: initial\|cascade | no | Filter catalog (Transaction): initial / cascade. Comma-separated; an unknown value is a 400 naming it. |
| `method` | csv enum: card\|wallet\|wire | no | Filter catalog (Transaction): card / wallet / wire. Comma-separated; an unknown value is a 400 naming it. |
| `population` | csv enum: live\|test\|imported | no | Filter catalog (Transaction): live / test / imported (reports: live only). Comma-separated; an unknown value is a 400 naming it. |
| `credentialMode` | csv enum: mit\|cit | no | Filter catalog (Transaction): Wire: mit / cit. Comma-separated; an unknown value is a 400 naming it. |
| `threeDs` | csv enum: applied\|applied-other\|attempted\|reserved\|holdout\|excluded\|rule\|none\|not-run\|frictionless\|challenge\|attempt\|data-only | no | Filter catalog (Transaction): 3DS outcome. Comma-separated; an unknown value is a 400 naming it. |
| `declineCategory` | string (CSV) | no | Filter catalog (Transaction): Decline-engine category. |
| `declineSeverity` | csv enum: soft\|hard | no | Filter catalog (Transaction): soft / hard. Comma-separated; an unknown value is a 400 naming it. |
| `amountMin` | string (whole number) | no | Filter catalog (Transaction): Amount >= (cents). |
| `amountMax` | string (whole number) | no | Filter catalog (Transaction): Amount <= (cents). |
| `currency` | string (CSV) | no | Filter catalog (Transaction): ISO-4217 currency. |
| `gatewayTxnId` | string | no | Filter catalog (Transaction): Gateway transaction id (exact, CSV). |
| `authCode` | string | no | Filter catalog (Transaction): Auth code of any attempt (exact, CSV). |
| `descriptor` | string | no | Filter catalog (Transaction): Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | csv enum: 1. < $25\|2. $25-49\|3. $50-74\|4. $75-99\|5. $100-149\|6. $150-199\|7. $200+ | no | Filter catalog (Transaction): Price bucket. Comma-separated; an unknown value is a 400 naming it. |
| `product` | string (CSV) | no | Filter catalog (Transaction): Basket product name / slug / ref. |
| `productSlug` | string (CSV) | no | Filter catalog (Transaction): Basket product slug. |
| `productKey` | string (CSV) | no | Filter catalog (Transaction): Product per store: <host>\|<ref>. |
| `accountId` | string (CSV) | no | Filter catalog (Routing): Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | string (CSV) | no | Filter catalog (Routing): Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string (CSV) | no | Filter catalog (Routing): a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | string (CSV) | no | Filter catalog (Routing): Any category of the final MID (ids). |
| `primaryCategory` | string (CSV) | no | Filter catalog (Routing): Primary category of the final MID (ids). |
| `atri` | string (CSV) | no | Filter catalog (Routing): ATRI reached (ids). |
| `atriFinal` | string (CSV) | no | Filter catalog (Routing): ATRI the order ended on (ids). |
| `processor` | string (CSV) | no | Filter catalog (Routing): Processor ids, none. |
| `acquiringBank` | string (CSV) | no | Filter catalog (Routing): Acquiring bank ids, none. |
| `company` | string (CSV) | no | Filter catalog (Routing): Company ids, none. |
| `gatewayMcc` | string (CSV) | no | Filter catalog (Routing): Final MID MCC. |
| `gatewayBin` | string (CSV) | no | Filter catalog (Routing): Final MID acquirer BIN. |
| `brand` | string (CSV) | no | Filter catalog (Card): Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string (CSV) | no | Filter catalog (Card): APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string (CSV) | no | Filter catalog (Card): Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string (CSV) | no | Filter catalog (Card): bin_info card type (or a wallet). |
| `cardLevel` | string (CSV) | no | Filter catalog (Card): bin_info card level (or a wallet). |
| `issuer` | string (CSV) | no | Filter catalog (Card): Issuing bank (RFC-4180 CSV). |
| `bin` | string | no | Filter catalog (Card): CSV of 6-digit BINs or a wallet label. |
| `first6` | string | no | Filter catalog (Card): Card prefix (1-6 digits). |
| `last4` | string | no | Filter catalog (Card): Card suffix (1-4 digits). |
| `country` | string (CSV) | no | Filter catalog (Customer): Billing country (ISO-2, inherited from the sale). |
| `storefront` | string (CSV) | no | Filter catalog: Existing store/domain selections, optionally including __no_store__ for canonical standalone orders. No store means canonical standalone orders; it is not a blank URL test. |
| `traffic` | string (CSV) | no | Filter catalog (Customer): Traffic source, (direct/organic). |
| `utmSource` | string (CSV) | no | Filter catalog (Customer): UTM source (case-insensitive). |
| `utmCampaign` | string (CSV) | no | Filter catalog (Customer): UTM campaign (case-insensitive). |
| `device` | string (CSV) | no | Filter catalog (Customer): Mobile / Tablet / Desktop. |
| `os` | string (CSV) | no | Filter catalog (Customer): Operating system. |
| `browser` | string (CSV) | no | Filter catalog (Customer): Browser. |
| `ipType` | csv enum: IPv4\|IPv6 | no | Filter catalog (Customer): IPv4 / IPv6. Comma-separated; an unknown value is a 400 naming it. |
| `ip` | string | no | Filter catalog (Customer): CSV of client IPs. |
| `email` | string | no | Filter catalog (Customer): E-mail contains. |
| `phone` | string | no | Filter catalog (Customer): Phone contains. |
| `firstName` | string | no | Filter catalog (Customer): First name contains. |
| `lastName` | string | no | Filter catalog (Customer): Last name contains. |
| `customerEmail` | string | no | Filter catalog (Client): Client e-mail (exact, CSV). |
| `customerThreeDs` | csv enum: with-ready\|without-ready\|single\|double\|ready-for-rebill | no | Filter catalog (Client): Customer authentication inventory now; single/double count proofs obtained, including used proofs. Comma-separated; an unknown value is a 400 naming it. |
| `clientBlacklisted` | enum: true\|false | no | Filter catalog (Client): Blacklisted (e-mail or card). An unknown value is a 400. |
| `clientLiveSub` | enum: true\|false | no | Filter catalog (Client): Has a live (active / paused) subscription. An unknown value is a 400. |
| `clientOrdersMin` | string (whole number) | no | Filter catalog (Client): Lifetime orders >=. |
| `clientOrdersMax` | string (whole number) | no | Filter catalog (Client): Lifetime orders <=. |
| `clientLtvMin` | string (whole number) | no | Filter catalog (Client): Lifetime value >= (cents). |
| `clientLtvMax` | string (whole number) | no | Filter catalog (Client): Lifetime value <= (cents). |
| `clientFirstFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen from. A bare day is read in tz. |
| `clientFirstTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): First seen to. A bare day is read in tz. |
| `clientLastFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen from. A bare day is read in tz. |
| `clientLastTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Client): Last seen to. A bare day is read in tz. |
| `checkout` | string (CSV) | no | Filter catalog (Transaction): Checkout ids at sale; none for unattributed / legacy. |
| `flow` | string (CSV) | no | Filter catalog: Shared flow filter: comma-separated owned flow UUIDs, optionally none for transactions without a flow. Derived from the immutable purchase session/version, not the current store assignment. Foreign IDs are rejected. |
| `affiliate` | string (CSV) | no | Filter catalog: Multi-select affiliate filter. none means No affiliate. Account-owned disabled IDs remain valid for history; unknown or foreign values fail closed. |
| `subscription` | string (CSV) | no | Filter catalog (Subscription): Subscription product ids. |
| `cycle` | string (CSV) | no | Filter catalog (Subscription): Charge cycle (0 = the straight sale). |
| `cycleMin` | string (whole number) | no | Filter catalog (Subscription): Charge cycle >=. |
| `cycleMax` | string (whole number) | no | Filter catalog (Subscription): Charge cycle <=. |
| `engine` | csv enum: subscription\|legacy\|external | no | Filter catalog (Subscription): subscription / legacy / external. Comma-separated; an unknown value is a 400 naming it. |
| `subStatus` | csv enum: active\|paused\|failed\|cancelled\|completed\|expired | no | Filter catalog (Subscription): Sub status. Comma-separated; an unknown value is a 400 naming it. |
| `attachedBy` | csv enum: auto\|manual\|legacy\|optin | no | Filter catalog (Subscription): auto / manual / legacy / optin. Comma-separated; an unknown value is a 400 naming it. |
| `due` | enum: overdue\|24h\|7d | no | Filter catalog (Subscription): Next charge: overdue / 24h / 7d. An unknown value is a 400. |
| `endCause` | string (CSV) | no | Filter catalog (Subscription): End cause. |
| `subCreatedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created from. A bare day is read in tz. |
| `subCreatedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub created to. A bare day is read in tz. |
| `subEndedFrom` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended from. A bare day is read in tz. |
| `subEndedTo` | string (ISO instant or YYYY-MM-DD) | no | Filter catalog (Subscription): Sub ended to. A bare day is read in tz. |
| `schedule` | string (CSV) | no | Filter catalog (Schedule): Schedule (day) ids. |
| `scheduleStatus` | csv enum: scheduled\|processing\|partial\|paused\|done\|cancelled | no | Filter catalog (Schedule): Schedule status. Comma-separated; an unknown value is a 400 naming it. |
| `scheduleType` | csv enum: subscription\|auto\|manual | no | Filter catalog (Schedule): subscription / auto / manual. Comma-separated; an unknown value is a 400 naming it. |
| `dayFrom` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string (YYYY-MM-DD) | no | Filter catalog (Schedule): Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | csv enum: scheduled\|processing\|rebill_success\|declined\|blocked\|rebill_failed\|rejected\|cancelled\|missed | no | Filter catalog (Schedule): Charge state of the schedule entry. Comma-separated; an unknown value is a 400 naming it. |
| `entryReason` | string (CSV) | no | Filter catalog (Schedule): Charge reason (decline reason of the entry). |
| `refund` | csv enum: refund\|chargeback\|rdr\|ethoca | no | Filter catalog (Refund): Refund event kind. Comma-separated; an unknown value is a 400 naming it. |
| `refundBasis` | enum: refund\|charge | no | Filter catalog (Refund): Refund event dated by refund (default) / charge. An unknown value is a 400. |
| `refunded` | csv enum: true\|false | no | Filter catalog (Refund): Refunded state flag. Comma-separated; an unknown value is a 400 naming it. |
| `refundStatus` | csv enum: approved\|pending\|declined\|error\|unknown\|cancelled | no | Filter catalog (Refund): Refund row status. Comma-separated; an unknown value is a 400 naming it. |
| `refundTest` | enum: exclude\|include\|only | no | Filter catalog (Refund): Test refunds: exclude (= absent) / include / only. An unknown value is a 400. |
| `q` | string | no | Filter catalog (Search): The page's identity search. |

**Response**

```json
{
  "rows": [
    {
      "day": "2026-09-19",
      "rebills": 210,
      "success": 176,
      "failed": 34,
      "rejected": 1,
      "amount_cents": 1231824
    },
    {
      "day": "2026-09-18",
      "rebills": 640,
      "success": 512,
      "failed": 128,
      "rejected": 3,
      "amount_cents": 3583488
    }
  ],
  "sites": [
    "shop.example.com",
    "store.example.org"
  ],
  "timezone": "America/New_York"
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | One row per charge day with at least one decided or rejected charge, newest first. |
| `rows[].day` | string (YYYY-MM-DD) | The charge day (of `timezone`): the day /transactions files the charge on. |
| `rows[].charges` | integer | Success + declined: the charges that have a transaction row (= /transactions engine=subscription,legacy for that day). Approval = success / charges. |
| `rows[].success` | integer | Approved charges (the list's status=approved). |
| `rows[].declined` | integer | Failed charges WITH a transaction row: the MID's decline or a technical error (the list's status=failed,pending,unknown). Replaces `failed` (which counted the blocked ones too). |
| `rows[].blocked` | integer | Refused before any MID or left without a transaction row ("No card on file", ...): no list row, never inside charges. |
| `rows[].rejected` | integer | Scrubbed (BIN scrub / duplicate-card guard) before any attempt - no transaction row. |
| `rows[].amount_cents` | integer | Approved volume. |
| `rows[].run_days` | string[] | The schedule (run) days the day's charges belonged to - a force-billed or reopened day charges on another date than its run day. |
| `sites` | string[] | The account's storefront BUCKETS of the last 180 days: the catalog's storefront values (the host, www. / pay. kept, the path cut - db/txFilters STORE_HOST), i.e. the values a `storefront=` filter matches. The filter options otherwise come from GET /v1/filters/facets (storefronts). |
| `timezone` | string | The timezone the days are cut in: `tz`, else the account's display timezone. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten()>} - from / to missing or not YYYY-MM-DD, a reversed range, an unknown query key (sites included) or closed-vocabulary value.
- `400` {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}: a flow or affiliate id in the query is not one of the account's (checked before the handler).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"reports"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `504` "The request took too long and was cancelled - narrow the range and retry." (statement timeout).

**Gotchas**

- Grouped by CHARGE day (the /transactions date), no longer by run day: a row's charges equal the list's engine=subscription,legacy drill-down of that day in the same timezone; the run days are in `run_days`.
- `rebills` / `failed` are gone (v3.9.9): charges = success + declined, blocked and rejected apart (no transaction row).
- BREAKING: `sites` retires (a 400) - it is the catalog's `storefront` (the host bucket of the charge, else its originating sale). Every catalog key applies on the decided entries (the entry grain); `sites` in the response lists the account's storefront buckets (the storefront= values).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

#### Financial

The financial report: ledger, daily and breakdown.

From `GET /v1/metrics/financial` (one report for the range, one for the previous period, one for the breakdown):

- Previous period = the period of the same length just before the range, read as a second report; each change pill = (range - previous) / previous.
- Margin = bottom line / gross volume (also after ad spend); breakdown Share and ledger "% of gross" = value / gross volume.
- Daily and Breakdown totals are summed in the browser; the charts (cumulative series, deductions = fees - reserve, fees by type, the waterfall, "Other" past the 7th breakdown row) too.

##### `GET /v1/metrics/financial`

**Scope** `reports.read` - **Get the Financial report (the Finance breakdown day by day)**

Reports > Financial (v3.9.8): the dashboard's Finance breakdown (GET /v1/metrics `finance`) cut into the calendar days of [from, to] in `tz`, every line also split Straight / Subscription (the cards' classifier), with the range totals, the Pilot block of the range and, with `groupBy`, the same per-day series exploded by a dimension (gateway, processor, acquiring bank, company, ATRI, store, product, payment method, source, traffic source, country), top N + an Other row, drillable step by step (`drill`). Every figure is one of the Finance breakdown's own statements re-cut: the LIVE charges of the window (counts, gross, discount, reserve, the charges' 3DS fees, the wallet providers' per-charge fee) dated by transactions.created_at; the per-attempt transaction fee (every non-skipped attempt of a LIVE charge on a MID the account owns, at that MID's CURRENT flat fee) dated by transaction_attempts.created_at; the refunds and chargebacks with their live per-network fees, dated by refunds.created_at; the 3DS fees billed on rejections, dated by charge_rejections.created_at. The days partition those facts, so the sum of the days equals GET /v1/metrics `finance` for the same range and scope TO THE CENT (proved on production for the last 7 and 30 days). Fees at today's gateway rates, like the dashboard: nothing fee-derived is read from a stored column. ONE statement for the money, one for the Pilot spend per day. Read-only. v3.9.9: the live refresh is handed the range's Pilot days (lib/pilotDays pilotDayRange - the days the read uses) and makes no Pilot call when they do not hold the report tz's today (nor yesterday before 06:00): a past range reads its closed days as stored (pilot.stale false). v3.9.9 (D1 / D4) - the refunds and chargebacks are the refund EVENTS of every page: successful, NON-TEST refunds rows (db/txFilters REFUND_EVENT_SQL) of LIVE charges, dated by the refund, a refund = not marked chargeback, a chargeback = marked, counted per TRANSACTION - the dashboard's refQ / splitQ, the list's `refund=refund` / `refund=chargeback` (the report's links). The 3DS fees also come in their two halves, like the dashboard's finance: threeDsFeeChargesCents / threeDsFeeRejectionsCents.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `groupBy` | enum: gateway \| processor \| acquiringBank \| company \| atri \| store \| product \| method \| source \| traffic \| country \| category \| gatewayMcc \| threeDs \| checkout \| subscription | no | The explosion: one of gateway, processor, acquiringBank, company, atri, store, product, method, source, traffic, country, category, gatewayMcc, threeDs, checkout, subscription. Omitted or empty -> no `groups`. Unknown -> 400 {"details":{"groupBy":"unknown dimension: ..."}}. Buckets: gateway = the charge's MID (`mid:<id>`), else its wallet provider (`wallet:<id>`), else `(none)` - an ATTEMPT is bucketed by the MID that took it (the per-gateway report's attribution); processor / acquiringBank / company = the charge's gateway's reference (the attempting MID's for an attempt), `(unset)` when none; atri = the ATRI the order ended on (final cascade ATRI; a rejection's own trip); store / traffic / country = the /transactions filters' inherited expressions (a subscription charge reads its originating sale's); product = the order's FIRST basket line (the transactions list's Product column); method = Apple Pay / Google Pay for a wallet charge, the card network otherwise (`Other card` when none); source = straight / subscription. A rejection (3DS fee) sits in its own channel's side, its trip's ATRI, its storefront, its card's network, `(none)` / `(unset)` elsewhere. |
| `top` | integer >= 1 (clamped to 50); default `10` | no | Groups kept before the fold: every bucket ranked by its range gross (then orders, then key), past the top N into ONE `__other__` row. Clamped to 50; < 1 or not an integer -> 400. |
| `drill` | string (JSON, max 4000 chars) | no | The drill path: a JSON array of at most 4 `{ "dim": <groupBy key>, "key": <a group's key> }` steps, each dimension once, e.g. [{"dim":"company","key":"<id>"}] with groupBy=gateway = the company's gateways. Each step filters every population on the very bucket expression it was grouped on, so the children of a row add up to that row. The `__other__` row cannot be drilled. Malformed -> 400 {"details":{"drill":...}}. Any groupBy dimension is a valid step; the `__ad_spend_unattributed__` row cannot be drilled either. |
| `atriView` | string (CSV of ATRI ids, max 4000) | no | The dashboard's ATRI view, intersected with the caller's grants exactly as GET /v1/metrics does (an empty pick or nothing left = the grants). |
| `from` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | **yes** | Window start, inclusive: an ISO instant (any offset) or a YYYY-MM-DD day read in `tz`. Send the same tz you built the bounds with, or the edge days split. Missing is a 400 (details.fieldErrors.from = Required). |
| `to` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | **yes** | Window end, inclusive. Must not precede `from` (400 `to is before from`); the range is limited to 366 days (one day of slack for DST) and, like every synchronous report, 400 days. |
| `tz` | string, max 64 (IANA timezone); default `account timezone` | no | The clock the days are cut in and the `hour` filter is read in; echoed back. Unknown is a 400 (`not a known IANA timezone`). |
| `hour` | CSV of integers 0..23, max 200 | no | Filter catalog, Date: CSV of hours 00-23 in tz (needs tz). Needs a valid tz: an hour without one is a 400 `hour needs a valid tz`. |
| `status` | CSV enum | no | Filter catalog, Transaction: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `source` | CSV enum, max 100 | no | Filter catalog, Transaction: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. An unknown value is a 400 naming it. |
| `pass` | CSV enum, max 40 | no | Filter catalog, Transaction: initial / cascade. Allowed values: initial, cascade. An unknown value is a 400 naming it. |
| `method` | CSV enum, max 40 | no | Filter catalog, Transaction: card / wallet / wire. Allowed values: card, wallet, wire. An unknown value is a 400 naming it. |
| `population` | CSV enum, max 40 | no | Filter catalog, Transaction: live / test / imported (reports: live only). Allowed values: live, test, imported. An unknown value is a 400 naming it. |
| `credentialMode` | CSV enum, max 20 | no | Filter catalog, Transaction: Wire: mit / cit. Allowed values: mit, cit. An unknown value is a 400 naming it. |
| `threeDs` | CSV enum | no | Filter catalog, Transaction: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. An unknown value is a 400 naming it. |
| `declineCategory` | string, max 1000 | no | Filter catalog, Transaction: Decline-engine category. |
| `declineSeverity` | CSV enum, max 40 | no | Filter catalog, Transaction: soft / hard. Allowed values: soft, hard. An unknown value is a 400 naming it. |
| `amountMin` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount >= (cents). |
| `amountMax` | string of 1..12 digits (cents) | no | Filter catalog, Transaction: Amount <= (cents). |
| `currency` | CSV of 3-letter codes, max 200 | no | Filter catalog, Transaction: ISO-4217 currency. |
| `gatewayTxnId` | string, max 4000 | no | Filter catalog, Transaction: Gateway transaction id (exact, CSV). |
| `authCode` | string, max 1000 | no | Filter catalog, Transaction: Auth code of any attempt (exact, CSV). |
| `descriptor` | string, max 128 | no | Filter catalog, Transaction: Descriptor contains (sent statement descriptor, MID soft descriptor or name). |
| `pricePoint` | CSV enum | no | Filter catalog, Transaction: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. An unknown value is a 400 naming it. |
| `product` | string, max 4000 | no | Filter catalog, Transaction: Basket product name / slug / ref. |
| `productSlug` | string, max 4000 | no | Filter catalog, Transaction: Basket product slug. |
| `productKey` | string, max 4000 | no | Filter catalog, Transaction: Product per store: <host>\|<ref>. |
| `accountId` | CSV of MID uuids, wallet:<uuid>, wire:<uuid> or none, max 4000 | no | Filter catalog, Routing: Gateway: MID ids, wallet:<walletProviderId>, none. |
| `walletProvider` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Wallet provider ids (API alias of accountId=wallet:<id>). |
| `gatewayType` | string, max 100 | no | Filter catalog, Routing: a gateway type (the gatewayType values returned by GET /v1/accounts). |
| `category` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Any category of the final MID (ids). |
| `primaryCategory` | CSV of uuids, max 4000 | no | Filter catalog, Routing: Primary category of the final MID (ids). |
| `atri` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI reached (ids). |
| `atriFinal` | CSV of uuids, max 4000 | no | Filter catalog, Routing: ATRI the order ended on (ids). |
| `processor` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Processor ids, none. |
| `acquiringBank` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Acquiring bank ids, none. |
| `company` | CSV of uuids or none, max 4000 | no | Filter catalog, Routing: Company ids, none. |
| `gatewayMcc` | string, max 1000 | no | Filter catalog, Routing: Final MID MCC. |
| `gatewayBin` | string, max 1000 | no | Filter catalog, Routing: Final MID acquirer BIN. |
| `brand` | string, max 200 | no | Filter catalog, Card: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. |
| `paysource` | string, max 100 | no | Filter catalog, Card: APPLEPAY / GOOGLEPAY (wallet payload). |
| `funding` | string, max 200 | no | Filter catalog, Card: Prepaid / Debit / Credit / Charge card (or a wallet). |
| `cardType` | string, max 200 | no | Filter catalog, Card: bin_info card type (or a wallet). |
| `cardLevel` | string, max 4000 | no | Filter catalog, Card: bin_info card level (or a wallet). |
| `issuer` | string, max 4000 | no | Filter catalog, Card: Issuing bank (RFC-4180 CSV). |
| `bin` | CSV of 6-digit BINs or Apple Pay / Google Pay, max 4000 | no | Filter catalog, Card: CSV of 6-digit BINs or a wallet label. |
| `first6` | string of 1..6 digits | no | Filter catalog, Card: Card prefix (1-6 digits). |
| `last4` | string of 1..4 digits | no | Filter catalog, Card: Card suffix (1-4 digits). |
| `country` | string, max 2000 | no | Filter catalog, Customer: Billing country (ISO-2, inherited from the sale). |
| `storefront` | string, max 4000 | no | Filter catalog, Customer: Store host bucket, (direct). May include __no_store__ for canonical standalone orders (no store), which is not a blank-URL test. |
| `traffic` | string, max 2000 | no | Filter catalog, Customer: Traffic source, (direct/organic). |
| `utmSource` | string, max 4000 | no | Filter catalog, Customer: UTM source (case-insensitive). |
| `utmCampaign` | string, max 4000 | no | Filter catalog, Customer: UTM campaign (case-insensitive). |
| `device` | string, max 200 | no | Filter catalog, Customer: Mobile / Tablet / Desktop. |
| `os` | string, max 200 | no | Filter catalog, Customer: Operating system. |
| `browser` | string, max 200 | no | Filter catalog, Customer: Browser. |
| `ipType` | CSV enum, max 40 | no | Filter catalog, Customer: IPv4 / IPv6. Allowed values: IPv4, IPv6. An unknown value is a 400 naming it. |
| `ip` | string, max 2000 | no | Filter catalog, Customer: CSV of client IPs. |
| `email` | string, max 200 | no | Filter catalog, Customer: E-mail contains. |
| `phone` | string, max 40 | no | Filter catalog, Customer: Phone contains. |
| `firstName` | string, max 120 | no | Filter catalog, Customer: First name contains. |
| `lastName` | string, max 120 | no | Filter catalog, Customer: Last name contains. |
| `customerEmail` | CSV of e-mails, max 4000 | no | Filter catalog, Client: Client e-mail (exact, CSV). |
| `customerThreeDs` | CSV enum, max 200 | no | Filter catalog, Client: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. An unknown value is a 400 naming it. |
| `clientBlacklisted` | enum | no | Filter catalog, Client: Blacklisted (e-mail or card). Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientLiveSub` | enum | no | Filter catalog, Client: Has a live (active / paused) subscription. Allowed values: true, false. An unknown value is a 400 naming it. |
| `clientOrdersMin` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders >=. |
| `clientOrdersMax` | string of 1..12 digits | no | Filter catalog, Client: Lifetime orders <=. |
| `clientLtvMin` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value >= (cents). |
| `clientLtvMax` | string of 1..12 digits (cents) | no | Filter catalog, Client: Lifetime value <= (cents). |
| `clientFirstFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen from. |
| `clientFirstTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: First seen to. |
| `clientLastFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen from. |
| `clientLastTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Client: Last seen to. |
| `checkout` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Checkout ids at sale; none for unattributed / legacy. |
| `flow` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped.. Derived from the immutable purchase session version, not the current store assignment; unknown or foreign flow ids are a 400 (`Unknown flow filter`). |
| `affiliate` | CSV of uuids or none, max 4000 | no | Filter catalog, Transaction: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids.. Account-owned disabled affiliates stay valid for history; malformed, unknown or foreign ids are a 400 (`Invalid affiliate filter` / `Unknown affiliate filter`), never an unfiltered answer. |
| `subscription` | CSV of uuids, max 4000 | no | Filter catalog, Subscription: Subscription product ids. |
| `cycle` | CSV of integers 0..999, max 200 | no | Filter catalog, Subscription: Charge cycle (0 = the straight sale). |
| `cycleMin` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle >=. |
| `cycleMax` | string of 1..6 digits | no | Filter catalog, Subscription: Charge cycle <=. |
| `engine` | CSV enum, max 60 | no | Filter catalog, Subscription: subscription / legacy / external. Allowed values: subscription, legacy, external. An unknown value is a 400 naming it. |
| `subStatus` | CSV enum | no | Filter catalog, Subscription: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. An unknown value is a 400 naming it. |
| `attachedBy` | CSV enum, max 60 | no | Filter catalog, Subscription: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. An unknown value is a 400 naming it. |
| `due` | enum | no | Filter catalog, Subscription: Next charge: overdue / 24h / 7d. Allowed values: overdue, 24h, 7d. An unknown value is a 400 naming it. |
| `endCause` | string, max 1000 | no | Filter catalog, Subscription: End cause. |
| `subCreatedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created from. |
| `subCreatedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub created to. |
| `subEndedFrom` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended from. |
| `subEndedTo` | string: ISO instant (any offset) or YYYY-MM-DD read in tz, max 40 | no | Filter catalog, Subscription: Sub ended to. |
| `schedule` | CSV of uuids, max 4000 | no | Filter catalog, Schedule: Schedule (day) ids. |
| `scheduleStatus` | CSV enum | no | Filter catalog, Schedule: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. An unknown value is a 400 naming it. |
| `scheduleType` | CSV enum, max 60 | no | Filter catalog, Schedule: subscription / auto / manual. Allowed values: subscription, auto, manual. An unknown value is a 400 naming it. |
| `dayFrom` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day from (YYYY-MM-DD). |
| `dayTo` | string YYYY-MM-DD | no | Filter catalog, Schedule: Schedule run day to (YYYY-MM-DD). |
| `entryStatus` | CSV enum | no | Filter catalog, Schedule: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. An unknown value is a 400 naming it. |
| `entryReason` | string, max 4000 | no | Filter catalog, Schedule: Charge reason (decline reason of the entry). |
| `refund` | CSV enum, max 100 | no | Filter catalog, Refund: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. An unknown value is a 400 naming it. |
| `refundBasis` | enum | no | Filter catalog, Refund: Refund event dated by refund (default) / charge. Allowed values: refund, charge. An unknown value is a 400 naming it. |
| `refunded` | CSV enum, max 20 | no | Filter catalog, Refund: Refunded state flag. Allowed values: true, false. An unknown value is a 400 naming it. |
| `refundStatus` | CSV enum, max 80 | no | Filter catalog, Refund: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. An unknown value is a 400 naming it. |
| `refundTest` | enum | no | Filter catalog, Refund: Test refunds: exclude (= absent) / include / only. Allowed values: exclude, include, only. An unknown value is a 400 naming it. |
| `q` | string, max 200 | no | Filter catalog, Search: The page's identity search. Accepted by the strict catalog; identity search of list pages. |

**Response**

```json
{
  "from": "2026-09-21T04:00:00.000Z",
  "to": "2026-09-28T03:59:59.999Z",
  "tz": "America/New_York",
  "filtered": false,
  "days": [
    {
      "day": "2026-09-21",
      "total": {
        "orders": 812,
        "approved": 350,
        "declined": 460,
        "completed": 812,
        "approvalRate": 0.431,
        "aovCents": 3812,
        "grossCents": 1334200,
        "discountFeeCents": 186788,
        "transactionFeeCents": 22650,
        "threeDsFeeCents": 3450,
        "reserveCents": 133420,
        "refundCents": 54990,
        "refundCount": 12,
        "refundFeesCents": 18000,
        "chargebackCents": 21980,
        "chargebackCount": 4,
        "chargebackFeesCents": 6000,
        "feesCents": 370308,
        "netCents": 886922,
        "adSpendCents": 512300,
        "netAfterAdSpendCents": 374622
      },
      "straight": "... the same fields for the straight side (ad spend null)",
      "subscription": "... the subscription side"
    },
    "... one per calendar day of the range in tz"
  ],
  "totals": {
    "total": "... the sum of the days, the same fields",
    "straight": "...",
    "subscription": "..."
  },
  "pilot": {
    "active": true,
    "reason": null,
    "spend_cents": 3586100,
    "straight_roas": 2.41,
    "blended_roas": 3.2,
    "synced_through": "2026-09-27",
    "days_missing": 0,
    "timezone": "America/New_York",
    "refreshed_at": "2026-09-27T20:14:03.000Z",
    "stale": false,
    "refresh_reason": null,
    "...": "the dashboard pilot block"
  },
  "groupBy": "company",
  "top": 10,
  "drill": [],
  "drillFilter": {},
  "groups": [
    {
      "key": "6f2d0c9a-3a41-4b7e-9d0e-2c1f5a7b8e11",
      "name": "STELLAR TIDE LLC",
      "filter": {
        "company": "6f2d0c9a-3a41-4b7e-9d0e-2c1f5a7b8e11"
      },
      "drillable": true,
      "folded": 0,
      "total": "... figures",
      "straight": "...",
      "subscription": "...",
      "days": [
        "... figures per day, aligned with days"
      ]
    },
    {
      "key": "(unset)",
      "name": "(unset)",
      "filter": null,
      "drillable": true,
      "folded": 0,
      "total": "...",
      "straight": "...",
      "subscription": "...",
      "days": [
        "..."
      ]
    },
    {
      "key": "__other__",
      "name": "Other",
      "filter": null,
      "drillable": false,
      "folded": 3,
      "total": "...",
      "straight": "...",
      "subscription": "...",
      "days": [
        "..."
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `days` | array | One entry per calendar day of the range in `tz`, zero-filled, ascending (`day` = YYYY-MM-DD); a day a fact landed on outside that list (a zone table disagreement) is added, never dropped. |
| `days[].total / straight / subscription` | object | The day's Finance breakdown, whole and per side (Straight = sale + recovery, Subscription = rebill: the cards' classifier, a rejection by its own channel). straight + subscription = total, field by field (ad spend aside: a side has none). |
| `<figures>.orders / approved / declined / completed` | integer | Every LIVE charge (the dashboard's totals.total) / approved / the Declines card (MID verdicts + technical errors) / the approval rate's base. |
| `<figures>.approvalRate / aovCents` | number \| null | approved / completed and gross / approved; null over an empty base. |
| `<figures>.grossCents ... chargebackFeesCents` | integer (cents) | The Finance breakdown's lines: gross, discount fees, transaction fees (per-attempt + the wallet providers' per-charge fee), 3DS fees (the charges' + the rejections'), reserve, refunds (+ count, fees), chargebacks (+ count, fees). |
| `<figures>.feesCents` | integer (cents) | Every fee line: discount + transaction + 3DS + reserve + refund fees + chargeback fees. netCents = grossCents - feesCents - refundCents - chargebackCents (the dashboard's Net volume). |
| `<figures>.adSpendCents / netAfterAdSpendCents` | integer \| null | The Pilot spend (the "Ad Spend Pilot" line: total - the ignored campaigns, per calendar day) and net - spend. null when Pilot is inactive or has no data for the range, on a side, on a non-store group; a day Pilot has not synced has adSpendCents null and nets its spend as 0 (the dashboard's sum does the same). |
| `totals` | object | The sum of the days (total / straight / subscription) = GET /v1/metrics `finance`, `refunds`, `chargebacks`, `totals` and `split` for the same range and scope. |
| `pilot` | object | The dashboard's own Pilot block for the range (active, reason, spend_cents, straight_roas, blended_roas, synced_through, days_missing, refreshed_at, stale...), read after today's spend was refreshed from Pilot (60 s window, single-flight, 4 s budget). |
| `filtered` | boolean | A transaction dimension filter is applied: the rejections' 3DS fees are out of every figure - v3.9.11: except under a SOURCE-ONLY filter (`source` = straight or subscription and no other dimension filter), which keeps the rejections of that side (their own channel) and still answers `filtered: true`. |
| `groups` | array | With groupBy: the top N buckets by range gross, then `__other__` (folded = the number of buckets it holds), and - on a store breakdown with Pilot data - `__ad_spend_unattributed__`, the spend no store row carries, so the rows' ad spend adds up to the range's. Each group: key (the drill key), name, filter (the /transactions params that reproduce its charges exactly, or null - a sentinel, the first-line product, a card network), drillable, folded, total / straight / subscription, days (aligned with `days`). The groups add up to `totals`, day by day. |
| `drillFilter` | object \| null | The /transactions params of the whole drill path merged, or null when one step has no exact filter (the drill-down links then stay plain). |
| `<figures>.threeDsFeeChargesCents / threeDsFeeRejectionsCents` | integer | v3.9.9 - the two halves of threeDsFeeCents: the 3DS fees of the charges (sum of the "3DS fee" of the rows `threeDs=applied,attempted` opens) and of the rejections (no transaction row: no list opens them). |
| `<figures>.refundCount / chargebackCount` | integer | v3.9.9 (D1) - the distinct transactions with a successful, non-test refunds row not marked / marked chargeback, dated by the refund - per day and bucket (a charge refunded on two days would count on both: never the case on production). |
| `totals/days/groups figure.affiliateCuts` | array<{currency:string,amountMinor:string}> | Event-dated append-only cut totals, separated by ISO currency; integer minor units serialized as strings. |
| `totals/days/groups figure.affiliateCutCents` | integer \| null | Comparable deduction in minor units, including negative reversal periods. Null when currencies cannot be combined. |
| `totals/days/groups figure.netUnavailableReason` | string \| null | Explains nullable net when no FX conversion is configured or source figures are unavailable. |

**Errors**

- `400` `{"error":"Invalid","details":...}`: from / to missing or malformed, to before from, a range over 366 days (`the range is limited to 366 days`), an unknown groupBy (`unknown dimension: ...`), top below 1 or not an integer, a malformed, unknown, repeated, too deep (more than 4 steps) or fold-row drill, an unknown parameter (strict catalog; `hours` is not a parameter here), an unknown closed-vocabulary value, an unknown tz. `Synchronous reports support at most 400 days. Use report jobs for larger ranges.` when the resolved window is longer than 400 days (one hour of tolerance); use POST /v1/metrics/jobs with kind=financial. The gate also refuses a malformed or foreign `affiliate` / `flow` filter (`Invalid affiliate filter`, `Unknown affiliate filter`, `Invalid flow filter`, `Unknown flow filter`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route. `Your subscription does not include this tool.` (code `subscription_module_required`, module `reports`) when the plan lacks the reports module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1). The database is temporarily unavailable (Retry-After: 1) when this API process already runs its 4 reporting reads and 40 more are waiting.
- `504` The request took too long and was cancelled (the 25-second budget, queue time included, was exceeded); retry, narrow the range or use POST /v1/metrics/jobs with kind=financial.

**Gotchas**

- v3.9.15 - STRICT: an unknown query parameter is a 400 (`details.formErrors` names it), an unknown value of a closed vocabulary a 400 naming it - a misspelt filter can never return unfiltered data again.
- The days are CALENDAR days of `tz`: send the tz you built `from` / `to` with (the dashboard's display timezone), or the edges of the range split across two days. The dashboard's day bounds end a second past midnight (lib/timezone dayBoundsUtc); that second never adds an empty day.
- Every fact is dated by its OWN timestamp, like the dashboard: a refund of an old sale counts on the day of the refund, an attempt on the day it was made. So a day's refunds do not belong to that day's gross, and a drill-down link of a day's refunds is `refund=refund` (v3.9.9: the refunds dated that day, chargebacks excluded; `refund=chargeback` for the chargebacks).
- Fees at today's gateway rates: a fee setting edited today re-prices every past day at once (the Finance breakdown's rule, docs/SNAPSHOTS.md).
- The explosion attributes an attempt to the MID that took it for gateway / processor / acquiring bank / company, to its charge for every other dimension - the gateway rows' transaction fees match the per-gateway report's.
- The product dimension is the order's FIRST basket line: the whole order (upsells included) counts on it, so the rows partition the money; its /transactions link would open every order CONTAINING the slug, so `filter` is null.
- A transaction filter narrows the charges, their attempts and their refunds; the 3DS fees of rejections (no charge) are then left out (`filtered: true`) - a filtered total is not the dashboard's card. v3.9.11 - except a SOURCE-ONLY filter (straight / subscription alone): the rejections' 3DS fees of that side stay in (their own channel), so Straight + Subscription = the unfiltered report and Reports -> Payment / Products agree.
- Cost: ONE statement over the window, measured on production: about 2 s for 30 days, 4-6 s for 30 days cut by product or traffic source (they read the order basket / the inherited store), 5 s warm to 11 s cold for the whole history (about 200 days), plus two small Pilot reads. The page reads the previous period too (the KPI changes).
- Gateway category and MCC attribute attempt fees to the attempting MID; transaction/refund figures use the final MID. Missing dimensions and pre-gateway rejection fees remain in a (none) bucket so breakdowns reconcile. Subscription product resolves one deterministically attributed product per charge.
- v4.5 ATRI grouping uses the final cascade ATRI, with atriFinal in transaction links. In the 3DS dimension, pre-gateway rejection fees have no transaction and are labelled separately from No 3DS.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- Net deducts the cut ledger exactly once using the shared dashboard/report formula. Cuts appear in all 16 financial breakdowns and exports. Different currencies are never implicitly summed or converted; incompatible net is null. Test payments never accrue cuts. The durable cut consumer may briefly lag payment confirmation.
- Friendlies (integration active): every split carries a `friendlies` side beside total / straight / subscription (totals, each day, each group), and the `total` figures leave the Friendlies sales out. groupBy=source adds a `friendlies` group whose total and days ARE its Friendlies figures. With the unified filter source=friendlies, or a drill step {"dim":"source","key":"friendlies"}, totals.total and every days[].total are the Friendlies figures. Without the integration, Friendlies-tagged transactions are excluded from every figure.
- The read runs on the isolated reporting pool (four connections per API process, shared with report jobs, never with charges) inside one read-only repeatable-read snapshot, so every figure of one response comes from the same database instant. It has a 25-second budget, including the wait for a connection: past it the SQL is cancelled and the answer is 504. Its own 366-day validation is stricter than the 400-day limit of the synchronous reads. A client that disconnects cancels its SQL. Use POST /v1/metrics/jobs with kind=financial for a heavy cut.

#### Report jobs

Run any dashboard report in the background: start, follow, cancel and read the result. The dashboard pages use these for every long report.

- A job is visible to the principal that started it (Part 1). `kind` and `query` are those of the synchronous report: main = `GET /v1/metrics`, financial, checkouts, traffic, bins, products, segments, three-ds, product-matching, schedule-selection. An account has at most 3 active report jobs.

##### `GET /v1/metrics/jobs`

**Scope** `reports.read` - **List dashboard report calculations**

Lists the dashboard report jobs (the background form of GET /v1/metrics and its sub-reports); Reporting API jobs are a separate family listed by GET /v1/report-jobs. List up to 50 report jobs of this credential and permission scope that are active or not yet expired: active first, then newest. Never includes results.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string (enum) | no | Only this report kind (same values as POST). |
| `query` | string (JSON object, max 20000 chars) | no | URL-encoded JSON object; only jobs whose stored query is exactly equal are returned (to find an earlier run of the same report). |

**Response**

```json
{
  "jobs": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "kind": "checkouts",
      "query": {
        "from": "2026-11-01",
        "to": "2026-11-18",
        "tz": "America/New_York"
      },
      "query_key": "5f2c9a0e1b",
      "status": "running",
      "cancel_requested": false,
      "attempts": 1,
      "error": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:02.000Z",
      "finished_at": null,
      "expires_at": "2026-11-21T10:00:00.000Z",
      "progress": {
        "completed": 0,
        "total": 1
      },
      "recalculateRequired": false,
      "resultState": "pending",
      "total": 1,
      "processed": 0,
      "failed": 0
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[]` | object[] | Job objects (same fields as GET /v1/metrics/jobs/:jobId, without lease fields), at most 50. |

**Errors**

- `400` Invalid query (kind unknown or query longer than 20000 characters); or Invalid query filter (query is not a JSON object).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module reports). Report access changed (body {"error","code":"REPORT_ACCESS_CHANGED"} with one of: "Report permissions changed. Calculate a new report.", "Report API key access changed" (key disabled, scopes changed, owner banned), "This older report has no verified principal. Calculate a new report.", "Report user access changed", "Report role access changed").
- `503` Authentication scope is temporarily unavailable. the database lock-timeout message (for example "canceling statement due to lock timeout") when a report control lock was not available within 1 s; retry.
- `504` The request took too long and was cancelled (the report control deadline of up to 15 s expired); retry.

**Gotchas**

- A query filter must match the stored query exactly (same keys and string values).

##### `POST /v1/metrics/jobs`

**Scope** `reports.write` - **Start a dashboard report calculation in the background**

Queues a dashboard report in the background (kinds main, financial, checkouts, traffic, bins, products, segments, three-ds, product-matching, schedule-selection: the background form of GET /v1/metrics and its sub-reports); Reporting API reports are queued with POST /v1/report-jobs, a separate family. Queue a report calculation and answer 202 once it is admitted (validated, scoped and committed). Poll GET /v1/metrics/jobs/:jobId, then read GET /v1/metrics/jobs/:jobId/result. The same requestId replays the same job; an identical active report of the same credential is shared instead of duplicated.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string (enum) | **yes** | Report kind: main, financial, checkouts, traffic, bins, products, segments, three-ds, product-matching or schedule-selection. Partner kinds are not accepted here (use /v1/report-jobs). |
| `query` | object | **yes** | Parameters of the report, as an object of strings (the same keys and values the synchronous report takes as query string): main = GET /v1/metrics; financial = GET /v1/metrics/financial; checkouts = GET /v1/metrics/checkouts; traffic = GET /v1/metrics/traffic; bins = GET /v1/metrics/bins; products = GET /v1/metrics/products; segments = GET /v1/metrics/segments; three-ds, product-matching and schedule-selection have no synchronous twin. Every key is listed below as query.<key>, with the kinds that accept it. Unknown keys are refused by the strict report schemas. affiliate and flow filter ids must belong to the account. |
| `query.from` | string (ISO 8601 date or date-time) | no | Range start, every kind except schedule-selection. main, financial, checkouts, traffic, bins, products, segments: the same value as the synchronous report. three-ds and product-matching: default the start of the current UTC day. Sent as a string inside query, like the query string of the synchronous report. |
| `query.to` | string (ISO 8601 date or date-time) | no | Range end, every kind except schedule-selection. main, financial, checkouts, traffic, bins, products, segments: the same value as the synchronous report. three-ds and product-matching: default now. Sent as a string inside query, like the query string of the synchronous report. |
| `query.hours` | integer 1..8760 | no | Kinds main, products, segments: trailing window in hours (default 24), used when from is absent. Sent as a string inside query, like the query string of the synchronous report. |
| `query.tz` | string <= 64 (IANA timezone) | no | Kinds main, financial, checkouts, traffic, bins, products, segments: the clock of calendar days, buckets and the hour filter; default the account timezone; an unknown zone answers 400. Sent as a string inside query, like the query string of the synchronous report. |
| `query.bucket` | enum: hour \| day | no | Kind main: chart series granularity; without it the series is empty. Sent as a string inside query, like the query string of the synchronous report. |
| `query.atriView` | CSV of ATRI ids (<= 4000 characters) | no | Kinds main, financial: restricts every figure to these ATRIs (cascade-aware); absent = every ATRI. Sent as a string inside query, like the query string of the synchronous report. |
| `query.provider` | string (max 100) | no | three-ds only: a 3DS integration key (for example paay); any other value means all providers. |
| `query.side` | string | no | Kinds main, products: the Straight / Subscription / Both tab, one of straight, subscription, friendlies, both (products validates it and ignores it). Kind three-ds: the traffic side, one of straight, subscription, friendlies, all. Sent as a string inside query, like the query string of the synchronous report. |
| `query.sections` | enum: gateways | no | Kind main: gateways returns only the per-gateway rows (perMid, perWallet, perWire, noGateway) with the same filters and live fees; absent = the whole payload. Sent as a string inside query, like the query string of the synchronous report. |
| `query.groupBy` | string | no | Kind financial: the breakdown dimension (gateway, processor, acquiringBank, company, atri, store, product, method, source, traffic, country, category, gatewayMcc, threeDs, checkout, subscription). Kind checkouts: an optional cross-breakdown (store, gateway, company, category, gatewayMcc, threeDs, subscription, source, method, country). Kind products: product (default) or store. Sent as a string inside query, like the query string of the synchronous report. |
| `query.top` | integer >= 1 (clamped to 50) | no | Kind financial: groups kept before the rest folds into one __other__ row (default 10). Sent as a string inside query, like the query string of the synchronous report. |
| `query.drill` | string (JSON, <= 4000 characters) | no | Kind financial: the drill path, a JSON array of at most 4 {"dim": <groupBy key>, "key": <group key>} steps, each dimension once. Sent as a string inside query, like the query string of the synchronous report. |
| `query.checkoutId` | uuid | no | Kind checkouts: restricts the report to one checkout. Sent as a string inside query, like the query string of the synchronous report. |
| `query.abTestId` | uuid | no | Kind checkouts: only the payments and visitor events attributed to this A/B test. Sent as a string inside query, like the query string of the synchronous report. |
| `query.dims` | CSV string (<= 500 characters) | no | Kind traffic: the dimensions to compute (source, traffic, storefront, device, browser, os, ipType, hour, brand, funding, level, issuer, bin, gateway and the others GET /v1/metrics/traffic lists). Sent as a string inside query, like the query string of the synchronous report. |
| `query.axis` | enum: issuer \| bin | no | Kind bins: rows keyed by issuing bank or by six-digit BIN. Sent as a string inside query, like the query string of the synchronous report. |
| `query.dim` | string | no | Kind bins: optional cut dimension; absent = one row per issuer or BIN (the All view). Sent as a string inside query, like the query string of the synchronous report. |
| `query.limit` | integer 1..10000 | no | Kind bins: page size (default 50). Sent as a string inside query, like the query string of the synchronous report. |
| `query.offset` | integer >= 0 | no | Kind bins: rows to skip, after the sort (default 0). Sent as a string inside query, like the query string of the synchronous report. |
| `query.axisLimit` | integer 1..5000 | no | Kind bins, with dim: how many issuers or BINs the cut covers (the top N by orders, default 100). Sent as a string inside query, like the query string of the synchronous report. |
| `query.sort` | enum: axis \| name \| charges \| approved \| declined \| approvalRate \| grossCents \| aovCents \| refunds \| refundRate \| chargebacks \| chargebackRate \| share | no | Kind bins: the column the list is ordered by before paging (default charges). Sent as a string inside query, like the query string of the synchronous report. |
| `query.dir` | enum: asc \| desc | no | Kind bins: sort direction (default desc). Sent as a string inside query, like the query string of the synchronous report. |
| `query.winners` | enum: 1 | no | Kind products: 1 adds the Winners tables. Sent as a string inside query, like the query string of the synchronous report. |
| `query.mode` | enum: rebill \| refunds | no | Kind segments: which report (default rebill). Sent as a string inside query, like the query string of the synchronous report. |
| `query.<filter>` | string | no | Every kind except schedule-selection: any key of the unified transaction filter catalog, with the names and values of GET /v1/transactions (discover values with GET /v1/filters/facets). Each report accepts the catalog keys its synchronous record lists; an unknown key or value is refused. |
| `query.ids` | array of uuid (1..500) | no | schedule-selection only (required there): schedule ids of this account; ids of other accounts are ignored, and none accessible answers 404. No other key is allowed. |
| `requestId` | uuid | no | Idempotency id. Resubmit the same id and payload after an uncertain answer; a new id calculates again. Generated when omitted. |

**Request body**

```json
{
  "kind": "checkouts",
  "query": {
    "from": "2026-11-01",
    "to": "2026-11-18",
    "tz": "America/New_York"
  },
  "requestId": "22222222-2222-4222-8222-222222222222"
}
```

**Response** `202`

```json
{
  "jobId": "11111111-1111-4111-8111-111111111111",
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "kind": "checkouts",
    "query": {
      "from": "2026-11-01",
      "to": "2026-11-18",
      "tz": "America/New_York"
    },
    "query_key": "5f2c9a0e1b",
    "status": "queued",
    "cancel_requested": false,
    "attempts": 0,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 0,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "pending",
    "total": 1,
    "processed": 0,
    "failed": 0,
    "lease_until": null,
    "next_attempt_at": "2026-11-20T10:00:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | The job id (new, replayed or shared). |
| `job.id` | uuid | Report job id. |
| `job.kind` | string | Report kind. |
| `job.query` | object | The query as submitted. |
| `job.query_key` | string | Fingerprint of the query (identical active jobs are shared). |
| `job.status` | string | queued \| running \| success \| failed \| cancelled. |
| `job.cancel_requested` | boolean | A cancel was requested. |
| `job.attempts` | integer | Worker attempts (a job interrupted 3 times fails with "Report interrupted repeatedly; please retry"). |
| `job.error` | string \| null | Failure text when status=failed. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps. The result is kept until expires_at (24 hours after the job ends); metadata stays listed 7 more days. |
| `job.progress` | object | {completed, total} report work units; use completed / total for progress. |
| `job.recalculateRequired` | boolean | True when the saved result was produced by report logic that is no longer deployed. |
| `job.resultState` | string | ready \| pending \| obsolete. |
| `job.total / processed / failed` | integer | Legacy whole-job counters (always total 1). |
| `job.lease_until / next_attempt_at` | string (ISO 8601) \| null | Worker scheduling fields, present only on the job returned at creation and on a cancel that changed the job. |

**Errors**

- `400` Invalid report (details: zod flatten; unknown key, bad kind, query not an object, bad requestId); Invalid report parameters (the kind query failed its schema or timezone check; details names the fields); Invalid schedule selection; Unknown affiliate filter; or Unknown flow filter.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module reports). Report access changed (body {"error","code":"REPORT_ACCESS_CHANGED"} with one of: "Report permissions changed. Calculate a new report.", "Report API key access changed" (key disabled, scopes changed, owner banned), "This older report has no verified principal. Calculate a new report.", "Report user access changed", "Report role access changed").
- `404` Not found (schedule-selection: none of the ids is a schedule of this account).
- `409` Three reports are already running for this account. Wait or cancel one.; or Request ID already used for a different report.
- `413` Body larger than 64 KB.
- `503` Authentication scope is temporarily unavailable. Report storage is temporarily unavailable; Schedule report storage is temporarily unavailable; or the database lock-timeout message (for example "canceling statement due to lock timeout") when a report control lock was not available within 1 s; retry.
- `504` The request took too long and was cancelled (the report control deadline of up to 15 s expired); retry.

**Gotchas**

- At most three queued or running reports per account (all credentials together); cancel obsolete ones before starting more.
- A result is served only while the report logic that produced it is still deployed; after an API release it becomes obsolete (resultState obsolete, result 410). Submit a new requestId to recalculate; replaying the old requestId returns the old job.
- Each job reads one read-only snapshot, so every figure of a result comes from the same database instant.
- Trailing ranges (no from/to) are frozen at submission.

##### `GET /v1/metrics/jobs/:jobId`

**Scope** `reports.read` - **Read a dashboard report calculation's progress**

Reads the progress of a dashboard report job; a Reporting API job id (POST /v1/report-jobs) answers 404 here. Read one report job (status, progress, error). Optionally wait up to 10 s for it to finish, and optionally receive the result in the same answer.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A value that is not a uuid answers 404. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `waitMs` | integer (0..10000); default `0` | no | While the job is queued or running, wait up to this long (capped by the request budget) for it to finish before answering; permissions are checked again before answering. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Accept` | string | no | Exactly "application/json; include=report-result" to also receive result when the job succeeded, is current and not expired. |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "kind": "checkouts",
    "query": {
      "from": "2026-11-01",
      "to": "2026-11-18",
      "tz": "America/New_York"
    },
    "query_key": "5f2c9a0e1b",
    "status": "success",
    "cancel_requested": false,
    "attempts": 1,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:02.000Z",
    "finished_at": "2026-11-20T10:00:09.000Z",
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 1,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "ready",
    "total": 1,
    "processed": 1,
    "failed": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Report job id. |
| `job.kind` | string | Report kind. |
| `job.query` | object | The query as submitted. |
| `job.query_key` | string | Fingerprint of the query (identical active jobs are shared). |
| `job.status` | string | queued \| running \| success \| failed \| cancelled. |
| `job.cancel_requested` | boolean | A cancel was requested. |
| `job.attempts` | integer | Worker attempts (a job interrupted 3 times fails with "Report interrupted repeatedly; please retry"). |
| `job.error` | string \| null | Failure text when status=failed. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps. The result is kept until expires_at (24 hours after the job ends); metadata stays listed 7 more days. |
| `job.progress` | object | {completed, total} report work units; use completed / total for progress. |
| `job.recalculateRequired` | boolean | True when the saved result was produced by report logic that is no longer deployed. |
| `job.resultState` | string | ready \| pending \| obsolete. |
| `job.total / processed / failed` | integer | Legacy whole-job counters (always total 1). |
| `job.lease_until / next_attempt_at` | string (ISO 8601) \| null | Worker scheduling fields, present only on the job returned at creation and on a cancel that changed the job. |
| `result` | object (optional) | Present only with the include=report-result Accept header and a ready, unexpired result; same body as GET /v1/metrics/jobs/:jobId/result. |

**Errors**

- `400` Invalid wait duration.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module reports). Report access changed (body {"error","code":"REPORT_ACCESS_CHANGED"} with one of: "Report permissions changed. Calculate a new report.", "Report API key access changed" (key disabled, scopes changed, owner banned), "This older report has no verified principal. Calculate a new report.", "Report user access changed", "Report role access changed").
- `404` Not found (jobId not a uuid); or Not found or report permissions changed.
- `503` Authentication scope is temporarily unavailable. the database lock-timeout message (for example "canceling statement due to lock timeout") when a report control lock was not available within 1 s; retry.
- `504` The request took too long and was cancelled (the report control deadline of up to 15 s expired); retry.

**Gotchas**

- No result is included without the exact Accept value; status alone is not enough to reuse a result, check resultState.

##### `POST /v1/metrics/jobs/:jobId/cancel`

**Scope** `reports.write` - **Cancel a dashboard report calculation**

Cancels a dashboard report job; Reporting API jobs are cancelled with POST /v1/report-jobs/:jobId/cancel. Request cancellation: a queued job is cancelled at once, a running job stops cooperatively at the worker. On a finished job nothing changes and the job is returned. Safe to repeat. No body.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A value that is not a uuid answers 404. |

**Response**

```json
{
  "job": {
    "id": "11111111-1111-4111-8111-111111111111",
    "kind": "checkouts",
    "query": {
      "from": "2026-11-01",
      "to": "2026-11-18",
      "tz": "America/New_York"
    },
    "query_key": "5f2c9a0e1b",
    "status": "cancelled",
    "cancel_requested": true,
    "attempts": 1,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:02.000Z",
    "finished_at": "2026-11-20T10:00:03.000Z",
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 0,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "pending",
    "total": 1,
    "processed": 0,
    "failed": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Report job id. |
| `job.kind` | string | Report kind. |
| `job.query` | object | The query as submitted. |
| `job.query_key` | string | Fingerprint of the query (identical active jobs are shared). |
| `job.status` | string | queued \| running \| success \| failed \| cancelled. |
| `job.cancel_requested` | boolean | A cancel was requested. |
| `job.attempts` | integer | Worker attempts (a job interrupted 3 times fails with "Report interrupted repeatedly; please retry"). |
| `job.error` | string \| null | Failure text when status=failed. |
| `job.created_at / updated_at / finished_at / expires_at` | string (ISO 8601) \| null | Timestamps. The result is kept until expires_at (24 hours after the job ends); metadata stays listed 7 more days. |
| `job.progress` | object | {completed, total} report work units; use completed / total for progress. |
| `job.recalculateRequired` | boolean | True when the saved result was produced by report logic that is no longer deployed. |
| `job.resultState` | string | ready \| pending \| obsolete. |
| `job.total / processed / failed` | integer | Legacy whole-job counters (always total 1). |
| `job.lease_until / next_attempt_at` | string (ISO 8601) \| null | Worker scheduling fields, present only on the job returned at creation and on a cancel that changed the job. |
| `job.__wake` | string | Internal notification column, present (empty) when the cancel changed the job; ignore it. |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module reports). Report access changed (body {"error","code":"REPORT_ACCESS_CHANGED"} with one of: "Report permissions changed. Calculate a new report.", "Report API key access changed" (key disabled, scopes changed, owner banned), "This older report has no verified principal. Calculate a new report.", "Report user access changed", "Report role access changed").
- `404` Not found.
- `503` Authentication scope is temporarily unavailable. the database lock-timeout message (for example "canceling statement due to lock timeout") when a report control lock was not available within 1 s; retry.
- `504` The request took too long and was cancelled (the report control deadline of up to 15 s expired); retry.

##### `GET /v1/metrics/jobs/:jobId/result`

**Scope** `reports.read` - **Read a completed dashboard report**

Returns the result of a completed dashboard report job; a Reporting API job's result is read with GET /v1/report-jobs/:jobId/result. Return the finished report, in the same response shape as the synchronous report endpoint of its kind (for three-ds and product-matching: {range, metrics}).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A value that is not a uuid answers 404. |

**Response**

```json
{
  "range": {
    "from": "2026-11-20T00:00:00.000Z",
    "to": "2026-11-20T10:00:00.000Z"
  },
  "metrics": {
    "charges": 120,
    "approved": 96,
    "applied": {
      "charges": 84,
      "approved": 74,
      "declined": 10
    },
    "attempted": {
      "charges": 6,
      "approved": 4,
      "declined": 2
    },
    "reserved": {
      "charges": 0,
      "approved": 0,
      "declined": 0
    },
    "none": {
      "charges": 30,
      "approved": 18,
      "declined": 12
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job.progress` | {completed:number,total:number} | Actual report work units. Use completed / total for progress; legacy job.total / processed count whole jobs, not report sections. |
| `job.recalculateRequired` | boolean | True when a saved result is incompatible with the current report version. |
| `job.resultState` | ready \| pending \| obsolete | Availability and version state; status alone is insufficient to reuse a saved result. |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module reports). Report access changed (body {"error","code":"REPORT_ACCESS_CHANGED"} with one of: "Report permissions changed. Calculate a new report.", "Report API key access changed" (key disabled, scopes changed, owner banned), "This older report has no verified principal. Calculate a new report.", "Report user access changed", "Report role access changed").
- `404` Not found (jobId not a uuid); or Not found or report permissions changed.
- `409` Report is not ready.
- `410` This saved report is outdated. Recalculate it to get a current result. (code report_result_obsolete, recalculateRequired true); or Report expired. Calculate it again.
- `503` Authentication scope is temporarily unavailable. the database lock-timeout message (for example "canceling statement due to lock timeout") when a report control lock was not available within 1 s; retry.
- `504` The request took too long and was cancelled (the report control deadline of up to 15 s expired); retry.

**Gotchas**

- Results expire 24 hours after the job ends; a release of the report logic makes older results obsolete even before that.

#### Partner reports

The Reporting API: frozen projections with a stable shape (/v1/reports/*), their background jobs and the daily status snapshot.

##### `GET /v1/report-jobs`

**Scope** `reports.read` - **List Reporting API report calculations**

Lists Reporting API report jobs (the background form of /v1/reports/*); the dashboard report jobs are a separate family listed by GET /v1/metrics/jobs. List up to 50 partner report jobs of this key and scope (active first, then newest; expired finished jobs drop out). Metadata only, no result payloads.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "kind": "partner-products",
      "query": {
        "from": "2026-09-01",
        "to": "2026-09-30",
        "tz": "UTC"
      },
      "status": "queued",
      "cancel_requested": false,
      "attempts": 0,
      "error": null,
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:00.000Z",
      "finished_at": null,
      "expires_at": "2026-11-21T10:00:00.000Z",
      "progress": {
        "completed": 0,
        "total": 1
      },
      "recalculateRequired": false,
      "resultState": "pending",
      "total": 1,
      "processed": 0,
      "failed": 0
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[].id` | uuid | Report job id. |
| `jobs[].kind` | string | partner-transactions, partner-gateways, partner-products or partner-segments. |
| `jobs[].query` | object | The query you submitted. |
| `jobs[].status` | string | queued, running, success, failed or cancelled. |
| `jobs[].error` | string\|null | Failure message of a failed job. |
| `jobs[].progress` | object | {completed,total} calculation stages (total 1 for partner reports). |
| `jobs[].resultState` | string | pending, ready or obsolete (computed by an earlier API release: recalculate). |
| `jobs[].recalculateRequired` | boolean | true when resultState is obsolete. |
| `jobs[].total / processed / failed` | integer | Legacy counters: 1 / 1 when success / 1 when failed. |
| `jobs[].cancel_requested, attempts, created_at, updated_at, finished_at, expires_at, query_key` | mixed | Bookkeeping; the result is served until expires_at (24 hours). |

**Errors**

- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Report storage is temporarily unavailable","requestId":"<id>"} when the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- The key, its owner and the current tenant scope are rechecked before execution, while running and on delivery. A job is visible only to the key that created it under the same scope: another key of the same account cannot read or cancel it.

##### `POST /v1/report-jobs`

**Scope** `reports.write` - **Calculate a Reporting API report in the background**

Queues a Reporting API report (kinds transactions, gateways, products, segments: the background form of /v1/reports/*); dashboard reports (main, financial, bins, traffic...) are queued with POST /v1/metrics/jobs, a separate family. Accepts {kind,query,requestId}; kind is transactions, gateways, products or segments. query is exactly the matching GET /v1/reports/{kind} query object. requestId is a required UUID. Returns 202 {jobId,job} only after durable COMMIT. Retry an uncertain submission with the same UUID and parameters. Reusing a UUID with different parameters or scope returns 409. The absolute date window is frozen at first acceptance.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | enum: transactions\|gateways\|products\|segments | **yes** | Which partner report to calculate. |
| `query` | object | **yes** | Exactly the query parameters of the matching synchronous report (GET /v1/reports/transactions, /gateways, /products or /segments), as a JSON object of strings; it is validated with that endpoint's schema. affiliate (CSV of ids or none), flow and storefront (including __no_store__) are checked against the account. |
| `requestId` | uuid | **yes** | Idempotency key: retry an uncertain submission with the same id and body; the same id with other parameters answers 409. |

**Request body**

```json
{
  "kind": "products",
  "query": {
    "from": "2026-09-01",
    "to": "2026-09-30",
    "tz": "UTC"
  },
  "requestId": "00000000-0000-4000-8000-000000000002"
}
```

**Response** `202`

```json
{
  "jobId": "00000000-0000-4000-8000-000000000001",
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "kind": "partner-products",
    "query": {
      "from": "2026-09-01",
      "to": "2026-09-30",
      "tz": "UTC"
    },
    "status": "queued",
    "cancel_requested": false,
    "attempts": 0,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 0,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "pending",
    "total": 1,
    "processed": 0,
    "failed": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | The job id. |
| `job.id` | uuid | Report job id. |
| `job.kind` | string | partner-transactions, partner-gateways, partner-products or partner-segments. |
| `job.query` | object | The query you submitted. |
| `job.status` | string | queued, running, success, failed or cancelled. |
| `job.error` | string\|null | Failure message of a failed job. |
| `job.progress` | object | {completed,total} calculation stages (total 1 for partner reports). |
| `job.resultState` | string | pending, ready or obsolete (computed by an earlier API release: recalculate). |
| `job.recalculateRequired` | boolean | true when resultState is obsolete. |
| `job.total / processed / failed` | integer | Legacy counters: 1 / 1 when success / 1 when failed. |
| `job.cancel_requested, attempts, created_at, updated_at, finished_at, expires_at, query_key` | mixed | Bookkeeping; the result is served until expires_at (24 hours). |

**Errors**

- `400` {"error":"Invalid report","details":<zod flatten()>} (body not exactly {kind, query, requestId}), {"error":"Invalid request","details":<zod flatten()>} (query invalid for that report), {"error":"Unknown flow filter"} or {"error":"Unknown affiliate filter"}.
- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"An account is required"}: affiliate or flow filters sent with a key that has no account.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `409` {"error":"Three reports are already running for this account. Wait or cancel one."} or {"error":"Request ID already used for a different report"}.
- `413` Body larger than 64 KiB.
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Background partner reports are temporarily disabled","requestId":"<id>"} when background workers are off, {"error":"Report storage is temporarily unavailable","requestId":"<id>"} when the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- The synchronous GET /v1/reports/* endpoints stay available; this job contract is for long calculations: submit, poll, then read the result.
- At most three active reports per account. Results are kept 24 hours and limited to 32 MiB; narrow the filters rather than expecting truncation.
- The key, its owner and the current tenant scope are rechecked before execution, while running and on delivery. A job is visible only to the key that created it under the same scope: another key of the same account cannot read or cancel it.
- Each job reads one read-only snapshot; no payment, refund or gateway change is ever issued.
- 202 is sent only after the admission committed. The absolute date window is frozen at the first acceptance. The body is strict and limited to 64 KiB.

##### `GET /v1/report-jobs/:jobId`

**Scope** `reports.read` - **Read a Reporting API report calculation's progress**

Reads a Reporting API job's progress; a dashboard report job id (POST /v1/metrics/jobs) answers 404 here and is read with GET /v1/metrics/jobs/:jobId. Read one partner report job: status, error and progress. Poll once per second or slower.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A non-uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "kind": "partner-products",
    "query": {
      "from": "2026-09-01",
      "to": "2026-09-30",
      "tz": "UTC"
    },
    "status": "success",
    "cancel_requested": false,
    "attempts": 0,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 1,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "ready",
    "total": 1,
    "processed": 1,
    "failed": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Report job id. |
| `job.kind` | string | partner-transactions, partner-gateways, partner-products or partner-segments. |
| `job.query` | object | The query you submitted. |
| `job.status` | string | queued, running, success, failed or cancelled. |
| `job.error` | string\|null | Failure message of a failed job. |
| `job.progress` | object | {completed,total} calculation stages (total 1 for partner reports). |
| `job.resultState` | string | pending, ready or obsolete (computed by an earlier API release: recalculate). |
| `job.recalculateRequired` | boolean | true when resultState is obsolete. |
| `job.total / processed / failed` | integer | Legacy counters: 1 / 1 when success / 1 when failed. |
| `job.cancel_requested, attempts, created_at, updated_at, finished_at, expires_at, query_key` | mixed | Bookkeeping; the result is served until expires_at (24 hours). |

**Errors**

- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `404` {"error":"Not found"} (jobId not a uuid) or {"error":"Not found or report permissions changed"}.
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Report storage is temporarily unavailable","requestId":"<id>"} when the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- The key, its owner and the current tenant scope are rechecked before execution, while running and on delivery. A job is visible only to the key that created it under the same scope: another key of the same account cannot read or cancel it.

##### `POST /v1/report-jobs/:jobId/cancel`

**Scope** `reports.write` - **Cancel a Reporting API report calculation**

Cancels a Reporting API job; dashboard report jobs are cancelled with POST /v1/metrics/jobs/:jobId/cancel. Cancels queued work immediately and requests active PostgreSQL cancellation for running work. Cancellation and history remain available when new partner admission is disabled. A running cancellation is cooperative and remains running until SQL has drained.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A non-uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "kind": "partner-products",
    "query": {
      "from": "2026-09-01",
      "to": "2026-09-30",
      "tz": "UTC"
    },
    "status": "cancelled",
    "cancel_requested": true,
    "attempts": 0,
    "error": null,
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null,
    "expires_at": "2026-11-21T10:00:00.000Z",
    "progress": {
      "completed": 0,
      "total": 1
    },
    "recalculateRequired": false,
    "resultState": "pending",
    "total": 1,
    "processed": 0,
    "failed": 0
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Report job id. |
| `job.kind` | string | partner-transactions, partner-gateways, partner-products or partner-segments. |
| `job.query` | object | The query you submitted. |
| `job.status` | string | queued, running, success, failed or cancelled. |
| `job.error` | string\|null | Failure message of a failed job. |
| `job.progress` | object | {completed,total} calculation stages (total 1 for partner reports). |
| `job.resultState` | string | pending, ready or obsolete (computed by an earlier API release: recalculate). |
| `job.recalculateRequired` | boolean | true when resultState is obsolete. |
| `job.total / processed / failed` | integer | Legacy counters: 1 / 1 when success / 1 when failed. |
| `job.cancel_requested, attempts, created_at, updated_at, finished_at, expires_at, query_key` | mixed | Bookkeeping; the result is served until expires_at (24 hours). |

**Errors**

- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `404` {"error":"Not found"} (jobId not a uuid) or {"error":"Not found or report permissions changed"}.
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Report storage is temporarily unavailable","requestId":"<id>"} when the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- A running job stops cooperatively and may stay running until its SQL is cancelled. Cancelling works even while new admissions are disabled.
- The key, its owner and the current tenant scope are rechecked before execution, while running and on delivery. A job is visible only to the key that created it under the same scope: another key of the same account cannot read or cancel it.

##### `GET /v1/report-jobs/:jobId/result`

**Scope** `reports.read` - **Read a completed Reporting API report**

Returns the result of a Reporting API job (the body of the matching GET /v1/reports/<kind>); a dashboard report's result is read with GET /v1/metrics/jobs/:jobId/result. Return the saved result of a successful partner report job: the same body the synchronous GET /v1/reports/<kind> would have returned for that query.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Report job id. A non-uuid answers 404 {"error":"Not found"}. |

**Response**

```json
{
  "from": "2026-09-01",
  "to": "2026-09-30",
  "rows": []
}
```

**Errors**

- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `404` {"error":"Not found"} (jobId not a uuid) or {"error":"Not found or report permissions changed"}.
- `409` {"error":"Report is not ready"}: status is not success.
- `410` {"error":"Report expired; request a new calculation"} or {"error":"This saved report is outdated. Recalculate it to get a current result.","code":"report_result_obsolete"} (obsolete result).
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Report storage is temporarily unavailable","requestId":"<id>"} when the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- A result computed by an earlier API release is obsolete (410) even inside its 24-hour retention: submit a new job with a new requestId.
- The key, its owner and the current tenant scope are rechecked before execution, while running and on delivery. A job is visible only to the key that created it under the same scope: another key of the same account cannot read or cancel it.

##### `GET /v1/report-jobs/capabilities`

**Scope** `reports.read` - **Read Reporting API background availability**

Tells whether Reporting API background jobs are available and their limits; the dashboard report jobs (POST /v1/metrics/jobs) are gated by GET /v1/operation-capabilities instead. Authenticate before choosing the optional asynchronous contract. A failed capability request is not permission to replay an uncertain submission.

*No parameters.*

**Response**

```json
{"enabled":true,"kinds":["transactions","gateways","products","segments"],"maxActivePerAccount":3,"resultRetentionHours":24,"maxResultBytes":33554432}
```

**Errors**

- `401` {"error":"Missing API key","code":"REPORT_ACCESS_CHANGED"} (no Authorization: Bearer or X-API-Key) or {"error":"Invalid API key","code":"REPORT_ACCESS_CHANGED"}.
- `403` {"error":"Account access is disabled","code":"REPORT_ACCESS_CHANGED"} (key owner banned) or {"error":"API key scope denied","code":"REPORT_ACCESS_CHANGED"} (the key lacks this operation's reports scope).
- `403` {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner (global bot guard).
- `429` Per-IP rate limit of these routes exceeded (RATE_LIMIT_STATUS, default 60 requests per minute).
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"error":"Required storage for partner reports is unavailable. Complete the current database migrations.","requestId":"<id>"} when background workers are on but the report storage is missing, or the database lock-timeout message (for example {"error":"canceling statement due to lock timeout","requestId":"<id>"}) when a lock could not be taken within 1 s; Retry-After: 1, retry later.
- `504` "The request took too long and was cancelled - narrow the range and retry." when the control transaction runs past its statement budget.

**Gotchas**

- The synchronous GET /v1/reports/* endpoints stay available; this job contract is for long calculations: submit, poll, then read the result.
- At most three active reports per account. Results are kept 24 hours and limited to 32 MiB; narrow the filters rather than expecting truncation.

##### `GET /v1/reports/gateways`

**Scope** `reports.read` - **Gateway report (Reporting API: stable shape)**

Reporting API gateway report: a stable projection of the dashboard metrics computation with a trailing-hours default and a 92-day cap; GET /v1/metrics is the dashboard version (Straight / Subscription split, ad spend). The full dashboard KPI payload for the calling account over a window: global totals and approval rates, per-MID and per-wallet performance and finance, per-ATRI splits, top decline reasons, request outcomes, breakdowns by store/traffic/brand/order-source, and an optional time series. Read-only; forwards to the same chargeMetricsBetween() the UI uses. v3.9.13 - the dashboard tab's `side` is never read here (no side / sideTotals / sideFinance / walletTraffic key; `series[].completed` is projected out). BEHAVIOUR CHANGE: under a dimension filter or pass=initial, `finance.transactionFeeCents` (and so `finance.netCents`) is now the unfiltered window's (see `finance`).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD) | no | Window start, inclusive. v3.9.15 - an ISO instant (any offset, e.g. 2026-08-01T00:00:00Z or 2026-08-01T00:00:00+02:00) or a YYYY-MM-DD day read in `tz` (its first millisecond); anything else is a 400. Max 40 characters. |
| `to` | string (ISO 8601 instant or YYYY-MM-DD); default `now` | no | Window end, inclusive. Defaults to now. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). Max 40 characters. Must not be before from (400 "to is before from"). The range from..to may span at most 92 days (400 with details.range). |
| `hours` | integer; default `24` | no | Trailing-window size in hours (1..8760), used only when `from` is absent. NOTE: the `windowHours` in the response is NOT this value - it is recomputed as round((to-from)/1h), floored at 1. |
| `tz` | string (IANA timezone); default `UTC` | no | IANA timezone, max 64 characters: buckets the series labels and reads a YYYY-MM-DD range and the hour filter (UTC when absent). An unknown zone or an empty tz= is a 400 "not a known IANA timezone" (with hour set: "hour needs a valid tz"). |
| `bucket` | enum: hour \| day | no | Time-series granularity. OMITTING IT RETURNS `series: []` - there is no default bucket. 'hour' labels are 'HH24:00', 'day' labels are 'MM-DD' (no year). |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: store host bucket(s), CSV, matched on the bare lowercased host (the full storefront_url of a row does not match). Add __no_store__ to select canonical standalone orders (orders with no store context, not a blank-URL test). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: flow UUIDs from the immutable checkout session version (not the current store assignment), CSV; none selects orders with no flow. An id that is not one of the account's flows answers 400 {"error":"Invalid request"}. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: affiliate UUIDs from the immutable payment attribution, CSV; none selects orders with no affiliate. Disabled affiliates of the account stay valid for history; an id that is not one of the account's affiliates answers 400 {"error":"Invalid request"} (never an unfiltered result). Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "windowHours": 24,
  "totals": {
    "total": 1482,
    "approved": 812,
    "declined": 601,
    "error": 44,
    "unknown": 7,
    "pending": 12,
    "duplicate": 6,
    "blocked": 0, "completed": 1464, "approvalRate": 0.5546,
    "approvedCents": 4187600,
    "avgLatencyMs": 1840,
    "p95LatencyMs": 4210,
    "approvalRateExApplePay": 0.5122,
    "completedExApplePay": 1301,
    "approvedExApplePay": 666,
    "applePayApprovalRate": 0.8931,
    "applePayCompleted": 163,
    "applePayApproved": 146
  },
  "perMid": [
    {
      "id": "3f1c9a04-2b77-4c58-9d1e-6a0b2f7d5c31",
      "name": "Atlas MID 03",
      "activated": true,
      "charges": 640,
      "approved": 371,
      "declined": 251,
      "approvalRate": 0.5797,
      "approvalRateMidFixable": 0.7412,
      "midFixableDenom": 501,
      "attempts": 702,
      "arAttempts": 0.5285,
      "classicAttempts": 612,
      "arClassic": 0.5588,
      "cascadeAttempts": 90,
      "arCascade": 0.3222,
      "monthlyCapCents": 50000000,
      "usedCents": 18742300,
      "atris": ["Checkout US", "Rebill US"],
      "processorId": "a1b2c3d4-0000-4000-8000-000000000001",
      "processorName": "PRIORITY",
      "acquiringBankId": "a1b2c3d4-0000-4000-8000-000000000002",
      "acquiringBankName": "SYNOVUS",
      "companyId": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
      "companyName": "STELLAR TIDE LLC",
      "sentCents": 3120400,
      "routedCents": 3894100,
      "grossCents": 1902300,
      "discountFeeCents": 55167,
      "transactionFeeCents": 21060,
      "reserveCents": 95115,
      "refundCents": 24900,
      "refundCount": 4,
      "refundFeesCents": 1200,
      "chargebackCents": 9998,
      "chargebackCount": 1,
      "chargebackFeesCents": 2500,
      "netCents": 1692360
    }
  ],
  "perWallet": [
    {
      "name": "Apple Pay",
      "processorId": "a1b2c3d4-0000-4000-8000-000000000003",
      "processorName": "CONVESIO PAY",
      "acquiringBankId": "a1b2c3d4-0000-4000-8000-000000000004",
      "acquiringBankName": "ADYEN",
      "companyId": "7d2e5c19-3b8a-4f61-9e0c-2a4b6d8f1c35",
      "companyName": "STELLAR TIDE LLC",
      "charges": 163,
      "approved": 146,
      "declined": 15,
      "approvalRate": 0.8957,
      "grossCents": 728500,
      "discountFeeCents": 21127,
      "transactionFeeCents": 4380,
      "reserveCents": 36425,
      "refundCents": 0,
      "refundCount": 0,
      "refundFeesCents": 0,
      "chargebackCents": 0,
      "chargebackCount": 0,
      "chargebackFeesCents": 0,
      "netCents": 666568
    }
  ],
  "declineReasons": [
    {
      "reason": "Insufficient funds",
      "count": 212,
      "byMid": [
        { "name": "Atlas MID 03", "count": 140 },
        { "name": "Vertex MID 01", "count": 72 }
      ]
    }
  ],
  "requestOutcomes": [
    { "outcome": "approved", "count": 812 },
    { "outcome": "declined", "count": 601 }
  ],
  "perAtri": [
    {
      "id": "c4b1e0aa-9f52-4e18-8c77-1d3a5b90e442",
      "name": "Checkout US",
      "type": "classic",
      "total": 1120,
      "approved": 640,
      "declined": 448,
      "error": 28,
      "unknown": 4,
      "approvalRate": 0.5714,
      "approvedCents": 3288000,
      "p95LatencyMs": 4020
    },
    {
      "id": "__no_atri__",
      "name": "Wallet / no ATRI",
      "type": "classic",
      "total": 163,
      "approved": 146,
      "declined": 15,
      "error": 2,
      "unknown": 0,
      "approvalRate": 0.8957,
      "approvedCents": 728500,
      "p95LatencyMs": 0
    }
  ],
  "authFailures": [
    { "id": "8a2d55f1-0c3e-4a91-b0d2-77e4c9a11b60", "name": "Vertex MID 01", "count": 6 }
  ],
  "finance": {
    "grossCents": 4187600,
    "discountFeeCents": 121440,
    "transactionFeeCents": 25440,
    "reserveCents": 209380,
    "refundCents": 24900,
    "refundFeesCents": 1200,
    "chargebackCents": 9998,
    "chargebackFeesCents": 2500,
    "netCents": 3792742
  },
  "refunds": { "amountCents": 24900, "count": 4, "feesCents": 1200 },
  "chargebacks": { "amountCents": 9998, "count": 1, "feesCents": 2500 },
  "perStore": [
    {
      "name": "shop.example.com",
      "charges": 1319,
      "approved": 666,
      "declined": 601,
      "error": 44,
      "approvalRate": 0.5119,
      "approvedCents": 3459100
    }
  ],
  "perTrafficSource": [
    {
      "name": "(direct/organic)",
      "charges": 702,
      "approved": 402,
      "declined": 281,
      "error": 19,
      "approvalRate": 0.5727,
      "approvedCents": 2011400
    }
  ],
  "perCardBrand": [
    {
      "name": "Visa",
      "charges": 890,
      "approved": 470,
      "declined": 390,
      "error": 30,
      "approvalRate": 0.5281,
      "approvedCents": 2402800
    }
  ],
  "perSource": [
    {
      "name": "Straight",
      "charges": 1002,
      "approved": 560,
      "declined": 410,
      "error": 32,
      "approvalRate": 0.5591,
      "approvedCents": 2900100
    },
    {
      "name": "Rebill",
      "charges": 480,
      "approved": 252,
      "declined": 191,
      "error": 12,
      "approvalRate": 0.5540,
      "approvedCents": 1287500
    }
  ],
  "series": [
    { "label": "08:00", "total": 61, "approved": 34, "declined": 25, "approvedCents": 174300 },
    { "label": "09:00", "total": 74, "approved": 41, "declined": 30, "approvedCents": 209800 }
  ]
}
```

| response field | type | description |
|---|---|---|
| `windowHours` | number | Length of the resolved window in hours, RECOMPUTED as round((to-from)/1h) with a floor of 1 - not an echo of the `hours` param. |
| `totals.total` | number | All LIVE transactions in the window (v3.9 section 1 - no test card, no CSV import, no 3DS park; a charge cocoapi refused before any MID is not a transaction), including pending and duplicate. |
| `totals.approved / declined / error / unknown / pending / duplicate` | number | Counts by status over the LIVE rows. v3.9 section 1: `declined` = the MID verdicts, `error` = the technical errors - together every decline of the window; 'unknown' = ambiguous gateway timeout requiring manual review. |
| `totals.approvalRate` | number (ratio 0..1) | approved / totals.completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). 0 when the base is 0. Multiply by 100 for a percentage. |
| `totals.approvedCents` | number | Approved volume in integer CENTS (a real JSON number here - metrics.ts casts bigints with Number()). |
| `totals.avgLatencyMs / p95LatencyMs` | number | Attempt-level latency in milliseconds over transaction_attempts in the window. |
| `totals.approvalRateExApplePay` | number | Ratio 0..1 for card-only traffic (crm <> 'convesio'), with completedExApplePay / approvedExApplePay as its numerator and denominator. |
| `totals.applePayApprovalRate` | number | Ratio 0..1 for wallet traffic (crm = 'convesio'), with applePayCompleted / applePayApproved behind it. |
| `perMid[]` | object[] | One row per MID (nmi_accounts). Every *Cents field is integer cents; every AR field is a ratio 0..1. |
| `perMid[].completed` | number | v3.9 section 1 - the approval rate's base of the row: LIVE orders that ENDED on this MID with status approved, declined, error or unknown (pending and duplicate are out). approvalRate = approved / completed, so a Total / grouped row recomputes sum of approved / sum of completed on it - never approved / charges (charges also counts pending rows). |
| `perMid[].approvalRate` | number (ratio 0..1) | approved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out; orders that ENDED on the MID), final_account-based, so it UNDERCOUNTS the MID's real work (a declined attempt later approved elsewhere is credited to the other MID). |
| `perMid[].approvalRateMidFixable` | number | Ratio 0..1: approved attempts / (approved + WINNABLE declines). Excludes unwinnable cardholder declines (NSF, pick-up, expired). midFixableDenom is its sample size. v3.9 section 1: a timeout is a technical error, so timed-out attempts sit in the winnable denominator next to declined / error ones (ATTEMPT_DECLINED_SQL), and only attempts of LIVE transactions count. |
| `perMid[].attempts / arAttempts / classicAttempts / arClassic / cascadeAttempts / arCascade` | number | Attempt-level counts and their ratios 0..1, split by pass. 'classic' = first-attempt traffic, 'cascade' = failover traffic. |
| `perMid[].sentCents` | number | Cents of orders that ENDED on this MID (final_account_id). |
| `perMid[].routedCents` | number | Cents this MID actually ATTEMPTED. Summing across MIDs deliberately EXCEEDS total volume: a cascaded order is credited to every MID that tried it. |
| `perMid[].monthlyCapCents / usedCents` | number | Monthly cap and current-period usage in cents. usedCents is period-to-date, NOT window-scoped. |
| `perMid[].atris` | string[] | Names of the ATRIs this MID belongs to. Not window-scoped. |
| `perMid[].atriRefs` | object[] | Current ATRI memberships as { id: UUID, name: string } for unambiguous item references. Not window-scoped. Empty when the MID has no ATRI membership. The legacy atris name array remains unchanged; never resolve an ID by its name. |
| `perMid[].processorId / processorName / acquiringBankId / acquiringBankName` | string \| null (each) | v3.9 section 0 - the MID's processor and acquiring bank (nmi_accounts.processor_id / acquiring_bank_id -> the global processors / acquiring_banks reference tables). Names as stored, UPPERCASE ('PRIORITY', 'SYNOVUS'); null when the gateway has none set. Group on them for a per-processor / per-bank view. |
| `perMid[].companyId / companyName` | string \| null (each) | v3.9.2 section 0 - the MID's company (nmi_accounts.company_id -> the global companies reference table: the legal entity - LLC - the MID is boarded under). Name as stored, UPPERCASE ('STELLAR TIDE LLC'); null when the gateway has none set. Group on it for a per-company view. |
| `perMid[].netCents` | number | gross - discount - reserve - per-attempt transaction fees - 3DS fees - refunds - refund fees - chargebacks - chargeback fees. Can be negative. v3.9.6 live fees: every fee line is computed at read time from the MID's CURRENT settings (discount_fee_bps, transaction_fee_cents, reserve_rate_bps, the per-brand refund fees) and the 3DS integration's current rate - a fee edit re-prices every historical row, so the figures of a past range move with the settings. |
| `perWallet[]` | object[] | Wallet / non-NMI traffic, ONE ROW PER WALLET PROVIDER (id = wallet_providers.id or null, name = the provider) x kind ('Apple Pay' \| 'Google Pay' \| 'Wallet'). v3.9.6 live fees: discountFeeCents / reserveCents at the provider's CURRENT bps, transactionFeeCents = ONE flat fee per completed wallet charge (wallet_providers.transaction_fee_cents), threeDsFeeCents at the integration's rate; refundCents / refundCount / refundFeesCents / chargebackCents / chargebackCount / chargebackFeesCents = the refunds and chargebacks of the row's wallet charges (dated by the refund, like perMid), the fee at the provider's CURRENT per-brand rate through the refunded charge - the same figure finance.refundFeesCents / chargebackFeesCents carries, so sum of (perMid + perWallet) reconciles with finance (these six fields were hard-coded to 0 before v3.9.6 while finance priced the same refunds); netCents = gross - every fee line - refunds - chargebacks (wallet rows carried 0 in every fee column before). |
| `perWallet[].processorId / processorName / acquiringBankId / acquiringBankName` | string \| null (each) | v3.9 section 0 - the wallet provider's processor / acquiring bank (wallet_providers.processor_id / acquiring_bank_id), the same reference tables as perMid. All four null on the '(unattributed)' row and when the provider has none set. |
| `perWallet[].companyId / companyName` | string \| null (each) | v3.9.2 section 0 - the wallet provider's company (wallet_providers.company_id), the same reference table as perMid. Both null on the '(unattributed)' row and when the provider has none set. |
| `declineReasons[]` | object[] | Top 10 decline/error/timeout reasons over transaction_attempts (v3.9 section 1 ATTEMPT_DECLINED_SQL, attempts of LIVE transactions only), each with a byMid split sorted desc. Unknown MIDs appear as '(unknown MID)', missing reasons as '(no reason)'. v3.9.8 item 1 - plus the WALLET declines (a wallet charge has no attempts row): the transaction's own decline reason, its MID named '<wallet> - <wallet provider>' (e.g. 'Apple Pay - MY STORE CONVESIO/ADYEN'). |
| `requestOutcomes[]` | object[] | Counts from charge_request_logs by outcome. Scoped by api_key only (no wallet branch), so wallet traffic never appears. |
| `perAtri[]` | object[] | Per-ATRI KPIs. type='classic' counts orders routed to the ATRI; type='cascade' counts DISTINCT orders that reached the cascade pool. A synthetic row with id '__no_atri__' / name 'Wallet / no ATRI' is appended when non-ATRI traffic exists. |
| `authFailures[]` | object[] | MIDs whose attempts failed GATEWAY AUTHENTICATION (bad username/password/security key). This is a config error to fix, not a normal decline. |
| `finance` | object | Window money in/out, all integer cents. transactionFeeCents is PER-ATTEMPT (every non-skipped authorization is billed, approved or not), while discount and reserve are capture-based (approved only). v3.9.13 - BEHAVIOUR CHANGE: transactionFeeCents (and so netCents) is the window's whole per-attempt fee (the unfiltered attempt aggregate + the wallet providers' per-charge fee), like every other finance line. It was the sum of the FILTERED perMid rows, so under a dimension filter or pass=initial the ledger mixed filtered attempt fees with the unfiltered rest. Calls with no filter return the same value as before (checked to the cent on production). |
| `refunds / chargebacks` | object | amountCents and feesCents in integer cents, count as a number. Chargebacks are refunds flagged is_chargeback; they are excluded from `refunds` and counted only here. |
| `perStore[] / perTrafficSource[] / perCardBrand[] / perSource[]` | object[] | Breakdown rows {name, charges, approved, declined, error, blocked, approvalRate, approvedCents}. approvalRate is a ratio 0..1 over completed only (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out); blocked is always 0 (deprecated, removed next release); approvedCents is integer cents. v3.9.10 - perStore[] counts the STRAIGHT sales only (sale + recovery: the subscription charges are not in it): this route never sends `side`, and without it perStore is the straight side; its (other) remainder closes on the straight side (split.straight), so sum of perStore = split.straight. v3.9.13 - the dashboard no longer reads it that way: its Store and Product breakdowns follow the Straight - Subscription - Both tab (GET /v1/metrics `side`; Both, the default, shows every charge and links with no `source`). |
| `series[]` | object[] | Time buckets {label, total, approved, declined, approvedCents}. Empty array unless `bucket` is passed. Labels are 'HH24:00' for hour and 'MM-DD' for day - no year, no date on hour buckets. v3.9.13 - the dashboard's `completed` (GET /v1/metrics series[].completed) is projected out: the partner points keep these five keys. |
| `totals.completed` | number | v3.9 section 1 - the approval rate's base (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). Read it instead of re-summing the buckets: it is what every approvalRate divides by. |
| `totals.blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `perMid[].declined` | number | v3.9 section 1 declines that ended on this MID: MID verdicts AND technical errors (status 'declined' or 'error') - there is no separate error column on this row. |
| `perWallet[].declined` | number | v3.9 section 1 declines on the row (status 'declined' or 'error' - technical errors folded in). |
| `perWallet[].completed` | number | v3.9 section 1 - the approval rate's base of the wallet row (live and completed charges: status approved, declined, error or unknown); approvalRate = approved / completed, and a Total / grouped row recomputes sum of approved / sum of completed on it. |
| `perWallet[].approvalRate` | number (ratio 0..1) | approved / completed for wallet traffic (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out) - the same base as totals.approvalRate since v3.9 section 1. |
| `perAtri[].approvalRate` | number (ratio 0..1) | approved / total (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). |
| `perStore[].blocked / perTrafficSource[].blocked / perCardBrand[].blocked / perSource[].blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `unfilteredFields` | string[] (only under a filter) | Under a filter, unfilteredFields names fields that do not follow the complete selected filter set. Affiliate and No-store selections apply to transaction totals, breakdowns, Friendlies and rejection 3DS fees; only requestOutcomes and subs remain unfiltered for these selections alone. Other or combined dimensions retain the broader list. Absent without narrowing filters. Subscription counts belong to the authenticated key owner; ownerless keys return zero. |
| `perWire` | object[] | One row per bank account receiving wire transfers in the window: amount, approvals, fees and refund events, in the same scope as perMid and perWallet. |
| `noGateway` | object \| null | The "(no gateway)" row: the finance shape of a perWallet row for the charges that ended on no MID and no wallet provider, and their refunds. perMid + perWallet + perWire + noGateway add up to the totals. null when empty. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten() with fieldErrors / formErrors>} for an unknown query parameter (formErrors names it), an unknown value of a closed list ("unknown value: x"), a malformed date, a reversed range pair, an invalid tz, or a value out of bounds; {"error":"Invalid request","details":{"range":"Use a range of at most 92 days, or a report job."}} when from..to spans more than 92 days; {"error":"Invalid request"} (no details) when an affiliate or flow id is not one of the account's.
- `401` {"error":"Missing API key"} when neither Authorization: Bearer nor X-API-Key is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the key's owner is banned; {"error":"An account owner is required for reports"} when the key has no owner; {"error":"Forbidden"} when the User-Agent looks like a crawler.
- `429` Per-IP rate limit of this route: RATE_LIMIT_STATUS requests per minute (default 60, counted per server instance), not the 300 default.
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected query failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the read exceeds its 25-second budget. Narrow the range or the filters.

**Gotchas**

- Strict query: an unknown parameter is a 400 (details.formErrors names it) and an unknown value of a closed list is a 400 naming it, so a misspelt filter never returns unfiltered data.
- At most 92 days per call (from..to, or the trailing hours window). For a longer range use a report job (POST /v1/metrics/jobs).
- Every key of the unified filter catalog is accepted (the same names as the dashboard filter bar); each is listed in params.
- Under a filter, unfilteredFields names fields that do not follow the complete selected filter set. Affiliate and No-store selections apply to transaction totals, breakdowns, Friendlies and rejection 3DS fees; only requestOutcomes and subs remain unfiltered for these selections alone. Other or combined dimensions retain the broader list. Absent without narrowing filters. Subscription counts belong to the authenticated key owner (an ownerless key is refused with 403).
- THE BIG ONE: the dimension filters are only PARTIALLY applied. buildTxDimensionClauses reaches exactly four queries - perMid, the per-MID attempt stats, the per-MID refund rollup, and perWallet. `totals`, `finance`, `refunds`, `chargebacks`, `series`, `perAtri`, `perStore`, `perTrafficSource`, `perCardBrand`, `perSource`, `declineReasons`, `requestOutcomes` and `authFailures` IGNORE every filter and always report the whole window. Do not compare a filtered perMid against unfiltered totals. v3.9.13 - finance.transactionFeeCents now follows this rule too; before, it summed the filtered perMid rows.
- With NO dimension filter set, perMid lists EVERY MID row visible to the query, including MIDs with zero traffic in the window (all-zero rows) - the `having count(t.id) > 0` guard is only added when a filter is present. The account's email is passed as null, so nmi_accounts is not owner-restricted either.
- `series` is EMPTY unless you pass `bucket`. There is no default.
- `series` labels carry no year and hour labels carry no date: bucket=hour gives '09:00', bucket=day gives '08-26'. Over a multi-day hour-bucketed window the labels collide.
- `windowHours` in the response is derived from the resolved range, not from the `hours` you sent. Send from/to spanning 3 days and it comes back as 72.
- perMid[].routedCents intentionally sums ABOVE total volume across MIDs, because a cascaded order is credited to every MID that attempted it. Never sum it as revenue.
- finance.transactionFeeCents bills EVERY non-skipped attempt, including declines, so a MID with a terrible AR carries fees far above its approved count - plus, since v3.9.6, one flat fee per completed wallet charge (the wallet provider's). v3.9.13 - whatever the filters: the window's whole attempt fee, never the sum of a filtered perMid.
- v3.9.6 live fees - RETROACTIVE BY DESIGN: no fee is stored on a row any more; every fee and net of this report is derived at read time from the gateways' CURRENT settings (nmi_accounts / wallet_providers discount bps, transaction fee, reserve bps, per-brand refund fees; account_integrations attemptFeeUsd for 3DS). Edit a MID's discount rate and every past range re-prices at once; a report exported yesterday will not match today's after a fee edit.
- perMid[].usedCents / monthlyCapCents are current billing-period values and ignore your window entirely.
- perStore and perTrafficSource are capped at the top 50 rows; when the cap bites an aggregated '(other)' row is appended so the column still reconciles to totals. perCardBrand and perSource are uncapped.
- v3.9 section 1 (this release): totals.declined / totals.error are the two halves of the declines (MID verdicts / technical errors); perMid[].declined and perWallet[].declined FOLD technical errors in (no error column on those rows); EVERY approvalRate is approved / completed - the one APPROVAL_BASE (live and completed) for totals, perMid, perWallet, perAtri and the breakdowns, so the per-MID rate no longer divides by charges incl. pending; a timed-out attempt is a decline in declineReasons and in the MID-fixable denominator; `blocked` is always 0 and goes away next release - the guards' refusals live in GET /v1/rejections.
- v3.9.9 - every statistic equals its /transactions drill-down: the report counts the key owner's ACCOUNT charges too (transactions.owner_email - an internal charge carries no key), lists that account's MIDs / ATRIs only, and carries the v3.9.9 fields of GET /v1/metrics: `noGateway` (the charges on no gateway, their refunds), `perAtri[].charges` (the ATRI the order ENDED on), `finance.threeDsFeeChargesCents` / `threeDsFeeRejectionsCents`, `declineReasons[].other` (per transaction, the rest in one row); refunds / chargebacks are the refund EVENTS (successful, non-test, of live charges, per transaction).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- perWallet covers the account's own wallet providers: the scope passed to the report carries the account's walletProviderIds, so wallet charges with a null api_key_id are counted.

##### `GET /v1/reports/products`

**Scope** `reports.read` - **Product report (Reporting API: stable shape)**

Reporting API product report: a stable shape of the same computation (products only, no totals, winners or ad spend, at most 500 rows); GET /v1/metrics/products is the dashboard version. Per-product (or per-store) performance over a window for the calling account: straight-sale and rebill counts, approval rates, and a pro-rata finance breakdown. Read-only; forwards straight to productMetrics(). v3.9.9 (D1 / D2) - the rows follow the admin report: refunds / chargebacks are the refund EVENTS of the window (successful, non-test refunds rows dated by the refund, per transaction, a chargeback never inside the refunds), volumeCents the CHARGED amount pro-rata, netCents the dashboard's Net (refunds, refund fees, chargebacks and chargeback fees deducted), groupBy=store the list's store bucket of every charge (no basket needed). The charges no basket names are not a row here (the dashboard shows them as its reconciling row). v3.9.11: `source` (straight / subscription, or the raw values) is read like the admin report's. v3.9.13 - exact cents: by product the money columns are allocated to the rows by largest remainder (each row the floor of its exact pro-rata share, the largest fractions one cent more, ties by key - over every row, before the 500-row cap), so sum of rows + the charges no basket names (the admin report's "(no product basket)" row, not returned here) = the account's figures of the window exactly, each row within 1 cent of its own exact share; netCents = grossCents - its parts, so sum of Net is exact too. A row's money can move by 1 cent against v3.9.12, its netCents by the sum of its parts' moves.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD) | no | Window start, inclusive. v3.9.15 - an ISO instant (any offset, e.g. 2026-08-01T00:00:00Z or 2026-08-01T00:00:00+02:00) or a YYYY-MM-DD day read in `tz` (its first millisecond); anything else is a 400. Max 40 characters. |
| `to` | string (ISO 8601 instant or YYYY-MM-DD); default `now` | no | Window end, inclusive. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). Max 40 characters. Must not be before from (400 "to is before from"). The range from..to may span at most 92 days (400 with details.range). |
| `hours` | integer; default `24` | no | Trailing-window size in hours (1..8760); used only when `from` is absent. |
| `tz` | string (IANA timezone); default `UTC` | no | IANA timezone, max 64 characters: the clock a YYYY-MM-DD from / to and the hour filter are read in (UTC when absent); timestamps come back in UTC. An unknown zone or an empty tz= is a 400 "not a known IANA timezone" (with hour set: "hour needs a valid tz"); it never falls back to UTC silently. |
| `groupBy` | enum: product \| store; default `product` | no | Grouping axis: product (default) or store. Any other value is a 400. With store, several product lines of one order collapse into a single row. |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: store host bucket(s), CSV, matched on the bare lowercased host (the full storefront_url of a row does not match). Add __no_store__ to select canonical standalone orders (orders with no store context, not a blank-URL test). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: flow UUIDs from the immutable checkout session version (not the current store assignment), CSV; none selects orders with no flow. An id that is not one of the account's flows answers 400 {"error":"Invalid request"}. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: affiliate UUIDs from the immutable payment attribution, CSV; none selects orders with no affiliate. Disabled affiliates of the account stay valid for history; an id that is not one of the account's affiliates answers 400 {"error":"Invalid request"} (never an unfiltered result). Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "products": [
    {
      "key": "SKU-COCO-9001",
      "name": "Coco Daily Greens - 30ct",
      "slug": "coco-daily-greens-30",
      "url": "https://shop.example.com/p/coco-daily-greens-30",
      "storefrontUrl": "https://shop.example.com",
      "charges": 612,
      "approved": 344,
      "declined": 261,
      "approvalRate": 0.5686,
      "volumeCents": 1719120,
      "rebillCharges": 288,
      "rebillApproved": 159,
      "rebillDeclined": 124,
      "rebillVolumeCents": 794100,
      "rebillApprovalRate": 0.5619,
      "grossCents": 2513220,
      "discountFeeCents": 72883,
      "transactionFeeCents": 15080,
      "reserveCents": 125661,
      "refundCents": 29940,
      "refundCount": 6,
      "chargebackCents": 9998,
      "chargebackCount": 1,
      "netCents": 2269658,
      "units": 391
    },
    {
      "key": "SKU-COCO-4402",
      "name": "Coco Sleep Blend",
      "slug": "coco-sleep-blend",
      "url": null,
      "storefrontUrl": "https://eu.example.com",
      "charges": 140,
      "approved": 71,
      "declined": 66,
      "approvalRate": 0.5182,
      "volumeCents": 283290,
      "rebillCharges": 0,
      "rebillApproved": 0,
      "rebillDeclined": 0,
      "rebillVolumeCents": 0,
      "rebillApprovalRate": 0,
      "grossCents": 283290,
      "discountFeeCents": 8215,
      "transactionFeeCents": 2100,
      "reserveCents": 14164,
      "refundCents": 0,
      "refundCount": 0,
      "chargebackCents": 0,
      "chargebackCount": 0,
      "netCents": 258811,
      "units": 84
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `products` | object[] | Rows sorted by straight-sale volumeCents descending, then (v3.9.13) by rebillVolumeCents descending, then key. Capped at 500 rows (the route never passes a limit; productMetrics defaults to 500, max 1000). There is no paging and no total count - the long tail is simply cut off. The admin report's v3.9.13 `rebillUnits` is not part of this payload: the rows keep their keys. |
| `products[].key` | string | Grouping identity. groupBy=product: `<store host>\|<product ref>` (the /transactions `productKey` value). groupBy=store (v3.9.9): the host of the charge's storefront (else its originating sale's), '(direct)' without one - the `storefront` value. |
| `products[].name` | string\|null | Display name. With groupBy=store: the host. |
| `products[].slug` | string\|null | Product slug. Always null when groupBy=store. |
| `products[].url` | string\|null | Product URL. With groupBy=store: https://<host> (null for '(direct)'). |
| `products[].storefrontUrl` | string\|null | Storefront URL for the row (max() over the grouped lines, so with groupBy=product a multi-store product shows only one of them). |
| `products[].charges` | number | DISTINCT straight-sale transactions touching this row. Never a sum of quantities. |
| `products[].approved` | number | Distinct straight-sale transactions with status='approved'. |
| `products[].declined` | number | Distinct straight transactions that are declines under v3.9 section 1: status 'declined' or 'error' (TXN_DECLINED_SQL - a technical error is a decline). |
| `products[].approvalRate` | number (ratio 0..1) | approved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out, over the DISTINCT straight transactions of the row). 0 when the base is 0 - never approved / (approved + declined). |
| `products[].volumeCents` | number | Integer CENTS. v3.9.9 - the CHARGED amount of the approved straight sales, pro-rata by the product's share of its order's basket (a basket without prices shares by its lines' count); it was the line total. |
| `products[].rebillCharges / rebillApproved / rebillDeclined` | number | Same counts restricted to rebill transactions, attributed through the original sale's order_id. |
| `products[].rebillApprovalRate` | number (ratio 0..1) | rebillApproved / rebill completed - the same v3.9 section 1 base over the rebill transactions of the row. |
| `products[].rebillVolumeCents` | number | Integer CENTS, PRO-RATA: the order amount weighted by this line's basket share (not the line total, unlike volumeCents). |
| `products[].grossCents` | number | Integer CENTS. Approved order amount pro-rated by line share, across straight AND rebill together. |
| `products[].discountFeeCents / transactionFeeCents / reserveCents / threeDsFeeCents / refundFeesCents / chargebackFeesCents` | number | Integer CENTS, each the order's LIVE fee x the line's basket share (v3.9.6: the gateway's CURRENT discount / reserve bps, the transaction fee per ATTEMPT + the wallet provider's per-charge fee, the 3DS integration's rate; v3.9.9: the refunds' / chargebacks' per-brand fees). The fees of a charge are its window's charges' only. |
| `products[].refundCount / chargebackCount` | number | v3.9.9 (D1) - the TRANSACTIONS refunded / charged back in the window (refunds rows dated by the refund; a chargeback never counts as a refund). Not pro-rated: a charge counts on each of its products' rows. |
| `products[].chargebackCents` | number | Integer CENTS, v3.9.9 - the chargebacks' own amounts (dated by the chargeback) x the share. |
| `products[].units` | number | Physical units shipped on approved straight sales (sum of quantity). DISPLAY ONLY - it never scales any count, rate or volume above. |
| `products[].refundCents` | number | Integer CENTS, v3.9.9 - the refunds' own amounts (dated by the refund, chargebacks excluded) x the share. |
| `products[].netCents` | number | Integer CENTS, v3.9.9 - grossCents - every fee - refunds - refund fees - chargebacks - chargeback fees (the dashboard's Net). v3.9.13 - from the row's allocated figures, so the rows' Net adds up exactly too. |
| `products[].completed / rebillCompleted` | number | v3.9.9 - the AR bases (approvalRate = approved / completed). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten() with fieldErrors / formErrors>} for an unknown query parameter (formErrors names it), an unknown value of a closed list ("unknown value: x"), a malformed date, a reversed range pair, an invalid tz, or a value out of bounds; {"error":"Invalid request","details":{"range":"Use a range of at most 92 days, or a report job."}} when from..to spans more than 92 days; {"error":"Invalid request"} (no details) when an affiliate or flow id is not one of the account's.
- `401` {"error":"Missing API key"} when neither Authorization: Bearer nor X-API-Key is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the key's owner is banned; {"error":"An account owner is required for reports"} when the key has no owner; {"error":"Forbidden"} when the User-Agent looks like a crawler.
- `429` Per-IP rate limit of this route: RATE_LIMIT_STATUS requests per minute (default 60, counted per server instance), not the 300 default.
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected query failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the read exceeds its 25-second budget. Narrow the range or the filters.

**Gotchas**

- Strict query: an unknown parameter is a 400 (details.formErrors names it) and an unknown value of a closed list is a 400 naming it, so a misspelt filter never returns unfiltered data.
- At most 92 days per call (from..to, or the trailing hours window). For a longer range use a report job (POST /v1/metrics/jobs).
- Every key of the unified filter catalog is accepted (the same names as the dashboard filter bar); each is listed in params.
- v3.9.15 - every catalog key applies (it was `source` alone): status, atri, product, storefront, country, device, brand, amountMin/Max, q, email, first6, last4... narrow the counted charges and the refund events' transactions - the same db/productMetrics path as GET /v1/metrics/products.
- Results are silently truncated to the top 500 rows by straight volume (then subscription volume - v3.9.13). No `total`, no paging, no indication that the tail was cut. A long catalogue is incomplete and looks complete.
- Money is PRO-RATA by basket share, so a 3-product order contributes a third of its fees to each row. Do not compare a single product's grossCents to a transaction's amount_cents.
- v3.9.13 - the pro-rata shares are allocated to integer cents by LARGEST REMAINDER across every row (each money column: volumeCents, rebillVolumeCents, grossCents, every fee, refunds, chargebacks and their fees): sum of rows + the charges no basket names = the account's window figure EXACTLY, each row within 1 cent of its own exact share, and netCents (grossCents - its parts) sums exactly too. A row's money column can differ by 1 cent from what v3.9.12 returned (each row was rounded on its own), its netCents by the sum of its parts' changes. groupBy=store is unchanged (whole charges). Sum the returned cents; never re-derive a row from the shares.
- `units` counts physical units and is display-only. Dividing volumeCents by units is not a unit price and dividing any rate by it is wrong.
- v3.9 section 1: `declined` = status 'declined' OR 'error' (a technical error is a decline); approvalRate = approved / completed (approved + declined + unknown), never approved / (approved + declined).
- Baskets are resolved by order_id (so a rebill inherits the original sale's products) but the window is applied to the TRANSACTION. A rebill of a year-old sale shows up in today's window under that old product.
- With groupBy=store, several lines of one order collapse into one row and every counter is count(DISTINCT transaction) - so store `charges` will not equal the sum of the product-level `charges`.
- v3.9.9 - refundCount / chargebackCount are per TRANSACTION and dated by the refunds row: a row can hold refunds with 0 charges (an earlier sale refunded in the window); across rows of a shared basket they double-count - they do not sum.
- v3.9.9 - the charges whose order carries no basket line appear in no product row (groupBy=store counts every charge).
- The straight / subscription split is the shared rebillSql classifier (the /transactions `source` filter's).
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/reports/segments`

**Scope** `reports.read` - **Segment report (Reporting API: stable shape)**

Reporting API segment report: a stable shape of the same computation, without totals; GET /v1/metrics/segments is the dashboard version with totals. Segment analysis over a window for the calling account: 17 dimensions (the processor and the acquiring bank of the charge's gateway joined the original 14 in v3.9 section 0, its company in v3.9.2 section 0; v3.9.12 - mode=rebill adds five, 22 there: subscription, cycle, mid, category, mcc) cut either by subscription approval rate (mode=rebill) or by the period's refunds and chargebacks against the period's approved sales (mode=refunds - v3.9.9: refund / chargeback EVENTS dated by the refund, chargebacks never inside refunds). The figures of the dashboard's Reports > Subscription > Charges and Reports > Refund & CHB. Read-only; forwards straight to segmentMetrics(). v3.9.11: `source` (straight / subscription, or the raw values) restricts both populations like the admin report's.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD) | no | Window start, inclusive. v3.9.15 - an ISO instant (any offset, e.g. 2026-08-01T00:00:00Z or 2026-08-01T00:00:00+02:00) or a YYYY-MM-DD day read in `tz` (its first millisecond); anything else is a 400. Max 40 characters. |
| `to` | string (ISO 8601 instant or YYYY-MM-DD); default `now` | no | Window end, inclusive. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). Max 40 characters. Must not be before from (400 "to is before from"). The range from..to may span at most 92 days (400 with details.range). |
| `hours` | integer; default `24` | no | Trailing-window size in hours (1..8760); used only when `from` is absent. |
| `tz` | string (IANA timezone); default `UTC` | no | IANA timezone, max 64 characters: labels the hour dimension and reads a YYYY-MM-DD range and the hour filter (UTC when absent). An unknown zone or an empty tz= is a 400 "not a known IANA timezone" (with hour set: "hour needs a valid tz"). |
| `mode` | enum: rebill \| refunds; default `rebill` | no | Which report. 'rebill' reads the window's subscription charges (SOURCE_BUCKET = rebill: channel LIKE 'rebill%' / 'legacy', or a rebill-named ATRI for an unknown channel). 'refunds' reads the window's approved sales and the refunds / chargebacks booked in the window (any sale date). Omitting it means rebill. A value outside the enum is a 400. |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: store host bucket(s), CSV, matched on the bare lowercased host (the full storefront_url of a row does not match). Add __no_store__ to select canonical standalone orders (orders with no store context, not a blank-URL test). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: flow UUIDs from the immutable checkout session version (not the current store assignment), CSV; none selects orders with no flow. An id that is not one of the account's flows answers 400 {"error":"Invalid request"}. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: affiliate UUIDs from the immutable payment attribution, CSV; none selects orders with no affiliate. Disabled affiliates of the account stay valid for history; an id that is not one of the account's affiliates answers 400 {"error":"Invalid request"} (never an unfiltered result). Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "mode": "refunds",
  "segments": [
    {
      "dim": "card_brand",
      "key": "Visa",
      "charges": 470,
      "approved": 470,
      "declined": 0,
      "blocked": 0,
      "approvalRate": 1,
      "volumeCents": 2402800,
      "refunds": 18,
      "refundRate": 0.0383,
      "chargebacks": 3,
      "chargebackRate": 0.0064
    },
    {
      "dim": "device",
      "key": "Mobile",
      "charges": 512,
      "approved": 512,
      "declined": 0,
      "approvalRate": 1,
      "volumeCents": 2611400,
      "refunds": 27,
      "refundRate": 0.0527,
      "chargebacks": 5,
      "chargebackRate": 0.0098
    },
    {
      "dim": "geo",
      "key": "US",
      "charges": 690,
      "approved": 690,
      "declined": 0,
      "approvalRate": 1,
      "volumeCents": 3502100,
      "refunds": 31,
      "refundRate": 0.0449,
      "chargebacks": 6,
      "chargebackRate": 0.0087
    },
    {
      "dim": "hour",
      "key": "14:00",
      "charges": 61,
      "approved": 61,
      "declined": 0,
      "approvalRate": 1,
      "volumeCents": 310400,
      "refunds": 4,
      "refundRate": 0.0656,
      "chargebacks": 0,
      "chargebackRate": 0
    },
    {
      "dim": "price_point",
      "key": "2. $25-49",
      "charges": 388,
      "approved": 388,
      "declined": 0,
      "approvalRate": 1,
      "volumeCents": 1552000,
      "refunds": 12,
      "refundRate": 0.0309,
      "chargebacks": 1,
      "chargebackRate": 0.0026
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `mode` | enum: rebill\|refunds | Echo of the resolved mode. Anything other than an explicit 'refunds' resolves to 'rebill'. |
| `segments` | object[] | Flat list of rows across ALL dimensions at once, sorted by dim then volumeCents desc. Group client-side on `dim`. No limit and no paging - a high-cardinality issuer or store list can be thousands of rows. |
| `segments[].dim` | enum: price_point\|initial_value\|card_brand\|store\|geo\|hour\|source\|device\|os\|traffic\|card_type\|issuer\|card_level\|product\|processor\|acquiring_bank\|company\|subscription\|cycle\|mid\|category\|mcc | Which dimension this row belongs to. Seventeen values: processor and acquiring_bank (the reference names behind the charge's gateway, '(unset)' when it carries none) were added to the original fourteen in v3.9 section 0, company (the legal entity the gateway is boarded under, same rule) in v3.9.2 section 0. Always these exact snake_case strings. v3.9.12 - mode=rebill adds five (22 there): subscription (the charge's sub's subscription product), cycle (the entry's rebill_number), mid (the gateway: a MID, or a wallet provider x wallet), category (the MID's PRIMARY category), mcc (the MID's MCC). mode=refunds is unchanged (17). |
| `segments[].key` | string | The dimension value - v3.9.9: for every dimension the dashboard links, the key IS the value of the /transactions filter that reproduces the cell, on that filter's own expression. price_point / initial_value carry a sort prefix ('1. < $25' ... '7. $200+'); hour is 'HH:00' in `tz`; geo an upper-cased country; source 'Straight' (the list's SOURCE_BUCKET sale + recovery) or 'Rebill' (source=rebill); card_brand the list's brand value (METHOD_CASE: 'Visa', 'Mastercard', 'Amex', 'Discover', 'Apple Pay', 'Google Pay' - the wallet first; '(unknown)' is exactly brand=Other, no network); store the storefront HOST (storeExpr), '(direct)' when the order has none; device / os the shared CASEs; traffic falls back to 'direct / organic' (the list's '(direct/organic)'); product the basket line's name, else slug, else ref - the list's `product` value, '(unknown)' included. card_type / issuer / card_level of a wallet charge are its wallet ('Apple Pay' / 'Google Pay'). Every other unresolved value is the literal '(unknown)' (no filter expresses it). v3.9.12 - subscription: the product's name, '(none)' = a charge no sub produced (a legacy / batch-API rebill); cycle: 'Cycle N', '(none)' likewise; mid: the MID's name, or '<provider> - <wallet>' for a wallet charge (the Payment report's wallet row), '(no gateway)' when the charge ended on none; category: the MID's PRIMARY category name (its first by name, the id breaking a tie - the list's primaryCategory), '(none)' = a MID without one or a wallet charge; mcc: the MID's MCC, '(none)' likewise; processor / acquiring_bank / company (both modes): the reference name, '(unset)' = a gateway WITHOUT that reference, '(no gateway)' = a charge that ended on no MID and no wallet provider - the two read '(unset)' together before v3.9.12. |
| `segments[].ref` | string (optional) | v3.9.12 - the /transactions value behind an id-keyed row, absent on the others: subscription -> the product id (the list's `subscription`); cycle -> N (`cycle`); mid -> the MID id (`accountId`), `wallet:<provider id>:<wallet>` (accountId=wallet:<provider id> + brand=<wallet>) or `none` on '(no gateway)' (accountId=none); category -> the category id (`primaryCategory`), `nogw` on '(no gateway)', absent on '(none)'; mcc -> `nogw` on '(no gateway)' only (the key itself is the list's `gatewayMcc` value); processor / acquiring_bank / company (both modes) -> the reference id (`processor` / `acquiringBank` / `company`), `none` on '(unset)' (that filter's own `none`: a gateway without the reference), `nogw` on '(no gateway)' (accountId=none). A row is (dim, key, ref): two products or MIDs of one name are two rows. |
| `segments[].charges` | number | v3.9.9 - the cell's CHARGES: live rows (no test card, no CSV import, no 3DS park) CREATED in the window, counted per transaction. mode=refunds: the approved sales (so it equals `approved`); mode=rebill: every subscription charge. A segment reached only through a refund / chargeback EVENT of an earlier charge reads 0 here (its refunds / chargebacks are not 0). |
| `segments[].approved` | number | Charges of the cell with status 'approved' (mode=refunds: the Sales - equals `charges`). |
| `segments[].declined` | number | Rows with status 'declined' or 'error' - the v3.9 section 1 declines (a technical error is one). Always 0 in mode=refunds. |
| `segments[].completed` | integer | v3.9 section 1 - the approval rate's base of the cell: the charges with status approved, declined, error or unknown (pending and duplicate are out). approvalRate = approved / completed, so a Total row recomputes sum of approved / sum of completed on it. In mode=refunds it equals approved. |
| `segments[].blocked` | number (always 0) | ALWAYS 0 since v3.9 section 1: a refusal cocoapi makes before any MID (card cooldown, velocity guard and the other interceptor filters, card validity pre-check, blacklist, BIN scrub, 3DS policy) is a REJECTION (GET /v1/rejections), not a charge, so it is in no charge figure. Deprecated - kept one release for the shape, removed next; never subtract it from anything. |
| `segments[].approvalRate` | number (ratio 0..1) | approved / completed (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out) - NOT approved / charges and no longer approved / (approved + declined). 0 when the base is 0; always 1 in mode=refunds when approved > 0. |
| `segments[].volumeCents` | number | Integer CENTS of the cell's approved charges (a JSON number). On dim='product': mode=refunds = that product's own basket lines of the sales (the lines aggregated per order and product - they partition the sales' revenue); mode=rebill = the subscription charges' amounts. |
| `segments[].refunds` | number | v3.9.9 - the refunds BOOKED in the window: transactions of the cell with a successful, non-test refunds row NOT marked chargeback whose created_at (the refund's date) is in the window - whatever the charge's own date - attributed to the refunded transaction's segment, counted per transaction. Never a chargeback (the old count read the transactions.refunded flag, which a chargeback sets too, on the window's sales). Drill-down: GET /v1/reports/transactions / the dashboard list ?refund=refund&population=live + the segment's filter (the list dates `refund` by the refunds row). |
| `segments[].refundRate` | number | RATIO: refunds / approved - events of the period / sales of the period (the card networks' ratio, not a cohort propensity: a segment can exceed 1, or hold events with no sale of the period). 0 when approved is 0 (the dashboard shows  - ). |
| `segments[].chargebacks` | number | v3.9.9 - the chargebacks BOOKED in the window: the same refunds rows marked is_chargeback, dated by that row, per transaction. Drill-down: GET /v1/reports/transactions / the dashboard list ?refund=chargeback&population=live + the segment's filter. |
| `segments[].chargebackRate` | number | RATIO: chargebacks / approved - events of the period / sales of the period (the card networks' ratio, not a cohort propensity: a segment can exceed 1, or hold events with no sale of the period). 0 when approved is 0 (the dashboard shows  - ). |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten() with fieldErrors / formErrors>} for an unknown query parameter (formErrors names it), an unknown value of a closed list ("unknown value: x"), a malformed date, a reversed range pair, an invalid tz, or a value out of bounds; {"error":"Invalid request","details":{"range":"Use a range of at most 92 days, or a report job."}} when from..to spans more than 92 days; {"error":"Invalid request"} (no details) when an affiliate or flow id is not one of the account's.
- `401` {"error":"Missing API key"} when neither Authorization: Bearer nor X-API-Key is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the key's owner is banned; {"error":"An account owner is required for reports"} when the key has no owner; {"error":"Forbidden"} when the User-Agent looks like a crawler.
- `429` Per-IP rate limit of this route: RATE_LIMIT_STATUS requests per minute (default 60, counted per server instance), not the 300 default.
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected query failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the read exceeds its 25-second budget. Narrow the range or the filters.

**Gotchas**

- Strict query: an unknown parameter is a 400 (details.formErrors names it) and an unknown value of a closed list is a 400 naming it, so a misspelt filter never returns unfiltered data.
- At most 92 days per call (from..to, or the trailing hours window). For a longer range use a report job (POST /v1/metrics/jobs).
- Every key of the unified filter catalog is accepted (the same names as the dashboard filter bar); each is listed in params.
- v3.9.15 - every catalog key applies (it was `source` alone): status / atri / product / ... narrow both populations - the same db/segmentMetrics path as GET /v1/metrics/segments.
- The two modes analyse DIFFERENT populations and are not comparable. mode=rebill keeps only subscription charges (so `source` is always the single bucket 'Rebill'). mode=refunds keeps the APPROVED sales of the window plus the transactions refunded / charged back in it: declined=0 and approvalRate=1 on every row with a sale, and a row can hold refunds with 0 sales (a refund of an earlier sale).
- One flat array holds all 17 dimensions (22 in mode=rebill since v3.9.12). If you render it without grouping on `dim`, 'Visa' (card_brand) and 'US' (geo) sit side by side as if they were the same axis.
- Rebill context is INHERITED from the originating sale, matched on order_id ALONE across api keys, because a rebill and its sale routinely carry different keys. Orphan rebills whose sale is not in the DB (legacy imports) stay '(unknown)' - measured at roughly 21% of approved rebills. dim='product' carries one row per (transaction, product): a multi-product basket sits on several rows.
- v3.9.9 - `refunds` and `chargebacks` are the EVENTS booked in the window: transactions with a successful, non-test refunds row (not / marked chargeback) dated in the window, whatever the sale's date, counted once per transaction. Refunds never include chargebacks. They are no longer the transactions.refunded / charged_back flags of the window's sales.
- refundRate and chargebackRate divide the period's events by the period's APPROVED charges (0 without one) - a period ratio that can exceed 1, not a cohort propensity.
- Bucket labels are literal strings with formatting baked in: price buckets carry a sort prefix like '2. $25-49', traffic uses 'direct / organic' with surrounding spaces, and unknowns are '(unknown)' with parentheses. String-match exactly.
- The `hour` dimension buckets by tz but there is no date component: over a multi-day window all 09:00s across every day collapse into one row.
- card_brand is the network on the transaction (the stored brand, else the PAN's BIN ranges - the list's brand values, METHOD_CASE); card_type / issuer / card_level come from bin_info on the mask's first 6 digits. A wallet charge (no PAN) reads its wallet - 'Apple Pay' / 'Google Pay' - in all four (v3.9.8).
- No row cap. A window with a wide issuer or store distribution can return thousands of rows in a single uncompressed array.
- `declined` folds status='error' into declines, which does not match the `status` semantics on /v1/reports/transactions.
- dim='processor' / dim='acquiring_bank' (v3.9 section 0) / dim='company' (v3.9.2 section 0): `key` is the reference NAME of the charge's own gateway - the final MID's processor / acquiring bank / company, else the wallet provider's (the GATEWAY_REF_JOIN of txFilters) - as stored (UPPERCASE, 'PRIORITY', 'SYNOVUS'). v3.9.12 - '(unset)' = a gateway WITHOUT that reference (ref `none`), '(no gateway)' = a charge that ended on no MID and no wallet provider (ref `nogw`); both read '(unset)' before. Unlike device / os / geo, a rebill is NOT matched to its originating sale on these three dims: it ran on its own MID and reports that MID's reference. To list the rows of a cell use GET /v1/reports/transactions?processor=<ref> / ?acquiringBank=<ref> / ?company=<ref> (`none` included); `nogw` -> ?accountId=none.
- v3.9.12 - `ref` values are the dashboard list's (GET /v1/transactions) filter values. GET /v1/reports/transactions takes accountId (a MID id, wallet:<provider id>, none) and processor / acquiringBank / company (an id, none); subscription, cycle, primaryCategory and gatewayMcc are admin-list filters only.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/reports/transactions`

**Scope** `transactions.read` - **Transactions report (Reporting API: stable shape, exact total)**

The Reporting API transactions report (a stable response shape with an exact total); GET /v1/transactions is the dashboard list and POST /v1/transactions the partner window sync. Paginated, filterable list of the calling account's transactions over a time window - newest first by default, or ordered by `sort` / `dir` over the whole result set. Read-only; nothing is created or changed. Accepts the exact same query-param names as the dashboard's /transactions screen (filters AND sort keys), so a URL copied from the UI works unchanged.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 instant or YYYY-MM-DD) | no | Window start, inclusive. v3.9.15 - an ISO instant (any offset, e.g. 2026-08-01T00:00:00Z or 2026-08-01T00:00:00+02:00) or a YYYY-MM-DD day read in `tz` (its first millisecond); anything else is a 400. v3.9.9 - with `refund` (and no refundBasis=charge) it reads the REFUNDS row's created_at (the refund date) instead of t.created_at. Max 40 characters. |
| `to` | string (ISO 8601 instant or YYYY-MM-DD); default `now` | no | Window end, inclusive, matched on transactions.created_at. Defaults to the server's current time when omitted. v3.9.9 - with `refund` (and no refundBasis=charge) it reads the REFUNDS row's created_at (the refund date) instead of t.created_at. v3.9.15 - an ISO instant, or a YYYY-MM-DD day read in `tz` (its first / last millisecond). Max 40 characters. Must not be before from (400 "to is before from"). The range from..to may span at most 92 days (400 with details.range). |
| `hours` | integer; default `24` | no | Trailing-window size in hours (1..8760), used ONLY as the fallback for `from`: start = end - hours. Completely ignored once `from` is supplied. Coerced from string. |
| `tz` | string (IANA timezone); default `UTC` | no | IANA timezone, max 64 characters: the clock a YYYY-MM-DD from / to and the hour filter are read in (UTC when absent); timestamps come back in UTC. An unknown zone or an empty tz= is a 400 "not a known IANA timezone" (with hour set: "hour needs a valid tz"); it never falls back to UTC silently. |
| `sort` | enum: created_at\|completed_at\|amount\|status\|order_id\|email\|customer\|mid\|atri\|crm\|country\|storefront\|traffic\|decline_reason\|card\|three_ds\|method\|source\|product\|processor\|acquiring_bank\|company\|utm_source\|utm_campaign; default `created_at` | no | Sort key - the dashboard's /transactions whitelist (db/txFilters TX_SORT): created_at (default), completed_at, amount (amount_cents), status, order_id, email / customer (both t.email), mid (final_account_name), atri (the trip name), crm, country (raw_payload country), storefront (storefront_url), traffic (traffic_source), decline_reason, card (masked_card), three_ds (three_ds_status), method (raw_payload paySource - APPLEPAY / GOOGLEPAY - else crm), source (straight sale before subscription charge when asc), product (the ORIGINAL sale's first basket slug - the same subquery as the Product column), processor / acquiring_bank / company (v3.9 section 0, company v3.9.2 section 0 - the reference NAMES the row carries as processor_name / acquiring_bank_name / company_name; a charge whose gateway has none sorts last). Every key other than created_at tie-breaks on created_at desc, nulls last. `subscription` (a dashboard-list key) is NOT accepted here - it needs that list's per-row subscription join - and answers 400 like any unknown key. Any other value - including a direction passed as the key (`sort=asc`) - is a 400 whose details.fieldErrors.sort names the allowed values; it is never silently ignored. v3.9.2 section 4: + utm_source, utm_campaign - both read the attribution side table (transaction_attribution, ATTRIBUTION_JOIN); a subscription charge sorts under its sale's copy. |
| `dir` | enum: asc \| desc; default `desc` | no | Sort direction, asc or desc. Anything else is a 400. Without sort, the order is created_at descending. |
| `limit` | integer; default `100` | no | Page size, 1 to 500, coerced from the query string. Out of range is a 400 (never clamped). |
| `offset` | integer; default `0` | no | Rows to skip, an integer >= 0. Offset paging only (no cursor). |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: store host bucket(s), CSV, matched on the bare lowercased host (the full storefront_url of a row does not match). Add __no_store__ to select canonical standalone orders (orders with no store context, not a blank-URL test). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: flow UUIDs from the immutable checkout session version (not the current store assignment), CSV; none selects orders with no flow. An id that is not one of the account's flows answers 400 {"error":"Invalid request"}. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: affiliate UUIDs from the immutable payment attribution, CSV; none selects orders with no affiliate. Disabled affiliates of the account stay valid for history; an id that is not one of the account's affiliates answers 400 {"error":"Invalid request"} (never an unfiltered result). Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "total": 1482,
  "limit": 100,
  "offset": 0,
  "count": 2,
  "transactions": [
    {
      "id": "9f3a1c22-7d41-4a0e-b6a1-2c9e0f5b1a77",
      "order_id": "ORD-100244",
      "crm": "nmi",
      "amount_cents": "4999",
      "currency": "USD",
      "status": "approved",
      "is_success": true,
      "source": "sale",
      "fl": false,
      "masked_card": "424242..4242",
      "email": "jane.doe@example.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "final_account_name": "Atlas MID 03",
      "method": "Visa",
      "processor_name": "PRIORITY",
      "acquiring_bank_name": "SYNOVUS",
      "company_name": "STELLAR TIDE LLC",
      "decline_reason": null,
      "order_id_supplier": "10293847561",
      "atri": "Checkout US",
      "refunded": false,
      "refunded_cents": "0",
      "charged_back": false,
      "traffic_source": "fb-ads",
      "storefront_url": "https://shop.example.com/checkout?utm_source=fb",
      "utm_source": "fb",
      "utm_campaign": "eu_retarget_7d",
      "created_at": "2026-08-26T09:12:44.118Z",
      "completed_at": "2026-08-26T09:12:45.902Z"
    },
    {
      "id": "1b70d9e4-58a2-42f0-9c3d-88ab41f6e210",
      "order_id": "ORD-100245",
      "crm": "nmi",
      "amount_cents": "12900",
      "currency": "USD",
      "status": "declined",
      "is_success": false,
      "source": "rebill",
      "fl": false,
      "masked_card": "545454..1881",
      "email": "buyer2@example.com",
      "first_name": "Mark",
      "last_name": "Ellis",
      "final_account_name": "Vertex MID 01",
      "method": "Visa",
      "processor_name": "SIGNAPAY",
      "acquiring_bank_name": "CHESAPEAK",
      "company_name": "STELLAR TIDE LLC",
      "decline_reason": "Insufficient funds",
      "order_id_supplier": null,
      "atri": "Rebill EU",
      "refunded": false,
      "refunded_cents": "0",
      "charged_back": false,
      "traffic_source": null,
      "storefront_url": "https://eu.example.com/",
      "utm_source": null,
      "utm_campaign": null,
      "created_at": "2026-08-26T08:57:02.004Z",
      "completed_at": "2026-08-26T08:57:03.771Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `total` | number | Total rows matching the filters BEFORE limit/offset. A real JS number (the bigint count is cast with Number()). |
| `limit` | number | Echo of the effective limit. |
| `offset` | number | Echo of the effective offset. |
| `count` | number | Number of rows actually in `transactions` for this page (<= limit). |
| `transactions` | object[] | The page of transactions, in the requested order. |
| `transactions[].id` | uuid | Transaction id. |
| `transactions[].order_id` | string | Merchant order id as supplied at checkout. NOT globally unique across accounts; a rebill reuses the original sale's order_id. |
| `transactions[].crm` | string | Processing family: 'nmi' for card charges, 'convesio' for wallet/Apple-Pay passthrough. |
| `transactions[].amount_cents` | string | Order amount in INTEGER CENTS, but serialized as a JSON STRING because the column is Postgres bigint and no int8 type parser is installed. Parse it before doing arithmetic. |
| `transactions[].currency` | string | ISO currency code, defaults to USD. |
| `transactions[].status` | enum: pending\|approved\|declined\|error\|unknown\|duplicate | Final status. 'unknown' means an ambiguous gateway timeout that needs manual review. |
| `transactions[].is_success` | boolean | True only for an approved capture. Use this, not status, for money math. |
| `transactions[].source` | enum: sale \| rebill \| recovery \| pre-auth \| friendlies | Order source bucket of the charge: friendlies (a Friendlies charge), pre-auth, rebill (a subscription charge), recovery (a recovered cart), else sale. The same classifier as the source filter. |
| `transactions[].fl` | boolean \| null | True when the charge payload carries the Friendlies flag (raw_payload.fl = true); false or null otherwise. |
| `transactions[].masked_card` | string | 'first6..last4' format. Never the full PAN. Null on wallet charges. |
| `transactions[].method` | string \| null | v3.9.8 item 1 - the payment method (METHOD_CASE, the `brand` filter's own expression): 'Apple Pay' \| 'Google Pay' on a wallet charge (whose masked_card is null), else the card network Visa \| Mastercard \| Amex \| Discover; null for a card with no recognised network. |
| `transactions[].email` | string\|null | Customer email. |
| `transactions[].first_name` | string\|null | Customer first name. |
| `transactions[].last_name` | string\|null | Customer last name. |
| `transactions[].final_account_name` | string\|null | Name of the MID the order ENDED on. Null for wallet traffic and for orders that never reached a gateway. |
| `transactions[].processor_name` | string\|null | v3.9 section 0 - name of the processor behind the charge (the final MID's, else the wallet provider's), as stored ('PRIORITY'). Null when the gateway carries none or the order ended on no gateway. |
| `transactions[].acquiring_bank_name` | string\|null | v3.9 section 0 - name of the acquiring bank behind the charge, resolved the same way ('SYNOVUS'). Null when unset. |
| `transactions[].company_name` | string\|null | v3.9.2 section 0 - name of the company (the legal entity the gateway is boarded under) behind the charge, resolved the same way ('STELLAR TIDE LLC'). Null when unset. |
| `transactions[].decline_reason` | string\|null | Normalised decline reason on the final attempt. |
| `transactions[].order_id_supplier` | string\|null | The gateway's own transaction id (NMI transactionid) of the winning attempt. Null when nothing was approved. |
| `transactions[].atri` | string\|null | trips.name joined on transactions.trip_id - the CLASSIC ATRI only. Null when the order carries no trip. |
| `transactions[].refunded` | boolean | True once any successful refund exists on the order. |
| `transactions[].refunded_cents` | string | Refunded amount in INTEGER CENTS, serialized as a JSON STRING (bigint column). |
| `transactions[].charged_back` | boolean | True when a refund on this order was reclassified as a chargeback. |
| `transactions[].traffic_source` | string\|null | Raw traffic source tag; null/empty means direct/organic. |
| `transactions[].storefront_url` | string\|null | Full checkout URL including path and query - not the bare host the `storefront` filter expects. |
| `transactions[].created_at` | string (ISO 8601 UTC) | When the charge was received. This is the column every date filter applies to. |
| `transactions[].completed_at` | string\|null (ISO 8601 UTC) | When the charge reached its final status. Null while pending. |
| `transactions[].utm_source / utm_campaign` | string \| null | v3.9.2 section 4 - the campaign attribution row's utm_source / utm_campaign (transaction_attribution; raw utm values, distinct from traffic_source). null without a row; a subscription charge carries its sale's copy. |

**Errors**

- `400` {"error":"Invalid request","details":<zod flatten() with fieldErrors / formErrors>} for an unknown query parameter (formErrors names it), an unknown value of a closed list ("unknown value: x"), a malformed date, a reversed range pair, an invalid tz, or a value out of bounds; {"error":"Invalid request","details":{"range":"Use a range of at most 92 days, or a report job."}} when from..to spans more than 92 days; {"error":"Invalid request"} (no details) when an affiliate or flow id is not one of the account's.
- `401` {"error":"Missing API key"} when neither Authorization: Bearer nor X-API-Key is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the key's account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the key's owner is banned; {"error":"An account owner is required for reports"} when the key has no owner; {"error":"Forbidden"} when the User-Agent looks like a crawler.
- `429` Per-IP rate limit of this route: RATE_LIMIT_STATUS requests per minute (default 60, counted per server instance), not the 300 default.
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected query failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the read exceeds its 25-second budget. Narrow the range or the filters.

**Gotchas**

- Strict query: an unknown parameter is a 400 (details.formErrors names it) and an unknown value of a closed list is a 400 naming it, so a misspelt filter never returns unfiltered data.
- At most 92 days per call (from..to, or the trailing hours window). For a longer range use a report job (POST /v1/metrics/jobs).
- Every key of the unified filter catalog is accepted (the same names as the dashboard filter bar); each is listed in params.
- The account scope is the key owner's whole tenancy, so a report includes traffic charged with a sibling key, the account's wallet charges and its internal charges. A key without an owner is refused (403), never scoped to itself.
- `amount_cents` and `refunded_cents` come back as JSON STRINGS, not numbers - they are Postgres bigint and node-pg has no int8 parser configured here. `total`, `limit`, `offset` and `count` ARE numbers. Mixing them in arithmetic silently concatenates.
- `pass` ORs its values: `pass=initial,cascade` is both (no narrowing); an unknown value is a 400 (v3.9.15). (`source` ORs its values since v3.9 section 2 - `source=sale,rebill` is both; note 'sale' excludes the recovery rows.)
- All date filtering is on `created_at` (when the charge arrived), never on `completed_at`. An order that started at 23:59 and settled at 00:01 belongs to the earlier day.
- Filtering by a CASCADE ATRI returns orders whose returned `atri` field shows a DIFFERENT (classic) name - the filter is cascade-aware but the displayed column is transactions.trip_id.
- `storefront` matches a bare lowercased HOST while the response returns the full `storefront_url`. Feeding a returned storefront_url straight back as a filter matches nothing.
- `country`, `paysource`, `brand`, `device`, `os` are case-sensitive exact matches on literal labels; '(unknown)' and '(direct/organic)' include their parentheses/slash.
- Ordering is `sort`/`dir` (default `created_at desc`; every other key tie-breaks on created_at desc, nulls last) with offset pagination over a live table. On an active account, new rows inserted between pages shift the window and you will re-see or skip rows.
- v3.9.2 section 4 - utmSource / utmCampaign filter on the attribution side table (case-insensitive) and the two utm columns come from it (one PK lookup per row): a card sale carries them only once the checkout sends `attribution` on POST /v1/charge; wallet sales carry theirs since migration 158 (the wallet-history backfill; the table itself is migration 150).
- v3.9.9 - the account's tenancy is the dashboard's whole rule: its keys, wallet providers, gateways, imports AND its own charges (transactions.owner_email - a subscription charge declined before any MID carries no key and no gateway). Before, those rows were missing here (578 of the September live rows).
- Requires transactions.read, consistently with every other transaction-list endpoint. reports.read alone does not grant detailed transaction access.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/status/daily`

**Scope** `reports.read` - **Get daily status snapshot**

Read-only, pull-based health snapshot of the account for an external status tracker: the last 24 h of live transactions, POST /v1/charge request logs, attempt latency and per-MID activity, each graded server-side against fixed thresholds (lib/statusThresholds.ts). Returns metrics[], providers[], alerts[] and declineReasons[].

*No parameters.*

**Response**

```json
{
  "generatedAt": "2026-11-24T14:07:33.512Z",
  "window": "24h",
  "overallSeverity": "critical",
  "metrics": [
    {
      "key": "approval_rate",
      "label": "Overall approval rate (AR)",
      "tier": 1,
      "value": 0.7194,
      "unit": "ratio",
      "dMinus1": 0.7256,
      "avg7d": 0.7331,
      "deltaVs7d": -0.0137,
      "severity": "ok",
      "threshold": "warn: <0.55 or drop>8pts · crit: <0.5 or drop>15pts",
      "hint": "Top-line health. A sharp drop with steady volume points at a dying MID - check the providers list."
    },
    {
      "key": "order_volume",
      "label": "Order quantity (24h)",
      "tier": 1,
      "value": 1842,
      "unit": "count",
      "dMinus1": 1907,
      "avg7d": 1874.3,
      "deltaVs7d": -32.3,
      "severity": "ok",
      "threshold": "warn: drop>30% · crit: drop>50% vs 7d avg",
      "hint": "A volume cliff usually means upstream traffic died or the integration broke - not a payments problem."
    },
    {
      "key": "unknown_rate",
      "label": "Ambiguous timeout rate",
      "tier": 1,
      "value": 0.0065,
      "unit": "ratio",
      "dMinus1": 0.0052,
      "avg7d": 0.0059,
      "deltaVs7d": 0.0006,
      "severity": "ok",
      "threshold": "warn: >1% · crit: >3%",
      "hint": "These never auto-failover (double-charge guard). Elevated = manual reconciliation needed."
    },
    {
      "key": "heartbeat",
      "label": "Minutes since last order",
      "tier": 1,
      "value": 3,
      "unit": "minutes",
      "dMinus1": null,
      "avg7d": null,
      "deltaVs7d": null,
      "severity": "ok",
      "threshold": "warn: >60m · crit: >180m or never",
      "hint": "During business hours a long gap means the system or all traffic is down. Adjust for known off-hours."
    },
    {
      "key": "error_rate",
      "label": "Gateway error rate",
      "tier": 2,
      "value": 0.0168,
      "unit": "ratio",
      "dMinus1": 0.0142,
      "avg7d": 0.0151,
      "deltaVs7d": 0.0017,
      "severity": "ok",
      "threshold": "warn: >2% · crit: >5%",
      "hint": "Network/gateway failures (not declines). Sustained errors → check NMI/Convesio status."
    },
    {
      "key": "duplicate_rate",
      "label": "Duplicate rate",
      "tier": 2,
      "value": 0.0119,
      "unit": "ratio",
      "dMinus1": 0.0105,
      "avg7d": 0.0113,
      "deltaVs7d": 0.0006,
      "severity": "ok",
      "threshold": "warn: >2% · crit: >5%",
      "hint": "A client retry storm or reused orderId. Idempotency is catching it, but the caller is misbehaving."
    },
    {
      "key": "auth_failed_rate",
      "label": "Auth-failed request rate",
      "tier": 2,
      "value": 0.0141,
      "unit": "ratio",
      "dMinus1": 0.0102,
      "avg7d": 0.0098,
      "deltaVs7d": 0.0043,
      "severity": "warn",
      "threshold": "warn: >1% · crit: >5% of requests",
      "hint": "Bad/leaked/rotated API key, or a caller pointed at the wrong env."
    },
    {
      "key": "invalid_body_rate",
      "label": "Invalid-body request rate",
      "tier": 2,
      "value": 0.005,
      "unit": "ratio",
      "dMinus1": 0.0044,
      "avg7d": 0.0047,
      "deltaVs7d": 0.0003,
      "severity": "ok",
      "threshold": "warn: >1% · crit: >5% of requests",
      "hint": "A caller shipped a broken integration / malformed payload."
    },
    {
      "key": "p95_latency_ms",
      "label": "p95 attempt latency",
      "tier": 2,
      "value": 3120,
      "unit": "ms",
      "dMinus1": null,
      "avg7d": 1180,
      "deltaVs7d": 1940,
      "severity": "warn",
      "threshold": "warn: >2× · crit: >3× the 7d p95",
      "hint": "Gateway degradation. Rising latency often precedes timeouts/unknowns."
    },
    {
      "key": "request_conversion",
      "label": "Order conversion (orders / requests)",
      "tier": 2,
      "value": 0.7643,
      "unit": "ratio",
      "dMinus1": 0.769,
      "avg7d": 0.761,
      "deltaVs7d": 0.0033,
      "severity": "ok",
      "threshold": "warn: drop>25% · crit: drop>40% vs 7d",
      "hint": "Inbound requests are the proxy for \"visits\" (not page views). A drop hints at a checkout/validation break."
    },
    {
      "key": "order_amount_cents",
      "label": "Approved volume (cents, 24h)",
      "tier": 3,
      "value": 11659000,
      "unit": "cents",
      "dMinus1": 12326500,
      "avg7d": 11914285.7,
      "deltaVs7d": -255285.7,
      "severity": "ok",
      "threshold": "informational - trend only",
      "hint": "Context for the graded metrics; not alerted on its own."
    },
    {
      "key": "traffic_requests",
      "label": "Inbound requests / traffic (24h)",
      "tier": 3,
      "value": 2410,
      "unit": "count",
      "dMinus1": 2480,
      "avg7d": 2462.9,
      "deltaVs7d": -52.9,
      "severity": "ok",
      "threshold": "informational - trend only",
      "hint": "Context for the graded metrics; not alerted on its own."
    },
    {
      "key": "external_api_forward_failures",
      "label": "External API forward failures",
      "tier": 1,
      "value": null,
      "unit": "count",
      "dMinus1": null,
      "avg7d": null,
      "deltaVs7d": null,
      "severity": "not_instrumented",
      "threshold": "pending instrumentation (Phase 2)",
      "hint": "No forwarding/postback layer logs this yet. Add a forward_attempts table where orders are pushed to the CRM/fulfillment."
    },
    {
      "key": "pixel_failures",
      "label": "Pixel / CAPI failures",
      "tier": 1,
      "value": null,
      "unit": "count",
      "dMinus1": null,
      "avg7d": null,
      "deltaVs7d": null,
      "severity": "not_instrumented",
      "threshold": "pending instrumentation (Phase 2)",
      "hint": "Not tracked. Add a pixel_events log (fired from the checkout frontend or a CAPI worker) to surface this."
    },
    {
      "key": "provider_ar_collapse",
      "label": "Per-provider AR collapse",
      "tier": 1,
      "value": 1,
      "unit": "count",
      "dMinus1": null,
      "avg7d": null,
      "deltaVs7d": null,
      "severity": "critical",
      "threshold": "warn: a MID (≥20 charges) AR<40% · crit: AR<20%",
      "hint": "One MID collapsing while others are healthy → pause it in its ATRI so the cascade skips it."
    },
    {
      "key": "mid_cap_usage",
      "label": "MID monthly cap usage",
      "tier": 1,
      "value": 1,
      "unit": "count",
      "dMinus1": null,
      "avg7d": null,
      "deltaVs7d": null,
      "severity": "warn",
      "threshold": "warn: any MID ≥85% · crit: ≥95%",
      "hint": "A capped MID drops out of routing and shifts load (and risk) onto the rest. Provision ahead of the cap."
    }
  ],
  "providers": [
    {
      "mid": "11111111-1111-4111-8111-111111111111",
      "name": "Example MID 01",
      "charges": 902,
      "approvalRate": 0.7594,
      "capPct": 0.6212,
      "severity": "ok",
      "issues": []
    },
    {
      "mid": "22222222-2222-4222-8222-222222222222",
      "name": "Example MID 02",
      "charges": 115,
      "approvalRate": 0.7652,
      "capPct": 0,
      "severity": "ok",
      "issues": []
    },
    {
      "mid": "33333333-3333-4333-8333-333333333333",
      "name": "Example MID 03",
      "charges": 611,
      "approvalRate": 0.7561,
      "capPct": 0.8731,
      "severity": "warn",
      "issues": [
        "cap 87% used"
      ]
    },
    {
      "mid": "44444444-4444-4444-8444-444444444444",
      "name": "Example MID 04",
      "charges": 214,
      "approvalRate": 0.1449,
      "capPct": 0.1904,
      "severity": "critical",
      "issues": [
        "AR 14% with 214 charges - MID likely frozen/dead, pause it"
      ]
    }
  ],
  "alerts": [
    {
      "source": "metric",
      "label": "Per-provider AR collapse",
      "severity": "critical",
      "hint": "One MID collapsing while others are healthy → pause it in its ATRI so the cascade skips it."
    },
    {
      "source": "provider:Example MID 04",
      "label": "AR 14% with 214 charges - MID likely frozen/dead, pause it",
      "severity": "critical",
      "hint": "See providers[] for detail."
    },
    {
      "source": "metric",
      "label": "Auth-failed request rate",
      "severity": "warn",
      "hint": "Bad/leaked/rotated API key, or a caller pointed at the wrong env."
    },
    {
      "source": "metric",
      "label": "p95 attempt latency",
      "severity": "warn",
      "hint": "Gateway degradation. Rising latency often precedes timeouts/unknowns."
    },
    {
      "source": "metric",
      "label": "MID monthly cap usage",
      "severity": "warn",
      "hint": "A capped MID drops out of routing and shifts load (and risk) onto the rest. Provision ahead of the cap."
    },
    {
      "source": "provider:Example MID 03",
      "label": "cap 87% used",
      "severity": "warn",
      "hint": "See providers[] for detail."
    }
  ],
  "declineReasons": [
    {
      "reason": "DECLINE",
      "count": 187
    },
    {
      "reason": "Insufficient funds",
      "count": 96
    },
    {
      "reason": "Do not honor",
      "count": 74
    },
    {
      "reason": "Invalid card number REFID:918273645",
      "count": 41
    },
    {
      "reason": "(no reason)",
      "count": 18
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `generatedAt` | string (ISO 8601) | Server clock at the moment the snapshot was assembled (new Date().toISOString()). NOT the end of the measurement window and not a cached timestamp - every 200 is computed fresh. |
| `window` | string | Always the literal "24h". Hardcoded; there is no way to request another window. |
| `overallSeverity` | enum: ok\|warn\|critical | Worst severity across metrics[] only (providers[] influence it only through the provider_ar_collapse / mid_cap_usage metrics). 'not_instrumented' metrics are folded to 'ok' first, so this field never returns 'not_instrumented'. |
| `metrics` | Metric[] | Fixed-length array of exactly 16 entries in a stable order: approval_rate, order_volume, unknown_rate, heartbeat, error_rate, duplicate_rate, auth_failed_rate, invalid_body_rate, p95_latency_ms, request_conversion, order_amount_cents, traffic_requests, external_api_forward_failures, pixel_failures, provider_ar_collapse, mid_cap_usage. Key off `key`, never off array index alone. |
| `metrics[].key` | string | Stable machine identifier. The only field safe to branch on. |
| `metrics[].label` | string | Human display name. Also the value used as alerts[].label for metric-sourced alerts. |
| `metrics[].tier` | integer (1\|2\|3) | 1 = page-worthy, 2 = investigate, 3 = informational (tier 3 is hardcoded severity 'ok' and never alerts). |
| `metrics[].value` | number \| null | Current 24h value. NULL for heartbeat when the transactions table has never had a row, and NULL for both not_instrumented metrics. Always null-check. |
| `metrics[].unit` | enum: ratio\|count\|cents\|ms\|minutes | 'ratio' values are 0..1 fractions rounded to 4 decimals (0.7194 = 71.94%), NOT percentages. 'cents' values are integer cents (11659000 = $116,590.00). 'ms' and 'minutes' are integers. |
| `metrics[].dMinus1` | number \| null | Same measure over the PREVIOUS 24h (now-48h .. now-24h). Hardcoded null for heartbeat, p95_latency_ms, provider_ar_collapse, mid_cap_usage and both not_instrumented metrics. |
| `metrics[].avg7d` | number \| null | 7-day baseline. For rates it is the pooled 7d rate; for counts/cents it is the 7d total divided by 7 (a daily average, rounded to 1 decimal); for p95_latency_ms it is the 7d p95, not an average. Null on the same metrics as dMinus1. |
| `metrics[].deltaVs7d` | number \| null | value - avg7d, in the metric's own unit (so for ratios it is an absolute difference in ratio points, e.g. -0.0137 = -1.37pts, not a percentage change). |
| `metrics[].severity` | enum: ok\|warn\|critical\|not_instrumented | Server-side grade. 'not_instrumented' means the data source does not exist yet - treat as no-signal, not as healthy. |
| `metrics[].threshold` | string | Human-readable rule that produced `severity`, e.g. "warn: >2% · crit: >5%". Written in PERCENT while `value` is a 0..1 ratio. Display-only prose - do not parse it. |
| `metrics[].hint` | string | Operator guidance shown next to the metric; copied verbatim into alerts[].hint for metric-sourced alerts. |
| `providers` | ProviderStatus[] | One entry per gateway account (MID) the account owns, ordered by name. Includes deactivated or paused MIDs and MIDs with no traffic in 24 h. |
| `providers[].mid` | string (uuid) | Kontrol's internal gateway account id (uuid), NOT the processor's merchant ID number. |
| `providers[].name` | string | Display name of the gateway account. This (not the uuid) is what appears in alerts[].source as "provider:<name>". |
| `providers[].charges` | integer | Transactions that ended on this account in the last 24h, in the approval rate's base (v3.9 section 1 APPROVAL_BASE: live and completed rows - status approved, declined, error or unknown; pending and duplicate are out). |
| `providers[].approvalRate` | number (0..1 ratio) | approved / charges over the last 24h (v3.9 section 1 - the same approved / completed base as every other AR of the platform), rounded to 4 decimals. 0 when charges is 0. |
| `providers[].capPct` | number (0..1 ratio) | Current-month usage / monthly cap, rounded to 4 decimals. 0 when the account has no cap configured (monthly_cap_cents = 0) - indistinguishable from genuinely zero usage. |
| `providers[].severity` | enum: ok\|warn\|critical | Worst of the AR grade and the cap grade for this account. Never 'not_instrumented'. |
| `providers[].issues` | string[] | Pre-formatted, human-readable problem strings (percentages already rendered with toFixed(0)). Empty when healthy. The tracker rolls these up by substring-matching 'AR' and 'cap', so treat the wording as part of the contract. |
| `alerts` | Array<{source,label,severity,hint}> | Flattened warn+critical items, sorted critical-first. Metric alerts come first within an equal severity, then provider alerts. Empty array when everything is ok. Contains no 'not_instrumented' entries. |
| `alerts[].source` | string | Either the literal "metric" or "provider:<provider name>". Parse the prefix, not the whole string. |
| `alerts[].label` | string | For metric alerts, the metric's label. For provider alerts, that provider's issues[] joined with "; " - a single string, not a list. |
| `alerts[].severity` | enum: warn\|critical | Severity of the underlying metric or provider. |
| `alerts[].hint` | string | The metric's hint, or the constant "See providers[] for detail." for provider alerts. |
| `declineReasons` | Array<{reason,count}> | Top 10 failure reasons over the last 24h, descending by count. Attempt-level (transaction_attempts), covering outcome in ('declined','error','timeout') - ATTEMPT_DECLINED_SQL - on the account's LIVE transactions (v3.9 section 1) - so one order that cascaded across MIDs contributes several rows, and the totals will NOT reconcile with the transaction-level decline counts. |
| `declineReasons[].reason` | string | Raw gateway response_text, falling back to decline_reason, falling back to the literal "(no reason)". Ungrouped and unnormalised - vendor-specific text and embedded reference ids mean near-identical failures can appear as separate rows and fragment the top-10. |
| `declineReasons[].count` | integer | Number of attempts with that exact reason string in the last 24h. |

**Errors**

- `401` `{"error":"Missing status key","detail":"Send X-Status-Key header or Authorization: Bearer <account API key>"}` when no key is presented; `{"error":"Invalid status key"}` when the value is neither an account key nor the platform status secret.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `Banned` (with the ban message) when the key's account owner is banned; `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `{"error":"Forbidden"}` from the global bot guard for a crawler-like User-Agent.
- `429` Per-IP limit of RATE_LIMIT_STATUS requests per minute (default 60), separate from the global budget.
- `503` `{"error":"Service temporarily unavailable"}` when the key lookup fails; `{"error":"Status snapshot failed","detail":"<message>"}` when an aggregate query fails; `Server busy, retry` from the back-pressure guard (Retry-After: 1). Safe to retry.

**Gotchas**

- No query, path or body parameter: window (24 h), thresholds and grading are fixed server-side. Any query string is ignored.
- HTTP 200 does not mean healthy: read overallSeverity and alerts[].
- The 7-day baseline (now-168h..now) includes the 24 h being graded, which dampens deltaVs7d. Same for the p95 latency baseline.
- Denominators differ: approval_rate divides by the live completed charges (approved + declined + error + unknown); unknown_rate, error_rate and duplicate_rate divide by every live transaction (pending and duplicate included). The rates do not sum to 1.
- unit 'ratio' values are 0..1 fractions while the threshold text is written in percent; deltaVs7d on a ratio is an absolute difference in ratio points.
- auth_failed_rate, invalid_body_rate, traffic_requests and request_conversion read only request logs attributed to the account's keys: requests with an unknown key are never counted, so auth_failed_rate reflects banned-owner refusals only.
- severity 'not_instrumented' (external_api_forward_failures, pixel_failures) means no data source exists (value null). They count as ok in overallSeverity and never appear in alerts[].
- heartbeat is null and critical when the account has no transaction at all.
- providers[] includes paused MIDs and the activated flag is not returned. Per-MID AR is graded only from 20 charges in 24 h; capPct is 0 both without a cap and with zero usage.
- order_amount_cents is integer cents; its avg7d and deltaVs7d are rounded to 1 decimal (fractional cents).
- declineReasons is attempt-level raw gateway text (top 10, live transactions only): a cascaded order adds several rows.
- The response is `cache-control: private, no-store`: every poll recomputes the snapshot. Poll no faster than the 60 per minute per-IP budget allows.

### Settings

The Settings menu and the account menu: integrations, monitoring and alerts, members, account settings and the Kontrol subscription, agreements, logs and preferences.

#### Integrations

The integrations catalogue and each integration's configuration, secrets and tests, with their analytics and jobs (3-D Secure, alerts, Pilot, Google Ads, Exify, PlatformPay, smart product matching, creative AI, TheSupportCare).

- Analytics windows compute their totals in the browser: Exify total row; alerts totals and the provider filter (`GET /v1/integrations/alerts` has no provider parameter); smart product matching total rates; 3-D Secure tiles (approval rate with vs without 3-D Secure, the shift in points, fees). The rows come from the integration's analytics endpoint or from `POST /v1/metrics/jobs` with kind `three-ds` / `product-matching`.

##### `GET /v1/expify`

**Scope** `integrations.read` - **Get the Exify export configuration**

Per-account configuration (each account has its own; not a platform operator route). Returns the caller's Exify export configuration: the settings (switch, send percentage, split mode, outcome toggles, test mode) and the targets (v2 current, v1 legacy) with has_*_key flags instead of the secrets. Defaults when the account never saved anything.

*No parameters.*

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "enabled": true,
    "send_pct": 30,
    "duplicate_inhouse": false,
    "success_enabled": true,
    "failed_enabled": true,
    "test_mode": false,
    "test_url": null,
    "updated_at": "2026-11-20T10:00:00.000Z",
    "updated_by": "ops@example.com"
  },
  "targets": [
    {
      "version": "v2",
      "label": "Customer Webhook (current)",
      "url": "https://hooks.example.com/exify",
      "header_name": "x-api-key",
      "account_id": null,
      "has_success_key": true,
      "has_failed_key": true,
      "updated_at": "2026-11-20T10:00:00.000Z"
    }
  ],
  "configured": true
}
```

| response field | type | description |
|---|---|---|
| `settings.owner_email` | string | The account. |
| `settings.enabled` | boolean | Master switch of the export (default false). |
| `settings.send_pct` | integer 0..100 | Percent of eligible sales sent to Exify (default 0). A percentage, not a ratio. |
| `settings.duplicate_inhouse` | boolean | true = the sales sent to Exify are also rebilled by the Kontrol subscription engine; false (default) = an exclusive split. |
| `settings.success_enabled / failed_enabled` | boolean | Include approved sales / finalized failed sales (defaults true). |
| `settings.test_mode` | boolean | Send every batch to test_url and mark nothing. |
| `settings.test_url` | string \| null | Test destination ("" or null when unset). |
| `settings.updated_at / updated_by` | string / string \| null | Last save (epoch 0 and null when never saved). |
| `targets[]` | object[] | The account's targets, v2 first then v1 (match by version, not index). Empty until a target is saved. |
| `targets[].version` | "v1" \| "v2" | v2 = the current customer webhook (the only one fed); v1 = legacy, no longer sent anything. |
| `targets[].label / url / header_name / account_id` | string / string / string / string \| null | Display label, endpoint URL, the header the secret travels in, the v1 account id. |
| `targets[].has_success_key / has_failed_key` | boolean | Whether each secret is stored (values only through GET /v1/expify/credentials). |
| `targets[].updated_at` | string (ISO-8601) | Last save of the target. |
| `configured` | boolean | false when the account never saved its settings (the defaults are shown). |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- send_pct is an integer percentage 0..100, not a 0..1 ratio.
- targets is ordered v2 then v1 and may be empty: match by version.
- The secrets are never in this answer; GET /v1/expify/credentials returns them (not to an API key).

##### `GET /v1/expify/credentials`

**Scope** `integrations.write` - **Read the Exify targets' stored secrets**

Per-account configuration (each account has its own; not a platform operator route). Returns each stored target's success and failed webhook secrets in clear ("" when unset). Answers Cache-Control: no-store and writes one audit row (view_secret) naming the fields, never a value.

*No parameters.*

**Response**

```json
{
  "targets": [
    {
      "version": "v2",
      "successKey": "example-success-secret",
      "failedKey": "example-failed-secret"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `targets[]` | object[] | {version, successKey, failedKey} per stored target; "" when a secret is not set. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"}: the key lacks integrations.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- The refusal for a key without integrations.write carries no requiredScope here (the scope needed is integrations.write).
- Live secrets in clear: never log or cache the answer.

##### `GET /v1/expify/jobs`

**Scope** `integrations.read` - **List queued Exify export jobs**

Lists the Exify export jobs queued on demand (POST /v1/expify/jobs) by the caller; the daily scheduled runs are GET /v1/expify/runs. Lists up to 30 Exify exports of the caller, unresolved ones (unknown or refused deliveries, or not done) first, then newest first.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
      "request_id": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
      "status": "running",
      "phase": "send",
      "policy": {
        "enabled": true,
        "sendPct": 50,
        "duplicate": false,
        "success": true,
        "failed": false,
        "test": false,
        "dry": false,
        "min": 10,
        "max": 200
      },
      "window_start": "2026-11-19T14:00:00.000Z",
      "window_end": "2026-11-20T14:00:00.000Z",
      "discover_older": false,
      "sample_done": "120",
      "sample_target": "60",
      "total": 60,
      "processed": 40,
      "confirmed": 40,
      "refused": 0,
      "unknown": 0,
      "skipped": 0,
      "deferred": 0,
      "cancel_requested": false,
      "error": null,
      "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
      "checkpoint_failures": 0,
      "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
      "created_at": "2026-11-20T14:00:00.000Z",
      "updated_at": "2026-11-20T14:02:10.000Z",
      "finished_at": null,
      "failed": 0,
      "result": {
        "done": 40,
        "skipped": 0
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs` | object[] | At most 30 jobs. |
| `jobs[].id` | string (uuid) | Job id. |
| `jobs[].request_id` | string (uuid) | The requestId sent at creation. |
| `jobs[].status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `jobs[].phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `jobs[].policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `jobs[].window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `jobs[].window_end` | string (ISO 8601) | End of the window (creation time). |
| `jobs[].discover_older` | boolean | Internal discovery flag. |
| `jobs[].sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `jobs[].sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `jobs[].total` | integer | Items in the job. |
| `jobs[].processed` | integer | Items handled. |
| `jobs[].confirmed` | integer | Items Exify accepted. |
| `jobs[].refused` | integer | Items Exify refused (or confirmed not delivered). |
| `jobs[].unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `jobs[].skipped` | integer | Items skipped. |
| `jobs[].deferred` | integer | Items deferred to a later export. |
| `jobs[].cancel_requested` | boolean | True once a cancel was requested. |
| `jobs[].error` | string \| null | Failure reason. |
| `jobs[].detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `jobs[].checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `jobs[].next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `jobs[].created_at` | string (ISO 8601) | Creation time. |
| `jobs[].updated_at` | string (ISO 8601) | Last change. |
| `jobs[].finished_at` | string \| null | End time. |
| `jobs[].failed` | integer | refused + unknown. |
| `jobs[].result` | object | {done: confirmed, skipped}. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- No pagination.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/expify/jobs`

**Scope** `integrations.write` - **Queue an Exify export**

Queues a durable export of the account's eligible straight sales to Exify and answers 202 {jobId, job}. Eligible: the account's own live NMI straight sales of the window (the last 24 hours, extended back to the end of the last completed live export, at most 48 hours), approved ones when success export is on and declined ones when failed export is on, limited to the account's send percentage unless duplicate or test mode is on, and not already exported. The worker samples, then sends batches of the configured size.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Your idempotency key. The same requestId with the same test flag returns the existing job; with a different flag it answers 409. |
| `test` | boolean; default `false` | no | true = send to the account's Exify test URL (batch minimum 1). The account's test_mode setting forces test mode too. |

**Request body**

```json
{
  "requestId": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
  "test": false
}
```

**Response**

```json
{
  "jobId": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
  "job": {
    "id": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
    "request_id": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
    "status": "queued",
    "phase": "discover",
    "policy": {
      "enabled": true,
      "sendPct": 50,
      "duplicate": false,
      "success": true,
      "failed": false,
      "test": false,
      "dry": false,
      "min": 10,
      "max": 200
    },
    "window_start": "2026-11-19T14:00:00.000Z",
    "window_end": "2026-11-20T14:00:00.000Z",
    "discover_older": false,
    "sample_done": "0",
    "sample_target": null,
    "total": 0,
    "processed": 0,
    "confirmed": 0,
    "refused": 0,
    "unknown": 0,
    "skipped": 0,
    "deferred": 0,
    "cancel_requested": false,
    "error": null,
    "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
    "checkpoint_failures": 0,
    "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:00:00.000Z",
    "finished_at": null,
    "failed": 0,
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | string (uuid) | The job id. |
| `job` | object | The job (HTTP 202). |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `job.phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `job.policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `job.window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `job.window_end` | string (ISO 8601) | End of the window (creation time). |
| `job.discover_older` | boolean | Internal discovery flag. |
| `job.sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `job.sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `job.total` | integer | Items in the job. |
| `job.processed` | integer | Items handled. |
| `job.confirmed` | integer | Items Exify accepted. |
| `job.refused` | integer | Items Exify refused (or confirmed not delivered). |
| `job.unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `job.skipped` | integer | Items skipped. |
| `job.deferred` | integer | Items deferred to a later export. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Failure reason. |
| `job.detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `job.checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `job.next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.failed` | integer | refused + unknown. |
| `job.result` | object | {done: confirmed, skipped}. |

**Errors**

- `400` {"error":"Invalid export request"} for an invalid body.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `409` {"error":"Request ID already belongs to another export"}; {"error":"An export or unresolved legacy run already owns this account"}; {"error":"Exify export is disabled"} when the account's Exify export is off (live mode); {"error":"Test URL is not configured"} in test mode; {"error":"Invalid export batch settings"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Durable Exify exports are disabled"} when background jobs are off on this deployment.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- Strict body: an unknown field is a 400.
- One export per account at a time, including an unresolved legacy run: another answers 409 while it owns the account.
- The Exify settings (enabled, send percentage, success / failed, test URL) are frozen in policy at creation; configure them first (Exify settings of the account).
- An accepted delivery cannot be recalled. An ambiguous delivery becomes unknown and is never resent automatically: investigate it, then resolve the batch.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/expify/jobs/:id`

**Scope** `integrations.read` - **Get an Exify export**

Reads one export with its counters. Poll it until phase is done.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |

**Response**

```json
{
  "job": {
    "id": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
    "request_id": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
    "status": "running",
    "phase": "send",
    "policy": {
      "enabled": true,
      "sendPct": 50,
      "duplicate": false,
      "success": true,
      "failed": false,
      "test": false,
      "dry": false,
      "min": 10,
      "max": 200
    },
    "window_start": "2026-11-19T14:00:00.000Z",
    "window_end": "2026-11-20T14:00:00.000Z",
    "discover_older": false,
    "sample_done": "120",
    "sample_target": "60",
    "total": 60,
    "processed": 40,
    "confirmed": 40,
    "refused": 0,
    "unknown": 0,
    "skipped": 0,
    "deferred": 0,
    "cancel_requested": false,
    "error": null,
    "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
    "checkpoint_failures": 0,
    "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:02:10.000Z",
    "finished_at": null,
    "failed": 0,
    "result": {
      "done": 40,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job. |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `job.phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `job.policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `job.window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `job.window_end` | string (ISO 8601) | End of the window (creation time). |
| `job.discover_older` | boolean | Internal discovery flag. |
| `job.sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `job.sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `job.total` | integer | Items in the job. |
| `job.processed` | integer | Items handled. |
| `job.confirmed` | integer | Items Exify accepted. |
| `job.refused` | integer | Items Exify refused (or confirmed not delivered). |
| `job.unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `job.skipped` | integer | Items skipped. |
| `job.deferred` | integer | Items deferred to a later export. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Failure reason. |
| `job.detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `job.checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `job.next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.failed` | integer | refused + unknown. |
| `job.result` | object | {done: confirmed, skipped}. |

**Errors**

- `400` {"error":"Invalid export ID"} when id (or batchId) is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- Available while workers are paused.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/expify/jobs/:id/batches`

**Scope** `integrations.read` - **List the batches of an Exify export**

Lists the delivery batches of one export, 1 to 100 per page (keyset pagination by batch id).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `after` | string (uuid) | no | The next value of the previous page; omit for the first page. |
| `limit` | integer; default `100` | no | Rows per page, 1 to 100. |

**Response**

```json
{
  "batches": [
    {
      "id": "6d2b9f4c-1a7e-4c3b-9e5d-8f0a2c4e6b71",
      "outcome": "success",
      "state": "confirmed",
      "item_count": 40,
      "accepted": 40,
      "rejected": 0,
      "reason": null,
      "intent_at": "2026-11-20T14:01:00.000Z",
      "finished_at": "2026-11-20T14:01:03.000Z",
      "operator_reference": null,
      "retry_job_id": null
    }
  ],
  "next": null
}
```

| response field | type | description |
|---|---|---|
| `batches` | object[] | Batches ordered by id. |
| `batches[].id` | string (uuid) | Batch id (use as after, and in resolve / retry). |
| `batches[].outcome` | enum: success \| failed | Which sales the batch carries. |
| `batches[].state` | enum: intent \| confirmed \| refused \| unknown | intent = being sent; unknown = outcome not known (investigate, then resolve). |
| `batches[].item_count` | integer | Items in the batch. |
| `batches[].accepted` | integer \| null | Items Exify accepted. |
| `batches[].rejected` | integer \| null | Items Exify rejected. |
| `batches[].reason` | string \| null | Outcome reason. |
| `batches[].intent_at` | string (ISO 8601) | When the send started. |
| `batches[].finished_at` | string \| null | When the outcome was recorded. |
| `batches[].operator_reference` | string \| null | Reference given when the batch was resolved or retried. |
| `batches[].retry_job_id` | string (uuid) \| null | The export created by an explicit retry of this batch. |
| `next` | string (uuid) \| null | Pass as after for the next page; null when the page is not full. |

**Errors**

- `400` {"error":"Invalid pagination"}; {"error":"Invalid export ID"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/expify/jobs/:id/batches/:batchId/resolve`

**Scope** `integrations.write` - **Resolve an unknown Exify batch**

Records the result of your own investigation of a batch whose delivery is unknown: confirmed (Exify has the items) or not_delivered (they are marked refused, which allows an explicit retry). Recounts the job and returns it.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |
| `batchId` | string (uuid) | **yes** | Batch id of that job (from GET /v1/expify/jobs/:id/batches). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `decision` | enum: confirmed \| not_delivered | **yes** | Outcome established with Exify. |
| `reference` | string | **yes** | Short investigation or ticket reference, 3 to 121 characters, starting with a letter, then letters, digits, dot, underscore, colon, slash, space or hyphen, and no run of 12 or more digits (400 "Use a short investigation ticket reference, not source data"). Never paste provider bodies, cards or credentials. |

**Request body**

```json
{
  "decision": "not_delivered",
  "reference": "TICKET-1042"
}
```

**Response**

```json
{
  "job": {
    "id": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
    "request_id": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
    "status": "partial",
    "phase": "done",
    "policy": {
      "enabled": true,
      "sendPct": 50,
      "duplicate": false,
      "success": true,
      "failed": false,
      "test": false,
      "dry": false,
      "min": 10,
      "max": 200
    },
    "window_start": "2026-11-19T14:00:00.000Z",
    "window_end": "2026-11-20T14:00:00.000Z",
    "discover_older": false,
    "sample_done": "120",
    "sample_target": "60",
    "total": 60,
    "processed": 40,
    "confirmed": 40,
    "refused": 20,
    "unknown": 0,
    "skipped": 0,
    "deferred": 0,
    "cancel_requested": false,
    "error": null,
    "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
    "checkpoint_failures": 0,
    "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:02:10.000Z",
    "finished_at": "2026-11-20T15:00:00.000Z",
    "failed": 20,
    "result": {
      "done": 40,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after the recount (a finished job becomes partial while refused, unknown or deferred items remain, else success). |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `job.phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `job.policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `job.window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `job.window_end` | string (ISO 8601) | End of the window (creation time). |
| `job.discover_older` | boolean | Internal discovery flag. |
| `job.sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `job.sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `job.total` | integer | Items in the job. |
| `job.processed` | integer | Items handled. |
| `job.confirmed` | integer | Items Exify accepted. |
| `job.refused` | integer | Items Exify refused (or confirmed not delivered). |
| `job.unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `job.skipped` | integer | Items skipped. |
| `job.deferred` | integer | Items deferred to a later export. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Failure reason. |
| `job.detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `job.checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `job.next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.failed` | integer | refused + unknown. |
| `job.result` | object | {done: confirmed, skipped}. |

**Errors**

- `400` {"error":"Invalid investigation result"} for an invalid body; {"error":"Invalid export ID"}; {"error":"Use a short investigation ticket reference, not source data"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `409` {"error":"Only an unknown delivery can be resolved; wait for any active request"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- Only a batch in state unknown can be resolved (409 otherwise). Repeating the same decision with the same reference returns the job unchanged.
- Strict body.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/expify/jobs/:id/batches/:batchId/retry`

**Scope** `integrations.write` - **Retry a refused Exify batch**

Creates a new export that re-sends exactly the items of one refused batch of a finished export (an unknown batch is never retried) and answers 202 {jobId, job} with that new export.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |
| `batchId` | string (uuid) | **yes** | Batch id of that job (from GET /v1/expify/jobs/:id/batches). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | string (uuid) | **yes** | Idempotency key of the retry export. Repeating it returns the same retry export. |
| `reference` | string | **yes** | Short investigation or ticket reference, 3 to 121 characters, starting with a letter, then letters, digits, dot, underscore, colon, slash, space or hyphen, and no run of 12 or more digits (400 "Use a short investigation ticket reference, not source data"). Never paste provider bodies, cards or credentials. |

**Request body**

```json
{
  "requestId": "5c9e3a1d-7b2f-4d6e-8a4c-0b1f3d5e7a92",
  "reference": "TICKET-1042"
}
```

**Response**

```json
{
  "jobId": "2a6c8e0b-4d1f-4b3a-9c7e-5f1b3d7a9c26",
  "job": {
    "id": "2a6c8e0b-4d1f-4b3a-9c7e-5f1b3d7a9c26",
    "request_id": "5c9e3a1d-7b2f-4d6e-8a4c-0b1f3d5e7a92",
    "status": "queued",
    "phase": "send",
    "policy": {
      "enabled": true,
      "sendPct": 50,
      "duplicate": false,
      "success": true,
      "failed": false,
      "test": false,
      "dry": false,
      "min": 10,
      "max": 200
    },
    "window_start": "2026-11-19T14:00:00.000Z",
    "window_end": "2026-11-20T14:00:00.000Z",
    "discover_older": false,
    "sample_done": "120",
    "sample_target": null,
    "total": 20,
    "processed": 0,
    "confirmed": 0,
    "refused": 0,
    "unknown": 0,
    "skipped": 0,
    "deferred": 0,
    "cancel_requested": false,
    "error": null,
    "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
    "checkpoint_failures": 0,
    "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:02:10.000Z",
    "finished_at": null,
    "failed": 0,
    "result": {
      "done": 0,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | string (uuid) | The new retry export. |
| `job` | object | The retry export (HTTP 202). |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `job.phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `job.policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `job.window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `job.window_end` | string (ISO 8601) | End of the window (creation time). |
| `job.discover_older` | boolean | Internal discovery flag. |
| `job.sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `job.sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `job.total` | integer | Items in the job. |
| `job.processed` | integer | Items handled. |
| `job.confirmed` | integer | Items Exify accepted. |
| `job.refused` | integer | Items Exify refused (or confirmed not delivered). |
| `job.unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `job.skipped` | integer | Items skipped. |
| `job.deferred` | integer | Items deferred to a later export. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Failure reason. |
| `job.detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `job.checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `job.next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.failed` | integer | refused + unknown. |
| `job.result` | object | {done: confirmed, skipped}. |

**Errors**

- `400` {"error":"Invalid explicit retry request"} for an invalid body; {"error":"Invalid export ID"}; {"error":"Use a short investigation ticket reference, not source data"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `409` {"error":"This refusal already has an explicit retry"}; {"error":"Retry requires a finished export and confirmed non-delivery; unknown is never retried"}; {"error":"Test mode changed; cannot reuse this delivery reservation"}; {"error":"Delivery reservations changed; investigate before retry"}; {"error":"An export or unresolved legacy run already owns this account"}; {"error":"Exify export is disabled"}; {"error":"Test URL is not configured"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Durable Exify exports are disabled"} when background jobs are off on this deployment.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- One explicit retry per refused batch: a second retry with another requestId answers 409.
- The retry export takes the account's single export slot: it answers 409 while another export owns the account.
- Strict body.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `POST /v1/expify/jobs/:id/cancel`

**Scope** `integrations.write` - **Cancel an Exify export**

Requests cancellation: work not yet dispatched stops; a batch already accepted by Exify cannot be recalled. Returns the job with cancel_requested true.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |

**Response**

```json
{
  "job": {
    "id": "8e2c4a6b-1f3d-4b7e-9a5c-0d2f6b8e4a17",
    "request_id": "3b7d1f5a-9c2e-4a8b-b6d4-1e0f3c7a9b52",
    "status": "running",
    "phase": "send",
    "policy": {
      "enabled": true,
      "sendPct": 50,
      "duplicate": false,
      "success": true,
      "failed": false,
      "test": false,
      "dry": false,
      "min": 10,
      "max": 200
    },
    "window_start": "2026-11-19T14:00:00.000Z",
    "window_end": "2026-11-20T14:00:00.000Z",
    "discover_older": false,
    "sample_done": "120",
    "sample_target": "60",
    "total": 60,
    "processed": 40,
    "confirmed": 40,
    "refused": 0,
    "unknown": 0,
    "skipped": 0,
    "deferred": 0,
    "cancel_requested": true,
    "error": null,
    "detail_cleanup_at": "2026-11-20T14:00:00.000Z",
    "checkpoint_failures": 0,
    "next_checkpoint_at": "2026-11-20T14:00:00.000Z",
    "created_at": "2026-11-20T14:00:00.000Z",
    "updated_at": "2026-11-20T14:02:10.000Z",
    "finished_at": null,
    "failed": 0,
    "result": {
      "done": 40,
      "skipped": 0
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job as read before the update, with cancel_requested true. |
| `job.id` | string (uuid) | Job id. |
| `job.request_id` | string (uuid) | The requestId sent at creation. |
| `job.status` | enum: queued \| discovering \| sampling \| running \| success \| partial \| failed \| cancelled | Lifecycle status; partial = finished with refused, unknown or deferred deliveries. |
| `job.phase` | enum: discover \| sample \| send \| done | discover = finding eligible sales; sample = applying the send percentage; send = delivering batches; done. |
| `job.policy` | object | Account Exify settings frozen at creation: {enabled, sendPct, duplicate, success, failed, test, dry, min, max} (min and max are batch sizes; max is at most 200). |
| `job.window_start` | string (ISO 8601) | Start of the sales window (24 hours before creation, or back to the end of the last completed live export, at most 48 hours). |
| `job.window_end` | string (ISO 8601) | End of the window (creation time). |
| `job.discover_older` | boolean | Internal discovery flag. |
| `job.sample_done` | string (integer) | Candidates sampled so far (a bigint serialized as a string). |
| `job.sample_target` | string (integer) \| null | Candidates to send after sampling (bigint as string); null until discovery completes, and on a batch retry. |
| `job.total` | integer | Items in the job. |
| `job.processed` | integer | Items handled. |
| `job.confirmed` | integer | Items Exify accepted. |
| `job.refused` | integer | Items Exify refused (or confirmed not delivered). |
| `job.unknown` | integer | Items whose delivery outcome is unknown (never resent automatically). |
| `job.skipped` | integer | Items skipped. |
| `job.deferred` | integer | Items deferred to a later export. |
| `job.cancel_requested` | boolean | True once a cancel was requested. |
| `job.error` | string \| null | Failure reason. |
| `job.detail_cleanup_at` | string (ISO 8601) | Internal pruning checkpoint. |
| `job.checkpoint_failures` | integer | Consecutive checkpoint failures of the worker. |
| `job.next_checkpoint_at` | string (ISO 8601) | When the worker may next run a checkpoint. |
| `job.created_at` | string (ISO 8601) | Creation time. |
| `job.updated_at` | string (ISO 8601) | Last change. |
| `job.finished_at` | string \| null | End time. |
| `job.failed` | integer | refused + unknown. |
| `job.result` | object | {done: confirmed, skipped}. |

**Errors**

- `400` {"error":"Invalid export ID"} when id (or batchId) is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- No body is read.
- The status changes when the worker notices the request; poll GET /v1/expify/jobs/:id.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/expify/jobs/:id/items`

**Scope** `integrations.read` - **List the items of an Exify export**

Lists the transactions of one export with their delivery state, 1 to 100 per page (keyset pagination by item id). References only: no card or customer data.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Export job id. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `after` | string (uuid) | no | The next value of the previous page; omit for the first page. |
| `limit` | integer; default `100` | no | Rows per page, 1 to 100. |

**Response**

```json
{
  "items": [
    {
      "id": "0f4b8d2a-6c1e-4a9b-8d3f-5e7a1c9b2d64",
      "transaction_id": "9a1c5e3b-7d2f-4b6a-8c4e-2f0b6d8a1c35",
      "outcome": "success",
      "state": "confirmed",
      "reason": null,
      "batch_id": "6d2b9f4c-1a7e-4c3b-9e5d-8f0a2c4e6b71"
    }
  ],
  "next": null
}
```

| response field | type | description |
|---|---|---|
| `items` | object[] | Items ordered by id. |
| `items[].id` | string (uuid) | Item id (use as after). |
| `items[].transaction_id` | string (uuid) | The exported transaction. |
| `items[].outcome` | enum: success \| failed | Approved sale or declined sale. |
| `items[].state` | enum: candidate \| ready \| confirmed \| refused \| unknown \| skipped \| deferred \| cancelled | Delivery state. |
| `items[].reason` | string \| null | Reason of a refusal, skip or deferral. |
| `items[].batch_id` | string (uuid) \| null | Batch the item was sent in. |
| `next` | string (uuid) \| null | Pass as after for the next page; null when the page is not full. |

**Errors**

- `400` {"error":"Invalid pagination"} when after is not a uuid or limit is out of range; {"error":"Invalid export ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Account access or permissions changed"} when the key was deactivated, its owner banned, the key belongs to a sub-account login, or the account changed.
- `404` {"error":"Export not found"} when the job (or the batch) is not visible to the caller.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- Item details are pruned 90 days after resolution.
- A job is visible only to the caller that created it (the same API key or login, with the same account scope); another key of the account gets 404. The key must belong to the account owner (a key of a sub-account login is refused with 403).

##### `GET /v1/expify/jobs/capability`

**Scope** `integrations.read` - **Exify export job capability**

Says whether durable Exify exports can be queued on this deployment (POST /v1/expify/jobs). Read-only.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

| response field | type | description |
|---|---|---|
| `enabled` | boolean | True when background jobs run and the export storage exists. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Required storage for Exify exports is unavailable. Complete the current database migrations.","requestId":"<id>"} when background jobs run but the job storage is missing.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 10-second control budget is exceeded.

**Gotchas**

- When background jobs run but the export storage is missing, the answer is a 503 {"error":"Required storage for Exify exports is unavailable. Complete the current database migrations.","requestId":"<id>"} (a missing migration), not enabled:false.

##### `GET /v1/expify/preview`

**Scope** `integrations.read` - **Preview Exify export payloads**

Per-account configuration (each account has its own; not a platform operator route). Shows what the export would POST: for recent transactions of the account with a stored order (or the transactions of one orderId), the element of the v2 "customers" array built by the export's own mapper. Read-only: it ignores eligibility and marks nothing.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer 1..50; default `5` | no | Rows to sample, newest first. Non-numeric or 0 becomes 5; clamped to 1..50. |
| `orderId` | string | no | Exact order id: returns that order's transactions (every attempt, newest first, up to limit), including rows without a stored order (v2 null). Without it, only rows with a stored order are sampled. |

**Response**

```json
{
  "count": 1,
  "note": "Each `v2` is one element of the `customers` array this account would POST to the v2 endpoint, built by the export's own mapper.",
  "samples": [
    {
      "orderId": "ORD-1001",
      "outcome": "success",
      "hasRawPayload": true,
      "hasCard": true,
      "v2": {
        "firstName": "Jane",
        "lastName": "Doe",
        "email": "jane.doe@example.com",
        "phone": "+15555550100",
        "orderDate": "2026-11-23T14:02:11.000Z",
        "address": {
          "line1": "1 Main St",
          "city": "Austin",
          "state": "TX",
          "postalCode": "78701",
          "country": "US"
        },
        "card": {
          "number": "4111111111111111",
          "expiredAt": "12/30",
          "cvc": "123",
          "type": "visa"
        },
        "ipAddress": "203.0.113.10",
        "userAgent": "Mozilla/5.0"
      }
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `count` | integer | Number of samples. |
| `note` | string | Fixed explanation. |
| `samples[].orderId` | string | Order id. |
| `samples[].outcome` | "success" \| "failed" | From is_success. |
| `samples[].hasRawPayload / hasCard` | boolean | Whether a stored order / a card number exists. |
| `samples[].v2` | object \| null | The exported element: firstName, lastName, email, phone, orderDate, address {line1, city, state, postalCode, country}, card {number, expiredAt MM/YY, cvc, type}, ipAddress, userAgent. null when the row has no stored order (it cannot be exported). |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).
- `504` Statement timeout on the transactions scan.

**Gotchas**

- The sample is exactly the payload: the card number, expiry and security code are in clear for role admin and API keys (masked first6..last4 without the code for role user). Treat the answer as card data.
- Eligibility is not applied: a sample may never be exported (window, outcome toggles, rebills and already-sent rows are ignored here).
- An unknown orderId answers 200 with count 0.
- Only v2 is shown: v1 is no longer sent anything.

##### `POST /v1/expify/run`

**Scope** `integrations.write` - **Run the Exify export now (retired)**

Per-account configuration (each account has its own; not a platform operator route). Retired: always answers 409. Start an export with the durable Exify export job (POST /v1/expify/jobs with a stable requestId) and poll it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `test` | boolean | no | Accepted and ignored: the route is retired and answers 409 to every caller. Queue an export with POST /v1/expify/jobs instead. |

**Response**

```json
{
  "error": "Use the durable Exify export action with a request ID"
}
```

| response field | type | description |
|---|---|---|
| `status` | enum: success\|partial\|failed\|disabled | 'disabled' = master switch off and no forced test (nothing selected, a run row is still written); 'failed' = test mode requested with no test_url (NO run row is written); 'partial' = at least one issue string; 'success' = no issue strings. |
| `testMode` | boolean | The effective test mode for this run: body.test === true, otherwise settings.test_mode. |
| `windowStart` | string (ISO-8601) | now minus 24 hours. Fixed - not settable over HTTP. |
| `windowEnd` | string (ISO-8601) | The moment the run started. |
| `eligible` | integer | Rows matching the window and all filters (expify_state is null, crm='nmi', not a rebill, outcome enabled). |
| `sent` | integer | Rows POSTed OK and marked 'sent'. Under EXIFY_DRY_RUN this instead reports the sampled count with zero real traffic. |
| `skipped` | integer | Size of the send_pct holdout only - permanently marked 'skipped' and never re-selected. Rows dropped for an unusable payload are marked 'skipped' in the DB but not counted here. |
| `rejected` | integer | Per-row rejections Exify reported inside otherwise-OK responses. |
| `errors` | string[] | Issue lines (no secret configured, sub-minimum batch held, HTTP failures, per-row messages). Capped at 50. |
| `targets[]` | object[] | Per version+outcome stats: { version, outcome, url, batches, sent, rejected }. Absent for combos with no rows. Note url is the test_url while in test mode. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"} when the key's scopes lack integrations.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `409` {"error":"Use the durable Exify export action with a request ID"}: always, nothing runs.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- Nothing is read from the body and nothing is sent.

##### `GET /v1/expify/runs`

**Scope** `integrations.read` - **List scheduled Exify export runs (daily cron log)**

Per-account configuration (each account has its own; not a platform operator route). Lists the scheduled Exify export runs of the account (the daily cron log); exports queued on demand are GET /v1/expify/jobs. The export log of the caller's account: the most recent runs, newest first, with window, status, counts, error and a detail object.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer 1..10000; default `30` | no | Runs to return. Non-numeric or 0 becomes 30; clamped to 1..10000. No offset. |

**Response**

```json
{
  "runs": [
    {
      "id": "9c1f0a72-4d3e-4f10-a8b1-7b9c2d5e6f30",
      "created_at": "2026-08-26T04:00:01.884Z",
      "completed_at": "2026-08-26T04:01:47.219Z",
      "window_start": "2026-08-25T04:00:01.802Z",
      "window_end": "2026-08-26T04:00:01.802Z",
      "status": "partial",
      "eligible_count": 412,
      "sent_count": 240,
      "skipped_count": 165,
      "rejected_count": 3,
      "error": "2 issue(s)",
      "detail": {
        "testMode": false,
        "targets": [
          { "version": "v1", "outcome": "success", "url": "https://legacy.exify.io/webhook/customers", "batches": 1, "sent": 68, "rejected": 3 },
          { "version": "v2", "outcome": "success", "url": "https://api.exify.io/v2/customers", "batches": 1, "sent": 172, "rejected": 0 }
        ],
        "errors": [
          "v1/failed: no secret configured - deferred 4 (retry once key is set)",
          "v2/failed: held 3 (below min batch 10) - retry next run"
        ],
        "deferred": 7
      }
    },
    {
      "id": "1b7d3e55-90aa-4c62-8f11-0d4a6c8e2211",
      "created_at": "2026-08-25T04:00:02.041Z",
      "completed_at": "2026-08-25T04:00:02.365Z",
      "window_start": "2026-08-24T04:00:01.960Z",
      "window_end": "2026-08-25T04:00:01.960Z",
      "status": "disabled",
      "eligible_count": 0,
      "sent_count": 0,
      "skipped_count": 0,
      "rejected_count": 0,
      "error": null,
      "detail": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `runs[].id` | string (uuid) | Run id - feed this to GET /v1/expify/runs/:id/sends. |
| `runs[].created_at` | string (ISO-8601) | When the run row was inserted (run start). Sort key, DESC. |
| `runs[].completed_at` | string (ISO-8601) \| null | Null means the run never reached completion (still running, or the process died mid-run). |
| `runs[].window_start` | string (ISO-8601) | Start of the selection window, applied to transactions.created_at (>=). |
| `runs[].window_end` | string (ISO-8601) | End of the selection window, applied to transactions.created_at (exclusive, <). |
| `runs[].status` | enum: success\|partial\|failed\|disabled | 'partial' = at least one issue was recorded (see detail.errors); 'disabled' = the master switch was off, nothing selected. |
| `runs[].eligible_count` | integer | Rows matching the window + filters (NMI credit-card, straight sales only, not previously marked). |
| `runs[].sent_count` | integer | Rows actually POSTed OK and marked 'sent'. In a dry run this reports the sampled count even though nothing was POSTed. |
| `runs[].skipped_count` | integer | Size of the send_pct HOLDOUT only. Rows dropped for an unusable payload are also marked 'skipped' in the DB but are NOT counted here. |
| `runs[].rejected_count` | integer | Per-row rejections reported by Exify inside an otherwise-OK 200 response. |
| `runs[].error` | string \| null | Only a count summary such as "2 issue(s)" - the actual messages are in detail.errors. |
| `runs[].detail` | object \| null | { testMode, targets[], errors[], deferred }. `deferred` is written by the job but is missing from the declared TypeScript type - treat it as optional. |
| `runs[].detail.targets[]` | object[] | Per version+outcome: { version, outcome, url, batches, sent, rejected }. A version/outcome combo with zero rows produces no entry at all. |
| `runs[].detail.errors[]` | string[] | Free-text issue lines, CAPPED AT 50 - a badly failing run silently truncates the rest. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- The platform owner's account also sees the runs from before exports were per account.
- sent_count + skipped_count is not eligible_count: deferred rows (no secret, small batch, failed POST) are only in detail.
- status success means no issue was recorded; Exify may still have rejected rows (rejected_count).

##### `GET /v1/expify/runs/:id/sends`

**Scope** `integrations.read` - **List the sends of an Exify run**

Per-account configuration (each account has its own; not a platform operator route). The raw HTTP send log of one run of the caller's account: one row per POST to Exify with status, response body and rejected count, oldest first.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Run id from GET /v1/expify/runs. Not validated before the query: not a uuid = 400 "A value has an invalid format.". |

**Response**

```json
{
  "sends": [
    {
      "id": "5a2e91c4-6f77-4a03-b0c6-3e1d8f9a4472",
      "created_at": "2026-08-26T04:00:39.512Z",
      "version": "v1",
      "outcome": "success",
      "url": "https://legacy.exify.io/webhook/customers",
      "test_mode": false,
      "batch_size": 68,
      "http_status": 200,
      "ok": true,
      "rejected": 3,
      "response_text": "{\"accepted\":65,\"rejected\":[{\"row\":12,\"message\":\"invalid postalCode\"}]}",
      "response_json": {
        "accepted": 65,
        "rejected": [
          { "row": 12, "message": "invalid postalCode" }
        ]
      },
      "error": null
    },
    {
      "id": "c07b4d18-2a55-4e91-9b3f-77c0e5a1b902",
      "created_at": "2026-08-26T04:01:12.884Z",
      "version": "v2",
      "outcome": "success",
      "url": "https://api.exify.io/v2/customers",
      "test_mode": false,
      "batch_size": 172,
      "http_status": 502,
      "ok": false,
      "rejected": 0,
      "response_text": "<html><head><title>502 Bad Gateway</title></head></html>",
      "response_json": null,
      "error": "HTTP 502"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `sends[].id` | string (uuid) | Send-log row id. |
| `sends[].created_at` | string (ISO-8601) | When the POST was logged. Rows are ordered created_at ASC (oldest first) - the opposite of /runs. |
| `sends[].version` | string \| null | 'v1' or 'v2' - which target shape this batch used. |
| `sends[].outcome` | string \| null | 'success' or 'failed' - which outcome group this batch carried (drives which secret was used). |
| `sends[].url` | string \| null | The URL actually POSTed to. In test mode this is settings.test_url, NOT the target url. |
| `sends[].test_mode` | boolean | True when the batch was a dry-fire to the test URL (rows were not marked). |
| `sends[].batch_size` | integer | Number of customer objects in this POST (production min 10, max 199 by default env). |
| `sends[].http_status` | integer \| null | HTTP status Exify returned. Null if the request never produced a status (transport failure). |
| `sends[].ok` | boolean \| null | Whether the client considered the POST successful. Rows are marked 'sent' only when this is true. |
| `sends[].rejected` | integer | Per-row rejections Exify reported inside an OK response - these rows are still marked 'sent' locally and will never be retried. |
| `sends[].response_text` | string \| null | Verbatim response body, may be HTML or plain text. Null when the body was empty. |
| `sends[].response_json` | object \| null | The same body re-parsed as JSON; null whenever the body was not valid JSON. |
| `sends[].error` | string \| null | First error message, or 'HTTP <status>' when the POST failed without a parseable error. |

**Errors**

- `400` {"error":"A value has an invalid format."}: id is not a uuid.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- An unknown run, or another account's, answers 200 {"sends":[]} (no 404).
- No limit: every send of the run is returned.
- response_json is null when the body was not JSON; read response_text.

##### `PATCH /v1/expify/settings`

**Scope** `integrations.write` - **Update Exify export settings**

Per-account configuration (each account has its own; not a platform operator route). Partially updates the caller's Exify settings (the row is created with defaults on the first save) and returns the whole refreshed configuration. Turning enabled on or off also mirrors the switch into the account's integrations list.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | no | Master switch. |
| `send_pct` | integer 0..100 | no | Percent of eligible sales sent to Exify. 0.6 is a 400; 1 means one percent. |
| `duplicate_inhouse` | boolean | no | true = sales sent to Exify are also rebilled by Kontrol; false = exclusive split. |
| `success_enabled` | boolean | no | Include approved sales. |
| `failed_enabled` | boolean | no | Include finalized failed sales. |
| `test_mode` | boolean | no | Send to test_url and mark nothing. |
| `test_url` | URL \| "" | no | Test destination; "" clears it. |

**Request body**

```json
{
  "enabled": true,
  "send_pct": 30,
  "duplicate_inhouse": false
}
```

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "enabled": true,
    "send_pct": 30,
    "duplicate_inhouse": false,
    "success_enabled": true,
    "failed_enabled": true,
    "test_mode": false,
    "test_url": null,
    "updated_at": "2026-11-20T10:00:00.000Z",
    "updated_by": "ops@example.com"
  },
  "targets": [
    {
      "version": "v2",
      "label": "Customer Webhook (current)",
      "url": "https://hooks.example.com/exify",
      "header_name": "x-api-key",
      "account_id": null,
      "has_success_key": true,
      "has_failed_key": true,
      "updated_at": "2026-11-20T10:00:00.000Z"
    }
  ],
  "configured": true
}
```

| response field | type | description |
|---|---|---|
| `settings.owner_email` | string | The account. |
| `settings.enabled` | boolean | Master switch of the export (default false). |
| `settings.send_pct` | integer 0..100 | Percent of eligible sales sent to Exify (default 0). A percentage, not a ratio. |
| `settings.duplicate_inhouse` | boolean | true = the sales sent to Exify are also rebilled by the Kontrol subscription engine; false (default) = an exclusive split. |
| `settings.success_enabled / failed_enabled` | boolean | Include approved sales / finalized failed sales (defaults true). |
| `settings.test_mode` | boolean | Send every batch to test_url and mark nothing. |
| `settings.test_url` | string \| null | Test destination ("" or null when unset). |
| `settings.updated_at / updated_by` | string / string \| null | Last save (epoch 0 and null when never saved). |
| `targets[]` | object[] | The account's targets, v2 first then v1 (match by version, not index). Empty until a target is saved. |
| `targets[].version` | "v1" \| "v2" | v2 = the current customer webhook (the only one fed); v1 = legacy, no longer sent anything. |
| `targets[].label / url / header_name / account_id` | string / string / string / string \| null | Display label, endpoint URL, the header the secret travels in, the v1 account id. |
| `targets[].has_success_key / has_failed_key` | boolean | Whether each secret is stored (values only through GET /v1/expify/credentials). |
| `targets[].updated_at` | string (ISO-8601) | Last save of the target. |
| `configured` | boolean | false when the account never saved its settings (the defaults are shown). |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): a wrong type, a percentage that is not an integer 0..100, a test_url that is neither a URL nor "".
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"} when the key's scopes lack integrations.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Unknown keys are silently dropped (sendPct instead of send_pct changes nothing): compare the answer with what you sent. v1_split_pct is no longer accepted.
- An empty body still writes updated_by / updated_at.
- The subscription engine caches enabled / send_pct / duplicate_inhouse for 60 seconds; the save invalidates that cache for the account at once.
- Last write wins: no concurrency check.

##### `PATCH /v1/expify/targets/:version`

**Scope** `integrations.write` - **Update an Exify target**

Per-account configuration (each account has its own; not a platform operator route). Creates or updates the caller's v1 or v2 target: endpoint URL, label, the header that carries the secret, the v1 account id, and the success / failed secrets (encrypted at rest). Returns the whole refreshed configuration.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `version` | "v1" \| "v2" | **yes** | Which target. Anything else (case-sensitive) = 404 {"error":"Unknown version"}. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `url` | URL | no | Endpoint. When the target does not exist yet it is created with this URL (or a placeholder https://example.com/webhook when absent). |
| `label` | string 1..128 | no | Display label (default "Customer Webhook (current)" for v2, "Legacy Webhook" for v1). |
| `header_name` | string 1..128 | no | Name of the HTTP header the secret is sent in. |
| `account_id` | string <= 128 \| null | no | Sent by the v1 sender as an extra field; unused by v2. |
| `successKey` | string 1..512 | no | Secret for approved sales (camelCase). Encrypted; cannot be cleared, only replaced. |
| `failedKey` | string 1..512 | no | Secret for failed sales (camelCase). Encrypted; cannot be cleared, only replaced. |

**Request body**

```json
{
  "url": "https://hooks.example.com/exify",
  "header_name": "x-api-key",
  "successKey": "example-success-secret",
  "failedKey": "example-failed-secret"
}
```

**Response**

```json
{
  "settings": {
    "owner_email": "ops@example.com",
    "enabled": true,
    "send_pct": 30,
    "duplicate_inhouse": false,
    "success_enabled": true,
    "failed_enabled": true,
    "test_mode": false,
    "test_url": null,
    "updated_at": "2026-11-20T10:00:00.000Z",
    "updated_by": "ops@example.com"
  },
  "targets": [
    {
      "version": "v2",
      "label": "Customer Webhook (current)",
      "url": "https://hooks.example.com/exify",
      "header_name": "x-api-key",
      "account_id": null,
      "has_success_key": true,
      "has_failed_key": true,
      "updated_at": "2026-11-20T10:00:00.000Z"
    }
  ],
  "configured": true
}
```

| response field | type | description |
|---|---|---|
| `settings.owner_email` | string | The account. |
| `settings.enabled` | boolean | Master switch of the export (default false). |
| `settings.send_pct` | integer 0..100 | Percent of eligible sales sent to Exify (default 0). A percentage, not a ratio. |
| `settings.duplicate_inhouse` | boolean | true = the sales sent to Exify are also rebilled by the Kontrol subscription engine; false (default) = an exclusive split. |
| `settings.success_enabled / failed_enabled` | boolean | Include approved sales / finalized failed sales (defaults true). |
| `settings.test_mode` | boolean | Send every batch to test_url and mark nothing. |
| `settings.test_url` | string \| null | Test destination ("" or null when unset). |
| `settings.updated_at / updated_by` | string / string \| null | Last save (epoch 0 and null when never saved). |
| `targets[]` | object[] | The account's targets, v2 first then v1 (match by version, not index). Empty until a target is saved. |
| `targets[].version` | "v1" \| "v2" | v2 = the current customer webhook (the only one fed); v1 = legacy, no longer sent anything. |
| `targets[].label / url / header_name / account_id` | string / string / string / string \| null | Display label, endpoint URL, the header the secret travels in, the v1 account id. |
| `targets[].has_success_key / has_failed_key` | boolean | Whether each secret is stored (values only through GET /v1/expify/credentials). |
| `targets[].updated_at` | string (ISO-8601) | Last save of the target. |
| `configured` | boolean | false when the account never saved its settings (the defaults are shown). |

**Errors**

- `400` {"error":"Invalid","details":{...}} (zod flatten): url not a URL, a string out of its bounds; {"error":"No fields to update"} when the body has none of the six fields.
- `404` {"error":"Unknown version"}
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"} when the key's scopes lack integrations.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"Internal Server Error","requestId":"..."}: the secret could not be encrypted, or another unexpected failure.
- `503` {"error":"Authentication scope is temporarily unavailable"} (the account scope could not load), or {"error":"The database is temporarily unavailable - please retry in a moment."} (Retry-After: 1).

**Gotchas**

- Mixed naming: url, label, header_name, account_id are snake_case, successKey and failedKey camelCase; an unknown key is silently dropped.
- A secret cannot be cleared ("" and null are refused); overwrite it instead.
- Only v2 is fed by the export; v1 is legacy.

##### `GET /v1/integrations`

**Scope** `integrations.read` - **List integrations catalog + account state**

Returns the whole integrations catalog (every integration cocoapi knows, grouped by category, with the field definitions of its Configure form) together with the calling account's state for each entry: enabled, configured (every required field set), the non-secret config and which secrets are set. Exify / PlatformPay state comes from their own settings tables, the Email/SMS provider pools report how many providers hold a credential, and alert providers get their per-account webhook URL. Read-only.

*No parameters.*

**Response**

```json
{
  "categories": [
    {
      "key": "subscription",
      "label": "Subscription"
    },
    {
      "key": "alerts",
      "label": "Alerts"
    },
    {
      "key": "3ds",
      "label": "3DS"
    },
    {
      "key": "tokenization",
      "label": "Tokenization"
    },
    {
      "key": "customer_service",
      "label": "Customer service"
    },
    {
      "key": "messaging",
      "label": "Messaging"
    },
    {
      "key": "ai",
      "label": "AI"
    },
    {
      "key": "domains",
      "label": "Domains"
    },
    {
      "key": "media_buying",
      "label": "Media buying"
    },
    {
      "key": "cloaking",
      "label": "Cloaking"
    }
  ],
  "catalog": [
    {
      "key": "xcaliber",
      "name": "XCaliber",
      "category": "alerts",
      "blurb": "XProtect chargeback & dispute alerts (Ethoca / RDR)",
      "status": "available",
      "byCoco": false,
      "defaultEnabled": false,
      "fields": [
        {
          "name": "apiKey",
          "label": "API key",
          "type": "secret",
          "section": "Credentials",
          "help": "Your XProtect API key."
        },
        {
          "name": "webhookSecret",
          "label": "Webhook secret",
          "type": "secret",
          "section": "Credentials",
          "help": "Sent by XCaliber with each alert (header X-Webhook-Secret or ?token=). Alerts without it are rejected."
        },
        {
          "name": "autoRefund",
          "label": "Auto-refund on alert",
          "type": "toggle",
          "default": false,
          "section": "Alerts",
          "help": "Refund the matched transaction as soon as an alert arrives (blacklists the customer). Off = alerts are only recorded."
        }
      ],
      "exclusiveGroup": null,
      "docsUrl": "https://xcaliber-solutions.com/chargeback-management-software/",
      "webhookUrl": "https://api.kontrolcheckout.com/v1/alerts/xcaliber/merchant%40example.com"
    },
    {
      "key": "paay_3ds",
      "name": "PAAY",
      "category": "3ds",
      "blurb": "EMV 3DS 2.2 via 3DS Integrator (Direct API)",
      "status": "available",
      "byCoco": false,
      "defaultEnabled": false,
      "fields": [
        {
          "name": "apiKey",
          "label": "API key",
          "type": "secret",
          "required": true,
          "section": "Credentials"
        },
        {
          "name": "apiSecret",
          "label": "API secret",
          "type": "secret",
          "required": true,
          "section": "Credentials",
          "help": "Signs the per-request JWT (\"Pass in JWT\" must be ON for the key). Same key pair for both environments."
        },
        {
          "name": "environment",
          "label": "Environment",
          "type": "select",
          "default": "sandbox",
          "section": "Credentials",
          "options": [
            {
              "value": "sandbox",
              "label": "Sandbox (test cards)"
            },
            {
              "value": "production",
              "label": "Production"
            }
          ]
        },
        {
          "name": "merchantUrl",
          "label": "Merchant website",
          "type": "url",
          "required": true,
          "default": "https://kontrolcheckout.com",
          "placeholder": "https://…",
          "section": "Merchant",
          "help": "Sent as Referer / threeDSRequestorURL."
        },
        {
          "name": "challengePreference",
          "label": "Challenge preference",
          "type": "select",
          "default": "no-preference",
          "section": "Authentication",
          "options": [
            {
              "value": "no-preference",
              "label": "Issuer decides (frictionless when possible)"
            },
            {
              "value": "no-challenge",
              "label": "No challenge requested"
            },
            {
              "value": "challenge-requested",
              "label": "Challenge requested"
            },
            {
              "value": "challenge-mandated",
              "label": "Challenge mandated"
            }
          ]
        },
        {
          "name": "attemptFeeUsd",
          "label": "Cost per attempt (USD)",
          "type": "number",
          "default": 0,
          "placeholder": "0.05",
          "section": "Fees"
        }
      ],
      "exclusiveGroup": "3ds",
      "docsUrl": "https://docs.3dsintegrator.com/docs/overview",
      "webhookUrl": null
    }
  ],
  "items": [
    {
      "key": "xcaliber",
      "enabled": true,
      "configured": true,
      "config": {
        "autoRefund": false
      },
      "secretsSet": {
        "apiKey": true,
        "webhookSecret": true
      },
      "updatedAt": "2026-09-02T14:11:08.412Z",
      "updatedBy": "ops@example.com"
    },
    {
      "key": "paay_3ds",
      "enabled": true,
      "configured": true,
      "config": {
        "environment": "production",
        "merchantUrl": "https://example.com",
        "challengePreference": "no-preference",
        "onChallenge": "skip",
        "inline": true,
        "inlineMethodWait": false,
        "requireLiabilityShift": false,
        "retryWithoutThreeDs": false,
        "brandVisa": true,
        "brandMastercard": false,
        "brandAmex": true,
        "brandDiscover": true,
        "onRebills": false,
        "inlineSharePct": 100,
        "attemptFeeUsd": 0.05
      },
      "secretsSet": {
        "apiKey": true,
        "apiSecret": true
      },
      "updatedAt": "2026-08-30T09:00:00.000Z",
      "updatedBy": "ops@example.com"
    },
    {
      "key": "exify",
      "enabled": true,
      "configured": true,
      "config": {
        "send_pct": 100,
        "duplicate_inhouse": false,
        "test_mode": false,
        "targets": [
          {
            "version": "v2",
            "url": "https://hooks.exify.example/v2/orders"
          }
        ]
      },
      "secretsSet": {},
      "updatedAt": null,
      "updatedBy": null
    },
    {
      "key": "platformpay",
      "enabled": false,
      "configured": true,
      "config": {
        "url": "https://platformpay.example/webhook",
        "user_id": "acme",
        "send_pct": 100,
        "hasSecret": true,
        "stats": {
          "sent_24h": 120,
          "ok_24h": 118,
          "failed_24h": 2
        }
      },
      "secretsSet": {},
      "updatedAt": null,
      "updatedBy": null
    },
    {
      "key": "email_providers",
      "enabled": true,
      "configured": true,
      "config": {
        "providers": 2
      },
      "secretsSet": {},
      "updatedAt": null,
      "updatedBy": null
    },
    {
      "key": "smart_product_matching",
      "enabled": true,
      "configured": true,
      "config": {},
      "secretsSet": {},
      "updatedAt": null,
      "updatedBy": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `categories` | array | Category keys in display order with their labels (subscription, alerts, 3ds, tokenization, customer_service, messaging, ai, domains, media_buying, cloaking). |
| `catalog` | array | One entry per integration, in catalog order. Static definitions - identical for every account except webhookUrl. |
| `catalog[].key` | string | Integration key: the :key of PUT /v1/integrations/:key and POST /v1/integrations/:key/test. |
| `catalog[].status` | enum: available\|coming_soon | coming_soon entries (evervault_tokenization) are listed but cannot be saved (PUT -> 409). v3.9.3: pilot (Media buying) is available - fields apiKey (secret; read back through GET /v1/integrations/pilot/secrets - v3.9.8 item 7), baseUrl (default https://pilot.ad), backfillDays (default 92, capped at 92 by the sync), preCloseRefresh (toggle, default on); enabling it with the key saved starts the hourly spend sync (jobs/pilotSpendSync.ts) and the Pilot cards / columns of the dashboard. v3.9.18: google_ads (Media buying) is available - secrets developerToken, clientId, clientSecret, refreshToken (the Google Ads API credentials, typed by the operator, encrypted; read back only through GET /v1/integrations/google_ads/secrets), config loginCustomerId (the manager account, 10 digits) and validateOnly (toggle, default off: every upload is validated by Google and recorded nowhere). With it enabled and a store tag carrying a customer + an "Import from clicks" action, paid orders with a Google click are uploaded by jobs/googleAdsUpload.ts (docs/GOOGLE_ADS.md). |
| `catalog[].byCoco` | boolean | Built by Coco, no third party (email_providers, sms_providers, recovery_templates, smart_product_matching). |
| `catalog[].defaultEnabled` | boolean | Enabled when the account never touched it (recovery_templates, smart_product_matching). |
| `catalog[].fields` | array | FieldDef list {name, label, type: text\|secret\|url\|number\|toggle\|select, required?, options?, default?, help?, placeholder?, section?}. Non-secret names are the accepted `config` keys, secret names the accepted `secrets` keys of the PUT. Empty for entries configured through their own screens (exify, platformpay, messaging pools). Optional enabledWhen names a boolean configuration dependency. Optional visibleWhen {field,value} shows a field only for the matching configured value; PAAY uses this for its custom second-authentication amount. |
| `catalog[].exclusiveGroup` | string\|null | '3ds' for the four 3DS providers: enabling one switches the others off. |
| `catalog[].docsUrl` | string\|null | Provider documentation link. |
| `catalog[].webhookUrl` | string\|null | Alerts category only: the URL the provider must POST alerts to - <API_PUBLIC_URL>/v1/alerts/<key>/<URL-encoded account email>. null for every other category. |
| `items` | array | The account's state, one entry per catalog entry, SAME ORDER (items[i].key === catalog[i].key). |
| `items[].enabled` | boolean | The on/off switch. For exify / platformpay mirrored from their own settings tables. |
| `items[].configured` | boolean | Every required field is set (a secret counts when saved). exify: settings row + a v2 target; platformpay: url and user_id set; email_providers / sms_providers: >=1 provider of the channel with its credential saved. |
| `items[].config` | object | Non-secret settings (catalog defaults merged under the saved values). exify adds send_pct / duplicate_inhouse / test_mode / targets[{version,url}]; platformpay adds url / user_id / send_pct / hasSecret / stats{sent_24h,ok_24h,failed_24h}; messaging pools add providers (count). |
| `items[].secretsSet` | object | field name -> boolean: whether that secret is saved. Secret VALUES are never in this list - GET /v1/integrations/:key/secrets (v3.9.8 item 7). |
| `items[].updatedAt` | string (ISO-8601)\|null | Last save of the account_integrations row; null when the account never saved it (defaults shown). |
| `items[].updatedBy` | string\|null | Login of the operator who last saved it (the account e-mail for an API key call). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- items and catalog are index-aligned; match on `key` anyway - it is the join key the dashboard uses.
- Secret values never leave the API: only secretsSet.<field> booleans. A secrets blob encrypted under another CREDENTIAL_ENC_KEY reads as "all unset" instead of erroring.
- exify / platformpay carry their state from expify_settings / platformpay_settings, not from account_integrations - their updatedAt/updatedBy stay null here and their `config` keys (send_pct, url, user_id, stats...) are read-only mirrors; edit them through their own settings routes.
- An account with no platformpay_settings row shows platformpay.configured:false; the exify / platformpay / messaging lookups are best-effort (a failing lookup leaves the plain registry state rather than failing the request).
- defaultEnabled entries (recovery_templates, smart_product_matching) report enabled:true with updatedAt:null - "on" without any row.
- config of an untouched integration already contains the catalog defaults of its non-secret fields (e.g. every 3DS policy toggle), so do not treat a non-empty config as "the operator saved something" - use updatedAt.
- webhookUrl is built from API_PUBLIC_URL when set, else the request protocol://host - behind a proxy without API_PUBLIC_URL it can point at an internal host.
- The response is large (every field definition for ~20 integrations). It carries no paging; call it once and cache client-side.
- v3.9.8 item 7 - the secret values are never in this list (secretsSet booleans only): GET /v1/integrations/:key/secrets returns them in clear to a caller that may configure the integration.
- google_ads is configured through PUT /v1/integrations/google_ads but is not part of this list (catalog and items both omit it).

##### `GET /v1/integrations/3ds/metrics`

**Scope** `integrations.read` - **Get 3DS analytics for a date range**

Aggregates the account's straight card charges of a date range by 3DS involvement: how many carried a cryptogram (applied), how many ran 3DS without a usable result (attempted), the no-3DS baseline (none, incl. the A/B holdout arm and excluded networks), approval counts of each bucket, flows (frictionless / challenge / attempt / data-only), non-applied outcomes, liability shifts, provider fees, per-provider breakdown and the session count by status. `provider` narrows the 3DS buckets to one integration (its Analytics view). v3.9.13 - `side` (straight | subscription | all) moves the population and the fee tile with the dashboard's Straight - Subscription - Both tab. Absent = the straight population as before (Integrations -> Analytics).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 with Z); default `today 00:00 UTC` | no | Start of the metrics window, inclusive. The metrics window itself is read only from an ISO datetime with Z (for example 2026-11-01T00:00:00Z): a bare day or an offset passes the filter validation but makes the window fall back to today (00:00 UTC to now). |
| `to` | string (ISO 8601 with Z); default `now` | no | End of the metrics window, inclusive. The metrics window itself is read only from an ISO datetime with Z (for example 2026-11-01T00:00:00Z): a bare day or an offset passes the filter validation but makes the window fall back to today (00:00 UTC to now). |
| `provider` | string | no | Restrict the applied / attempted / flows / outcomes / fees / sessions buckets to this provider. The `none` baseline stays account-wide. Non-3DS keys are ignored. Max 100 characters (longer is a 400). |
| `side` | enum: straight \| subscription \| friendlies \| all | no | straight, subscription, friendlies or all. Omitted keeps the straight card population while the fee totals include all card sources. straight/subscription restrict both the population and fee totals to that side; all includes both. PAAY subscription charges can apply saved proofs without a new authentication. Other providers keep their own rebill policy. Wallets and Friendlies are excluded. |
| `tz` | string | no | Date filter: IANA timezone the days and hours are read in. Max 64 characters. |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: Store host bucket, (direct). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "range": {
    "from": "2026-09-01T00:00:00.000Z",
    "to": "2026-09-19T12:44:10.221Z"
  },
  "metrics": {
    "charges": 1820,
    "approved": 1311,
    "applied": {
      "charges": 940,
      "approved": 720
    },
    "attempted": {
      "charges": 60,
      "approved": 31
    },
    "none": {
      "charges": 820,
      "approved": 560
    },
    "holdout": {
      "charges": 200,
      "approved": 141
    },
    "excluded": {
      "charges": 95,
      "approved": 66
    },
    "retryWithoutThreeDs": {
      "attempts": 12,
      "approved": 5
    },
    "flows": [
      {
        "flow": "frictionless",
        "charges": 900,
        "approved": 695
      },
      {
        "flow": "challenge",
        "charges": 40,
        "approved": 25
      }
    ],
    "outcomes": [
      {
        "status": "U",
        "charges": 35
      },
      {
        "status": "N",
        "charges": 15
      },
      {
        "status": "pending",
        "charges": 10
      }
    ],
    "liabilityShift": 905,
    "feeCents": 5000,
    "byProvider": [
      {
        "provider": "paay_3ds",
        "charges": 1000,
        "applied": 940,
        "approved": 751,
        "appliedApproved": 720
      }
    ],
    "sessions": {
      "total": 1050,
      "byStatus": [
        {
          "status": "consumed",
          "count": 900
        },
        {
          "status": "authenticated",
          "count": 60
        },
        {
          "status": "unavailable",
          "count": 50
        },
        {
          "status": "expired",
          "count": 40
        }
      ]
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `range` | object | The EFFECTIVE from/to used (defaults applied when a bound was missing or invalid). |
| `metrics.charges` | integer | Completed live card-charge population: approved, declined, error or unknown; excludes pending, duplicates, wallets and Friendlies. Defaults to straight/recovery sales. side=subscription selects rebills, and side=all includes both straight and subscription charges. |
| `metrics.approved` | integer | Approved charges of the population. |
| `metrics.applied` | object | {charges, approved}: charges where a cryptogram travelled to the gateway. |
| `metrics.attempted` | object | {charges, approved, declined}: authentication involvement without a cryptogram applied. Includes failed/unavailable, pending, late and reserved outcomes as appropriate; no_token belongs to the no-3DS baseline. |
| `metrics.none` | object | {charges, approved, declined}: no 3DS applied or attempted for this payment, including no provider, holdout, excluded network, no_3ds rule and no_token rebills. |
| `metrics.holdout` | object | The A/B arm: charges the policy deliberately charged without 3DS (inlineSharePct < 100). Subset of none. |
| `metrics.excluded` | object | Charges whose card network is switched off in the policy. Subset of none. |
| `metrics.retryWithoutThreeDs` | object | {attempts, approved}: same-MID retries without 3DS data after a decline with it (policy retryWithoutThreeDs). |
| `metrics.flows` | array | Applied charges by flow (frictionless \| challenge \| attempt \| data-only) with approvals. |
| `metrics.outcomes` | array | Not-applied charges by three_ds_status (EMV N/U/R, 'skipped', 'pending', 'fallback'...). |
| `metrics.liabilityShift` | integer | Applied charges carrying a liability shift. |
| `metrics.feeCents` | integer | Live provider fees in cents: recorded authentication count multiplied by the integration current attemptFeeUsd, with the legacy single-attempt fallback on older rows. The count normally is 2 for a pair and 0 for a later stored-proof rebill. Follows side for the fee population; absent/all includes every source. |
| `metrics.byProvider` | array | {provider, charges, applied, approved, appliedApproved} per 3DS provider that ran. |
| `metrics.sessions` | object | {total, byStatus[{status,count}]}: three_ds_sessions of the account created in the range (incl. explicit sessions never charged). |
| `metrics.notRun` | { charges, approved, declined } | v3.9.9 - none - holdout - excluded, counted on the list's threeDs=not-run predicate. |
| `metrics.feeCharges` | number | Number of recorded billable authentication attempts behind feeCents, not number of transactions: a double-authentication checkout normally contributes 2, a stored-proof rebill 0, and legacy rows retain their single-attempt fallback. Follows side like feeCents. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} for an unknown query parameter or an invalid filter value.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Strict query: every key of the unified filter catalog is accepted (listed in params); an unknown parameter is a 400.
- A malformed from/to never 400s: the whole range silently falls back to today-UTC -> now. Always check the echoed `range`.
- Datetimes must end with 'Z'; '+02:00' style offsets fail validation (-> defaults).
- holdout and excluded are included in `none`; do not add them again.
- Range bounds are inclusive (>= from and <= to) on transactions.created_at / sessions.created_at.
- Friendlies are excluded from ordinary approval rates, gross/net figures and Pilot ROAS. Both covers Straight and Subscription. Friendlies are shown through their own metrics and columns.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/integrations/3ds/sessions`

**Scope** `integrations.read` - **List recent 3DS sessions**

Diagnostics for the 3DS integrations: the account's most recent 3-D Secure sessions (explicit /v1/3ds sessions and inline ones started by /v1/charge), newest first, optionally narrowed to one 3DS provider. Each row is the full session minus the cryptogram (cavv) and the encrypted provider state.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | 1..10000, clamped (no 400). A non-numeric value falls back to 50. |
| `provider` | enum: evervault_3ds\|paay_3ds\|threedsecureio_3ds\|vgs_3ds | no | Narrow to one 3DS integration. Any value that is not a 3DS catalog key is silently ignored (all providers). |

**Response**

```json
{
  "sessions": [
    {
      "id": "a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91",
      "owner_email": "merchant@example.com",
      "api_key_id": "2b7d1a3e-9f40-4c6b-8e12-0a5d3c9b7f21",
      "provider": "paay_3ds",
      "provider_ref": "ae2c1f9a-…",
      "order_id": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
      "amount_cents": "4999",
      "currency": "USD",
      "masked_card": "411111******1111",
      "status": "consumed",
      "trans_status": "Y",
      "version": "2.2.0",
      "eci": "05",
      "ds_trans_id": "f38c7b1e-…",
      "acs_trans_id": "9d1e2a4b-…",
      "three_ds_server_trans_id": "c4a1e2d3-…",
      "liability_shift": true,
      "reason": null,
      "flow": "frictionless",
      "next_action": null,
      "raw": {
        "transStatus": "Y",
        "authenticationValue": "[redacted]"
      },
      "callback_payload": null,
      "consumed_by": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "created_at": "2026-09-19T11:02:40.018Z",
      "updated_at": "2026-09-19T11:02:41.902Z",
      "expires_at": "2026-09-19T12:02:40.018Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `sessions` | array | three_ds_sessions rows of the account, newest first, without state_enc and cavv. |
| `sessions[].status` | enum: pending\|method\|challenge\|authenticated\|attempted\|informational\|failed\|unavailable\|expired\|consumed | Lifecycle state. authenticated/attempted/informational = usable by a charge; consumed = used by transaction consumed_by. |
| `sessions[].trans_status` | string\|null | EMV transStatus of the final outcome: Y authenticated, A attempted, N denied, U unavailable, R rejected, C challenge, I informational. |
| `sessions[].flow` | string\|null | frictionless \| challenge \| attempt \| data-only - how the outcome was obtained. |
| `sessions[].next_action` | object\|null | Pending browser step ({type: method\|challenge\|sdk, ...}) while the session waits on the checkout. |
| `sessions[].raw` | object\|null | Last provider payload with secrets stripped (diagnostics). |
| `sessions[].callback_payload` | object\|null | What the ACS / hosted page posted back to /v1/3ds/callback/... (cres, methodCompleted, challengeReturned...). |
| `sessions[].amount_cents` | string | Integer cents, but returned as a STRING (Postgres bigint) - coerce with Number(). |
| `sessions[].expires_at` | string (ISO-8601) | created_at + 1 hour; a session past it flips to expired on its next read. |
| `sessions[].amount_cents / currency` | integer + string | Amount in minor units and currency actually sent to the authentication provider. This is not necessarily the amount of the later subscription payment. |
| `sessions[].intended_rebill_amount_cents / intended_rebill_currency` | integer + string \| null | Separate future-payment amount in minor units and currency, present on newly created PAAY second slots. Legacy null values retain the authentication amount/currency binding. Consumption uses the intended amount and still requires matching currencies. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- cavv (the cryptogram) and state_enc are never returned; eci / ds_trans_id / acs_trans_id are.
- amount_cents is a string here (bigint column) whereas most of the API returns integers.
- raw can be several KB per row; keep limit small for a dashboard poll.
- No date filter and no paging (limit only): use GET /v1/integrations/3ds/metrics for aggregates.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.
- Only limit and provider are read; any other query parameter is ignored.

##### `PUT /v1/integrations/:key`

**Scope** `integrations.write` - **Save an integration (enable, config, secrets)**

Upserts the calling account's row for one integration: the on/off switch, the non-secret config (merged over what is stored) and the secrets (encrypted together as one AES-GCM blob; read back only through GET /v1/integrations/:key/secrets - v3.9.8 item 7). Enabling a member of an exclusive group (a 3DS provider) switches its siblings off in the same transaction. For exify / platformpay the `enabled` flag is also written to their dedicated settings tables. Returns the public state of the saved item, plus a warning when it was enabled while a required field is still missing. Friendlies accepts config.unitCosts as an object mapping owned API key UUIDs to integer USD cents (0..100000000). For example {"enabled":true,"config":{"unitCosts":{"00000000-0000-4000-8000-000000000001":125}}}. At least one explicit tariff, including zero, makes it configured. Unmapped attempts show N/A. Costs apply once per recorded transaction, approved or declined, never per MID cascade or idempotent replay. Rates are current, so changes reprice reporting periods and invalidate cached/in-flight account reports. Disabled by default; disabled or incomplete prevents new fl:true charges and hides Friendlies UI. Foreign keys return 403 and invalid costs 400. Pilot accepts up to 20 distinct API keys in the existing secrets.apiKey string, separated by newlines; legacy single-key values remain valid. Saving an enabled, configured Pilot integration queues a durable history backfill over its configured window, including closed days, and returns sync:{jobId,status}. If queue admission fails, settings remain saved and a retryable warning is returned.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | enum: friendlies \| exify \| platformpay \| xcaliber \| rcvr \| evervault_3ds \| paay_3ds \| threedsecureio_3ds \| vgs_3ds \| evervault_tokenization \| thesupportcare \| email_providers \| sms_providers \| recovery_templates \| openai \| anthropic \| fal \| higgsfield \| namecheap \| cloudflare \| pilot \| google_ads \| smart_product_matching | **yes** | Catalog key. Anything else answers 404 {"error":"Unknown integration"}; evervault_tokenization is coming soon (409). exify, platformpay, friendlies, email_providers, sms_providers, recovery_templates and smart_product_matching have no catalog field: only enabled (and, for friendlies, config.unitCosts) is meaningful. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean; default `stored value` | no | Switch. Omitted = keep the stored value (or the catalog defaultEnabled when no row exists yet). |
| `config` | object; default `{}` | no | Non-secret catalog settings, shallow-merged with stored config; unknown fields are discarded. PAAY validates booleans, holding days and second-authentication amount settings before saving. The merged PAAY configuration is validated while holding its database row lock, so custom mode cannot be saved without a valid custom amount. Invalid values return 400 and preserve stored settings. Every accepted field is listed below as config.<field> with the integrations that accept it; a field another integration owns is discarded. |
| `secrets` | object; default `{}` | no | Secret fields, key -> string (max 4096 chars) or null. A string overwrites, null or '' CLEARS that secret, an absent key keeps the stored one. Only catalog secret fields are kept; others are dropped. Pilot secrets.apiKey is the complete key list: at most 20 distinct tokens and 4096 characters total. Whitespace, comma and semicolon separators are accepted; exact duplicates are removed and the encrypted value is normalized to one token per line. Omission preserves the saved list; a supplied string replaces the entire list, while null or an empty string clears it. Every accepted secret is listed below as secrets.<field>. |
| `secrets.apiKey` | string | no | The provider API key of the integration being saved (for XCaliber: the XProtect API key). Accepted by: xcaliber, rcvr, evervault_3ds, paay_3ds, threedsecureio_3ds, thesupportcare, openai, anthropic, fal, higgsfield, namecheap, pilot. Required for the integration to be configured (active) on: evervault_3ds, paay_3ds, threedsecureio_3ds, thesupportcare, openai, anthropic, fal, higgsfield, namecheap, pilot. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `secrets.webhookSecret` | string | no | Webhook secret. Sent by XCaliber with each alert (header X-Webhook-Secret or ?token=). Alerts without it are rejected. Accepted by: xcaliber, rcvr. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `config.autoRefund` | boolean | no | Auto-refund on alert. Refund the matched transaction as soon as an alert arrives (blacklists the customer). Off = alerts are only recorded. Accepted by: xcaliber, rcvr. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.appId` | string | no | App ID. Evervault Dashboard -> App. Accepted by: evervault_3ds. Required for the integration to be configured (active) on: evervault_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.teamId` | string | no | Team ID. Evervault Dashboard -> Settings. Needed by the browser SDK / hosted page. Accepted by: evervault_3ds. Required for the integration to be configured (active) on: evervault_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.merchantName` | string | no | Merchant name. Shown to the cardholder by some issuers. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: evervault_3ds "Online Store"; threedsecureio_3ds "Online Store"; vgs_3ds "Online Store". Required for the integration to be configured (active) on: evervault_3ds, threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.merchantWebsite` | string (URL) | no | Merchant website. Accepted by: evervault_3ds. Catalog default: "https://kontrolcheckout.com". Required for the integration to be configured (active) on: evervault_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.merchantMcc` | string | no | MCC. Accepted by: evervault_3ds. Catalog default: "5999". Required for the integration to be configured (active) on: evervault_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.merchantCountry` | string | no | Merchant country. Accepted by: evervault_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: "US". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.acquirerBin` | string | no | Acquirer BIN. Production only: fill BIN + merchant ID here, or configure default acquirers in the Evervault dashboard. Accepted by: evervault_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: threedsecureio_3ds "438309"; vgs_3ds "438309". Required for the integration to be configured (active) on: threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.acquirerMerchantId` | string | no | Acquirer merchant ID. Accepted by: evervault_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: threedsecureio_3ds "00002000000"; vgs_3ds "00002000000". Required for the integration to be configured (active) on: threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.acquirerCountry` | string | no | Acquirer country. Accepted by: evervault_3ds, vgs_3ds. Catalog default: "US". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightThreeDsMode` | enum: inherit \| off \| single \| double | no | inherit \| off \| single \| double (PAAY only). Overrides the initial sale authentication count. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.straightChallengePreference` | enum: inherit \| no-preference \| no-challenge \| challenge-requested \| challenge-mandated | no | inherit \| no-preference \| no-challenge \| challenge-requested \| challenge-mandated. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.straightOnChallenge` | enum: inherit \| return \| skip \| decline | no | inherit \| return \| skip \| decline. A mandatory-authentication rule cannot be bypassed by skip. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.straightRequireLiabilityShift` | enum: inherit \| yes \| no | no | inherit \| yes \| no. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.postSellThreeDsMode` | enum: inherit \| off \| single \| double | no | inherit \| off \| single \| double (PAAY only). PAAY defaults to double. Both requests authenticate the accepted post-sell amount. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.postSellChallengePreference` | enum: inherit \| no-preference \| no-challenge \| challenge-requested \| challenge-mandated | no | inherit \| no-preference \| no-challenge \| challenge-requested \| challenge-mandated. PAAY defaults to no-challenge; the issuer may still require a challenge. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.postSellOnChallenge` | enum: inherit \| return \| skip \| decline | no | inherit \| return \| skip \| decline. PAAY defaults to return so the buyer can complete an issuer challenge. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.postSellRequireLiabilityShift` | enum: inherit \| yes \| no | no | inherit \| yes \| no. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.rebillThreeDsMode` | enum: inherit \| off \| stored | no | inherit \| off \| stored (PAAY only). Unattended collection cannot perform a fresh browser challenge. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.rebillRequireLiabilityShift` | enum: inherit \| yes \| no | no | inherit \| yes \| no. Required authentication must use compatible unused saved proof. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. |
| `config.challengePreference` | enum: no-preference \| no-challenge \| challenge-requested \| challenge-mandated | no | Challenge preference. EMV threeDSRequestorChallengeInd. The issuer always has the final say. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: "no-preference". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.onChallenge` | enum: skip \| return \| decline | no | If a browser step is required. Inline charges only. "Return" parks the order until the checkout completes the step and re-submits with threeDsSessionId. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: "skip". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.inline` | boolean | no | Inline authentication on /v1/charge. Evervault decides every outcome in the browser (SDK), so an inline charge is parked until the checkout completes it. Prefer the explicit /v1/3ds flow. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: true. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.inlineMethodWait` | boolean | no | Continue without device fingerprint. On: when the issuer asks for the 3DS Method, wait its timeout (~10 s) and continue so the authentication reaches the issuer. Off: treated like a browser step. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.requireLiabilityShift` | boolean | no | Decline when authentication fails. On: a failed / unavailable authentication (N, U, R) declines the order. Off: charged without 3DS data. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.retryWithoutThreeDs` | boolean | no | On decline, retry once without 3DS. A charge sent WITH the cryptogram that the gateway declines is re-sent once to the same MID without any 3DS data; if that fails too, the cascade continues with the 3DS data. Not on timeouts, credential or float errors. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.brandVisa` | boolean | no | Visa. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: true. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.brandMastercard` | boolean | no | Mastercard. Off until the provider is configured for Mastercard (PAAY: "acquirerBIN not recognized"). Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.brandAmex` | boolean | no | American Express. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: true. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.brandDiscover` | boolean | no | Discover. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: true. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.onRebills` | boolean | no | Authenticate rebills. Start a new authentication during the rebill. A scheduled charge has no live browser to complete a challenge. Stored PAAY authentications are configured separately. Accepted by: evervault_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.inlineSharePct` | number | no | Share of charges authenticated (%). A/B: below 100, the rest is charged without 3DS (stamped "holdout") so the dashboard compares AR with vs without 3DS on the same traffic. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: 100. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.attemptFeeUsd` | number | no | Cost per attempt (USD). Billed by the provider per authentication request, applied or not. Shown as "3DS fees" in finance, transactions and reports. Accepted by: evervault_3ds, paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: 0. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.pendingTimeoutSeconds` | integer; default `45` | no | PAAY only. Maximum wait for optional silent authentication of the current purchase, integer 5-120, default 45 seconds from primary session creation. Retries do not restart the budget. Optional secondary work proceeds separately and cannot delay the sale. Mandatory authentication, actual issuer challenges, negative outcomes, unknown bank results and payment idempotency retain their controls. Accepted by: paay_3ds. |
| `secrets.apiSecret` | string | no | API secret. Signs the per-request JWT ("Pass in JWT" must be ON for the key). Same key pair for both environments. Accepted by: paay_3ds, higgsfield. Required for the integration to be configured (active) on: paay_3ds, higgsfield. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `config.environment` | enum: sandbox \| production | no | Environment. Accepted by: paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: "sandbox". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.merchantUrl` | string (URL) | no | Merchant website. Sent as Referer / threeDSRequestorURL. Accepted by: paay_3ds, threedsecureio_3ds, vgs_3ds. Catalog default: "https://kontrolcheckout.com". Required for the integration to be configured (active) on: paay_3ds, threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.requestorName` | string | no | 3DS Requestor name. Accepted by: paay_3ds, threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightInline` | boolean | no | Inline authentication on /v1/charge. Authenticate server-side before routing when the order carries no 3DS data. Off = explicit /v1/3ds sessions only. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightInlineSharePct` | number | no | Share of charges authenticated (%). Accepted by: paay_3ds. Bounds: paay_3ds 0..100. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightInlineMethodWait` | boolean | no | Continue without device fingerprint. On: when the issuer asks for the 3DS Method, wait its timeout (~10 s) and continue so the authentication reaches the issuer. Off: treated like a browser step. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightRetryWithoutThreeDs` | boolean | no | On decline, retry once without 3DS. A charge sent WITH the cryptogram that the gateway declines is re-sent once to the same MID without any 3DS data; if that fails too, the cascade continues with the 3DS data. Not on timeouts, credential or float errors. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightBrandVisa` | boolean | no | Visa. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightBrandMastercard` | boolean | no | Mastercard. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightBrandAmex` | boolean | no | American Express. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.straightBrandDiscover` | boolean | no | Discover. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellInline` | boolean | no | Inline authentication on /v1/charge. Authenticate server-side before routing when the order carries no 3DS data. Off = explicit /v1/3ds sessions only. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellInlineSharePct` | number | no | Share of charges authenticated (%). Accepted by: paay_3ds. Bounds: paay_3ds 0..100. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellBrandVisa` | boolean | no | Visa. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellBrandMastercard` | boolean | no | Mastercard. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellBrandAmex` | boolean | no | American Express. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.postSellBrandDiscover` | boolean | no | Discover. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.rebillRetryWithoutThreeDs` | boolean | no | On decline, retry once without 3DS. A charge sent WITH the cryptogram that the gateway declines is re-sent once to the same MID without any 3DS data; if that fails too, the cascade continues with the 3DS data. Not on timeouts, credential or float errors. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.rebillBrandVisa` | boolean | no | Visa. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.rebillBrandMastercard` | boolean | no | Mastercard. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.rebillBrandAmex` | boolean | no | American Express. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.rebillBrandDiscover` | boolean | no | Discover. Accepted by: paay_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.doubleRebillAuthentication` | boolean; default `false` | no | PAAY only, default false. Start two independent checkout authentications. Disabling stops new pairs while compatible existing stock remains usable when PAAY is active. Accepted by: paay_3ds. |
| `config.secondThreeDsAmountMode` | enum: same_as_original\|subscription_product\|custom; default `subscription_product` | no | PAAY only. Controls the second authentication amount; active only with double authentication. same_as_original copies the final straight amount/currency, subscription_product uses the next subscription plan amount/currency, custom uses secondThreeDsCustomAmount in the original purchase currency. Does not change the actual future debit or existing proofs. Accepted by: paay_3ds. |
| `config.secondThreeDsCustomAmount` | number | no | Positive finite amount in MAJOR units, from 0.01 through 21474836.47, with at most two decimals. Required in the merged configuration when secondThreeDsAmountMode is custom. String values, sub-cent precision and out-of-range amounts are rejected. Stored custom values remain available when switching to another mode. Accepted by: paay_3ds. |
| `config.optimizeThreeDsTokens` | boolean; default `false` | no | PAAY only, default false. Once both authentication results are terminal, reserve a sole usable proof for a matching rebill and send an optional straight sale without 3DS. While the sibling is still pending, use a usable primary for the current sale immediately. Mandatory authentication always takes precedence; allocation cannot be changed after dispatch. Accepted by: paay_3ds. |
| `config.rebillTokenValidityDays` | integer; default `90` | no | PAAY local maximum holding period, 1-90 days from authentication request creation. Default 90. Does not promise issuer, network or processor validity for that duration. Accepted by: paay_3ds. |
| `config.mcc` | string | no | MCC. Accepted by: threedsecureio_3ds, vgs_3ds. Catalog default: "5999". Required for the integration to be configured (active) on: threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.requestorId` | string | no | 3DS Requestor ID. Assigned by the scheme / DS (production, optional). Accepted by: threedsecureio_3ds, vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.clientId` | string | no | Service account client ID. Scopes cards:read, cards:write, 3ds:read, 3ds:write. Accepted by: vgs_3ds. Required for the integration to be configured (active) on: vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `secrets.clientSecret` | string | no | Service account client secret. Accepted by: vgs_3ds, google_ads. Required for the integration to be configured (active) on: vgs_3ds, google_ads. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `config.vaultId` | string | no | Vault ID. Accepted by: vgs_3ds. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.accountId` | string | no | Account id. Sent as X-Account-Id with every order. Accepted by: thesupportcare, cloudflare. Required for the integration to be configured (active) on: thesupportcare. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.apiUrl` | string (URL) | no | API URL. createOrder endpoint. Leave the default unless TheSupportCare gives you another. Accepted by: thesupportcare. Catalog default: "https://tracking.getsupportcare.com/api/createOrder". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.organizationId` | string | no | Organization ID. Accepted by: openai. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.model` | enum: gpt-6-astra \| gpt-5.6-sol \| gpt-5.6-terra \| gpt-5.6-luna \| claude-fable-5-1 \| claude-opus-5 \| claude-sonnet-5 \| claude-haiku-4-5 | no | Default model. Accepted by: openai, anthropic, fal, higgsfield. Catalog default: openai "gpt-5.6-terra"; anthropic "claude-sonnet-5"; fal "fal-ai/flux/dev". Options per integration: openai gpt-6-astra\|gpt-5.6-sol\|gpt-5.6-terra\|gpt-5.6-luna; anthropic claude-fable-5-1\|claude-opus-5\|claude-sonnet-5\|claude-haiku-4-5; fal ; higgsfield . Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.baseUrl` | string (URL) | no | Base URL. Accepted by: openai, anthropic, higgsfield, pilot. Catalog default: openai "https://api.openai.com/v1"; anthropic "https://api.anthropic.com"; higgsfield "https://platform.higgsfield.ai"; pilot "https://pilot.ad". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.anthropicVersion` | string | no | anthropic-version header. Accepted by: anthropic. Catalog default: "2023-06-01". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.queueUrl` | string (URL) | no | Queue base URL. Accepted by: fal. Catalog default: "https://queue.fal.run". Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.apiUser` | string | no | API user. Accepted by: namecheap. Required for the integration to be configured (active) on: namecheap. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.username` | string | no | Username. Accepted by: namecheap. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.clientIp` | string | no | Client IP. Accepted by: namecheap. Required for the integration to be configured (active) on: namecheap. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.sandbox` | boolean | no | Sandbox. Accepted by: namecheap. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `secrets.apiToken` | string | no | API token. Accepted by: cloudflare. Required for the integration to be configured (active) on: cloudflare. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `config.backfillDays` | number | no | Backfill (days, max 92). Accepted by: pilot. Catalog default: 92. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.preCloseRefresh` | boolean | no | Refresh the Live Report before local midnight. Accepted by: pilot. Catalog default: true. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `secrets.developerToken` | string | no | Developer token. Accepted by: google_ads. Required for the integration to be configured (active) on: google_ads. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `secrets.clientId` | string | no | OAuth client ID. Accepted by: google_ads. Required for the integration to be configured (active) on: google_ads. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `secrets.refreshToken` | string | no | Refresh token. Accepted by: google_ads. Required for the integration to be configured (active) on: google_ads. Max 4096 characters; null or "" clears it; omitted keeps the stored value. Never returned by reads (only secretsSet), except GET /v1/integrations/:key/secrets. |
| `config.loginCustomerId` | string | no | Manager account ID. Accepted by: google_ads. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.validateOnly` | boolean | no | Validate only. Accepted by: google_ads. Catalog default: false. Stored as sent (shallow merge over the stored config); only the 3DS, PAAY and Friendlies settings are type-checked. |
| `config.unitCosts` | object; default `{}` | no | friendlies only: the USD cost per Friendlies transaction, per API key of the account: {"<apiKeyId>": <integer cents>}. Strict: any other config field on friendlies answers 400 "Invalid Friendlies costs". Friendlies stays inactive until at least one key has a cost. Saving it invalidates the account's cached report jobs. |
| `config.unitCosts.<apiKeyId>` | integer | no | Cost in USD cents, 0 to 100000000, for one API key id (uuid). Every id must be a key of the caller's account (else 403 "Costs may only be configured for your own API keys"). |
| `config.rebillChallengePreference` | never | no | 3DS integrations: refused (400 "Invalid 3DS settings for this payment type"): a scheduled rebill has no live browser to run a challenge. |
| `config.rebillOnChallenge` | never | no | 3DS integrations: refused (400 "Invalid 3DS settings for this payment type"), for the same reason. |

**Request body**

```json
{
  "enabled": true,
  "config": {
    "environment": "production",
    "merchantUrl": "https://shop.example.com",
    "onChallenge": "skip",
    "inline": true,
    "brandMastercard": false,
    "attemptFeeUsd": 0.05
  },
  "secrets": {
    "apiKey": "example-paay-api-key",
    "apiSecret": "example-paay-api-secret"
  }
}
```

**Response**

```json
{
  "item": {
    "key": "paay_3ds",
    "enabled": true,
    "configured": true,
    "config": {
      "environment": "production",
      "merchantUrl": "https://shop.example.com",
      "challengePreference": "no-preference",
      "onChallenge": "skip",
      "inline": true,
      "inlineMethodWait": false,
      "requireLiabilityShift": false,
      "retryWithoutThreeDs": false,
      "brandVisa": true,
      "brandMastercard": false,
      "brandAmex": true,
      "brandDiscover": true,
      "onRebills": false,
      "inlineSharePct": 100,
      "attemptFeeUsd": 0.05
    },
    "secretsSet": {
      "apiKey": true,
      "apiSecret": true
    },
    "updatedAt": "2026-09-19T12:40:11.902Z",
    "updatedBy": "ops@example.com"
  }
}
```

| response field | type | description |
|---|---|---|
| `item` | object | The saved integration in the same shape as items[] of GET /v1/integrations (key, enabled, configured, config, secretsSet, updatedAt, updatedBy). Re-read from the database after the write. |
| `item.configured` | boolean | Whether every required field is now set. When false while enabled, the integration is INACTIVE on the charge path. |
| `warning` | string | Optional non-fatal warning; settings were saved. Missing required configuration warns that the integration is inactive. Pilot queue admission failure returns "Pilot settings saved. Automatic synchronization could not start. Save again to retry." and does not roll back the saved configuration. Repeat the same PUT to retry the full configured history refresh. Inspect item.configured rather than inferring inactivity from any warning. |
| `sync` | object | Pilot only, when enabled/configured settings were saved and automatic history sync was admitted: {jobId:string,status:string}. The durable job merges all connected profiles across the configured history window, including closed days. Absent when inactive, incomplete or queue admission failed; the latter returns warning. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} for a malformed body (enabled not boolean, config or secrets not an object, a secret over 4096 characters); {"error":"Invalid 3DS settings for this payment type","details":...} for an invalid 3DS context value; {"error":"Invalid PAAY authentication settings" | "3DS timeout must be a whole number of seconds between 5 and 120." | "Custom second 3DS amount requires a positive amount with at most 2 decimals, up to 21,474,836.47.","details":...} for PAAY; {"error":"Invalid Friendlies costs","details":...}; {"error":"Pilot API keys must be text" | "Pilot API keys exceed the 4096-character limit" | "Add at most 20 Pilot API keys" | "One or more Pilot API keys have an invalid format","code":"invalid_pilot_keys"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account. {"error":"Costs may only be configured for your own API keys"} when a friendlies unitCosts key is not one of the account's keys.
- `404` {"error":"Unknown integration"}.
- `409` {"error":"<Name> is coming soon and cannot be configured yet"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Enabling a 3DS provider (exclusiveGroup "3ds") switches every OTHER enabled 3DS provider of the account off in the same transaction; the response only shows the one you saved - re-fetch GET /v1/integrations to see the siblings.
- config is a shallow MERGE, secrets are per-key: to unset a config value you must send it explicitly (e.g. ""); to clear a secret send null or "". Sending {} changes nothing but still bumps updatedAt/updatedBy.
- Unknown config / secret keys are silently discarded - a typo in a field name is accepted with 200 and stored nowhere. Check item.config / item.secretsSet in the response.
- An incomplete-configuration warning means the integration is inactive; Pilot can also return a synchronization warning after a valid configuration was saved. Test item.configured and inspect sync/warning separately.
- For exify / platformpay only `enabled` is meaningful here (they have no catalog fields); it is mirrored into expify_settings / platformpay_settings. Their config/secrets live on their own routes.
- The audit log records action "update", objectType "integration", page "Integrations" with the body `name` (none here) - objectId is null because :key is not an id.
- The PAAY pair settings have strict value validation; string "true" or fractional/out-of-range holding days are rejected with 400. Other config fields retain their existing catalog and type handling. The legacy onRebills control applies to other providers, not PAAY stored-proof consumption.
- PAAY custom mode requires a valid amount even when double authentication is currently off. A patch may supply mode and amount together, or reuse a valid stored custom amount. Partial patches are merged and validated atomically; an invalid custom value is rejected rather than rounded or substituted.
- 3DS integrations expose separate Straight/Post-sell/Rebill settings. straight/postSell ThreeDsMode supports inherit|off|single and PAAY double; ChallengePreference supports inherit|no-preference|no-challenge|challenge-requested|challenge-mandated; OnChallenge supports inherit|return|skip|decline; RequireLiabilityShift supports inherit|yes|no. Rebill mode accepts inherit|off and PAAY stored only; explicit fresh challenge/double is rejected because unattended collection has no live buyer browser. PAAY post-sell default is double/no-challenge/return. Existing Straight/Rebill behavior stays inherited.
- Pilot list example: {"enabled":true,"secrets":{"apiKey":"pilot_key_example_one\npilot_key_example_two"}}. Keep existing keys in the replacement list when adding another. Ordinary reads expose secretsSet.apiKey only; the existing authorized no-store secrets endpoint is required to edit saved values.
- Pilot reports are deduplicated by profile and advertiser/campaign identity. Every key is checked; profiles must use a common report timezone. A source with no historical snapshot contributes no rows for that date; a failed source request cannot publish a partial merged day. Saving settings schedules a full history refresh and invalidates obsolete queued/running jobs by integration fingerprint.
- updatedBy records the caller: the account e-mail for an API key call.
- Non-PAAY 3DS providers refuse PAAY-only values: pendingTimeoutSeconds, double modes, rebillThreeDsMode stored and the per-context overrides (straightInline, straightBrandVisa...) answer 400 "Invalid 3DS settings for this payment type".

##### `GET /v1/integrations/:key/secrets`

**Scope** `integrations.write` - **Read an integration's stored secrets (in clear)**

Returns the caller account's STORED secrets of one catalog integration, decrypted (only the secret fields that hold a value), to a caller that may edit that integration. Lists and general reads only carry secretsSet booleans.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | enum: friendlies \| exify \| platformpay \| xcaliber \| rcvr \| evervault_3ds \| paay_3ds \| threedsecureio_3ds \| vgs_3ds \| evervault_tokenization \| thesupportcare \| email_providers \| sms_providers \| recovery_templates \| openai \| anthropic \| fal \| higgsfield \| namecheap \| cloudflare \| pilot \| google_ads \| smart_product_matching | **yes** | Catalog key. Unknown answers 404. |

**Response**

```json
{
  "key": "openai",
  "secrets": {
    "apiKey": "example-openai-key"
  }
}
```

| response field | type | description |
|---|---|---|
| `key` | string | The catalog key asked for. |
| `secrets` | object | field name -> stored value, in clear. An unset field is ABSENT (not ""); a blob that no longer decrypts (rotated CREDENTIAL_ENC_KEY) reads as {}. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"}: the key lacks integrations.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `404` {"error":"Unknown integration"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- v3.9.8 item 7 - the answer carries LIVE secrets in clear: it is `Cache-Control: no-store` (+ `Pragma: no-cache`); never log it, never cache it, never echo it into a transcript.
- The lists and general reads never carry these values (only *_set booleans): this route is the only way to read them, and the dashboard calls it when the form opens.
- Clearing is a write: PUT /v1/integrations/:key with secrets.<field> = null (or ""); an absent key keeps the stored value.

##### `POST /v1/integrations/:key/test`

**Scope** `integrations.write` - **Test an integration's credentials**

Runs the provider's cheapest authenticated call to verify the credentials of one integration that carries a check (AI providers openai / anthropic / fal / higgsfield, domains namecheap / cloudflare, media buying pilot - v3.9.3, google_ads - v3.9.18). The check uses what the Configure form holds: config / secrets in the body override the saved ones, so a key can be verified before it is saved and while the integration is switched off. Nothing is persisted. Bounded by ONE 10 s timeout for the whole check (v3.9.3 review: all Pilot key checks share that deadline, with up to four concurrent key checks - users/me, live-report/status, then the best-effort range and tiktok/status reads, which answer null past it); answers {ok, detail} where detail is data only.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `key` | enum: openai\|anthropic\|fal\|higgsfield\|namecheap\|cloudflare\|pilot\|google_ads | **yes** | Any other catalog key (or unknown key) is 404 "No credentials check for this integration". v3.9.3: pilot - GET {baseUrl}/api/users/me (Bearer; the maintenance gate read first) then GET /api/live-report/status (200 = operator scope + Software entitlement), then best effort GET /api/live-report/range (last 7 days -> daysTracked) and GET /api/auth/tiktok/status (needsReauth). v3.9.18: google_ads - an OAuth 2.0 refresh (POST https://oauth2.googleapis.com/token, scope adwords) with the saved / typed client id, client secret and refresh token, then GET /v25/customers:listAccessibleCustomers and a read-only GAQL search of conversion_action on the manager account (loginCustomerId), else the first accessible customer - headers developer-token and login-customer-id. Every Google error is redacted of the credentials. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `config` | object; default `{}` | no | Non-secret settings used for THIS check only (baseUrl, model, organizationId, anthropicVersion, queueUrl, apiUser, username, clientIp, sandbox, accountId...). Layered over: catalog defaults -> saved config -> this body. The accepted config.<field> names and the integrations each belongs to are listed on PUT /v1/integrations/:key. |
| `secrets` | object; default `{}` | no | Secret fields, key -> string (max 4096). Layered over the saved (decrypted) secrets; a blank/whitespace value is IGNORED (falls back to the saved one); keys that are not secret fields of the integration are dropped. Pilot secrets.apiKey replaces the check's full key list: one key per line, up to 20 distinct keys/4096 total characters. Whitespace, commas and semicolons are accepted separators; exact duplicates are removed. A nonblank draft list is checked without saving or combining it with the saved list. The accepted secrets.<field> names and the integrations each belongs to are listed on PUT /v1/integrations/:key. |

**Request body**

```json
{
  "config": {
    "model": "gpt-5.6-terra"
  },
  "secrets": {
    "apiKey": "sk-proj-7hF..."
  }
}
```

**Response**

```json
{
  "ok": true,
  "detail": {
    "models": 42,
    "ms": 318
  }
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Credentials accepted by the provider. |
| `detail` | object | Data only (strings / numbers / booleans / null and provider diagnostic objects), always with `ms` (elapsed). Success: openai / anthropic -> models (count listed); fal -> endpoint (+ unitPrice, unit, currency, or prices:0); higgsfield -> status (200\|404), credentials:'accepted'; namecheap / cloudflare -> provider-specific counts/ids; pilot (v3.9.3) -> { status: 200, softwareEntitled, isAdmin, maintenanceMode, maintenanceAllowed, currency: 'USD' (the Live Report reports floats in currency units without a currency field - USD is assumed and asserted here), liveReport: { running, daysTracked (last 7 days, null when the range read failed), timezone (the Pilot profile tz = the spend days' clock), intervalMinutes, needsReauth (null when the TikTok status read failed) } } - a nested diagnostic object; NEVER the e-mail /users/me answers with. Pilot failures: 401 -> {status:401, error:'UNAUTHENTICATED: ...'}; a gated maintenance key -> ok:false with error 'Pilot is in maintenance mode...' after ONE call; 403 on live-report/status -> {status:403, error:'operator scope or software entitlement missing ...', requestId}. Failure: {status, error} where status 0 = network error / timeout / blocked URL and error is the provider's code+message, 'timeout', 'https required', 'private host' or 'invalid url'; or {missing:'<Field label>'} when a required credential is absent. google_ads (v3.9.18) -> { accessibleCustomers, loginCustomer (10 digits \| null), customer, conversionActions, uploadClickActions (type UPLOAD_CLICKS and enabled: what a store tag can upload to) }; a failure names its step ({ step: 'oauth' \| 'customers' \| 'conversion_actions', status, error }) or the missing field ({ missing: 'OAuth client ID' }). With multiple distinct Pilot keys, detail also contains keysConfigured, keysVerified, profiles (integer counts) and key1, key2, etc. Each numbered object is {verified:boolean,status:number,timezone:string} on success or {verified:false,status:number,error:string} on failure. All keys must verify and share a canonical report timezone for ok:true; duplicate-profile keys are checked separately, but report diagnostics count each profile once. Successful multi-key diagnostics retain currency:"USD", status:200, softwareEntitled and liveReport:{running,daysTracked,timezone,intervalMinutes,needsReauth}. daysTracked is the union of last-seven-day coverage, intervalMinutes is the maximum, needsReauth is true if any profile requires it. Optional diagnostic reads may return null. A single distinct key keeps its original response shape. No API key, profile identity or email is returned. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} - config not an object, a secret not a string or over 4096 chars.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"No credentials check for this integration"} - the key has no verifier (3DS, alerts, exify, thesupportcare... use their own test routes) or is unknown.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` Internal Server Error with a requestId.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- A completed check is ALWAYS 200 - bad credentials show up as ok:false with detail.status (401/403...) and detail.error. Do not key off the HTTP status of this route.
- Works on a disabled or never-saved integration (it reads the account row directly instead of resolveIntegration), and it never saves anything: follow with PUT /v1/integrations/:key.
- SSRF guard: an account-editable base URL must be https to a public host - loopback / RFC1918 / link-local / .local hosts and plain http answer ok:false with detail.error "private host" / "https required" (status 0) without any network call.
- A blank secret in the body is not "clear", it means "use the saved one"; to test a NEW key just send it.
- fal: the probe hits api.fal.ai/v1/models/pricing with config.model as endpoint_id - a 404 means the ENDPOINT ID is unknown, not that the key is bad. higgsfield: 404 on a random request id is the SUCCESS signal (credentials accepted); only 401/403 fail.
- The timeout is 10 s per check; detail.ms tells how long the provider took.
- It is a POST, so the audit log records a mutation ('create', page Integrations) although nothing changes.
- Pilot verifies every distinct key, including multiple keys belonging to one profile, within one shared 10-second budget. A bad key or incompatible report timezone makes the combined check ok:false; a malformed key list also returns ok:false with a safe detail.error. Only schema errors return HTTP 400. This check never queues a history sync; a successful PUT of enabled/configured Pilot settings does.

##### `GET /v1/integrations/alerts`

**Scope** `integrations.read` - **List inbound dispute alerts**

Returns the chargeback / dispute alerts received for the account on its alert webhooks (POST /v1/alerts/xcaliber|rcvr/<account>), newest first: the parsed identifiers, the transaction they were matched to and the action taken (recorded / refunded / refund_failed / already_refunded).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | 1..10000, clamped (no 400); non-numeric -> 50. |

**Response**

```json
{
  "alerts": [
    {
      "id": "5e1c9b2a-0d4f-4a7e-b8c3-2f6a1d9e7b50",
      "provider": "xcaliber",
      "received_at": "2026-09-19T08:12:31.440Z",
      "alert_type": "ethoca",
      "external_id": "ALR-88213",
      "amount_cents": "4999",
      "currency": "USD",
      "card_last4": "1111",
      "gateway_txn_id": "9876543210",
      "order_id": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
      "descriptor": "ACME*STORE 8005551234",
      "transaction_id": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
      "action": "refunded",
      "action_detail": null
    },
    {
      "id": "7a2d0c4e-8b1f-4c3a-9e5d-6f0b2a8c1d73",
      "provider": "rcvr",
      "received_at": "2026-09-18T22:03:10.002Z",
      "alert_type": "rdr",
      "external_id": "RDR-55012",
      "amount_cents": "2999",
      "currency": "USD",
      "card_last4": "4242",
      "gateway_txn_id": null,
      "order_id": null,
      "descriptor": null,
      "transaction_id": null,
      "action": "recorded",
      "action_detail": "no matching transaction"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `alerts` | array | integration_alerts rows of the account, newest first. |
| `alerts[].provider` | enum: xcaliber\|rcvr | Which webhook received it. |
| `alerts[].alert_type` | string\|null | Lower-cased type read from the payload (ethoca, rdr, cdrn, dispute...) or 'unknown'. |
| `alerts[].external_id` | string\|null | Provider's alert / case id. |
| `alerts[].amount_cents` | string\|null | Disputed amount in integer cents (returned as a string - bigint). |
| `alerts[].card_last4` | string\|null | Last 4 digits parsed from the payload. |
| `alerts[].gateway_txn_id` | string\|null | Gateway transaction id from the payload (matched against transactions.order_id_supplier). |
| `alerts[].order_id` | string\|null | Merchant order id from the payload. |
| `alerts[].transaction_id` | uuid\|null | The matched transaction; null when nothing matched. |
| `alerts[].action` | enum: recorded\|refunded\|refund_failed\|already_refunded | What happened: recorded only (no match or autoRefund off), refunded through the refund engine, refund attempted and failed, or the transaction was already refunded. |
| `alerts[].action_detail` | string\|null | 'no matching transaction' when unmatched; the refund error when refund_failed. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- The raw webhook payload and the ARN are stored but NOT returned by this route.
- amount_cents is a string (bigint) - coerce.
- A refund triggered by an alert appears in GET /v1/refunds with requestedBy '<provider> alert' and reason '<provider> <alert_type> alert <external_id>'.
- No filters, no paging beyond limit, no date range.

##### `POST /v1/integrations/creative/jobs`

**Scope** `integrations.write` - **Create an idempotent creative generation job**

Generate media (fal, Higgsfield) or text (OpenAI, Anthropic) with the account's saved provider integration. The job row is saved before the provider is called. Media jobs return 202 queued with a provider handle (poll them); writing runs inside the request and returns 202 completed or failed. Replaying the same requestId with the same body returns the saved job (200) without calling the provider again. Results are not attached or published anywhere.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | **yes** | Idempotency key, unique per account. Same id + identical body = replay (200, no new provider call); same id + different body = 409. |
| `provider` | enum: fal\|higgsfield\|openai\|anthropic | **yes** | Provider whose account integration (API key; Higgsfield also its secret) is used. |
| `model` | string | no | Provider model id, 1..200 characters matching ^[a-zA-Z0-9_-]+([/.][a-zA-Z0-9_-]+)*$. Omitted: the integration's saved model; when there is none either, 400. |
| `input` | object | **yes** | Provider input. Media providers: passed through as the model's input schema. Writing providers accept only prompt, system and maxTokens (below). |
| `input.prompt` | string | no | Writing (openai, anthropic): required, non-blank, at most 30000 characters. |
| `input.system` | string | no | Writing: optional system instructions, at most 10000 characters. |
| `input.maxTokens` | integer; default `2000` | no | Writing: output token cap, OpenAI 16..8000, Anthropic 1..8000. |

**Request body**

```json
{
  "requestId": "00000000-0000-4000-8000-000000000002",
  "provider": "openai",
  "model": "example-model",
  "input": {
    "prompt": "Write a two-sentence product description for an example water bottle.",
    "maxTokens": 300
  }
}
```

**Response** `202`

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "provider": "fal",
    "model": "YOUR_VERIFIED_MODEL_ID",
    "status": "queued",
    "provider_id": "provider-request-id",
    "result": null,
    "error": null,
    "created_at": "2026-10-18T12:00:00Z",
    "updated_at": "2026-10-18T12:00:00Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Creative job id. |
| `job.request_id` | uuid | Your idempotency key. |
| `job.provider` | string | fal, higgsfield, openai or anthropic. |
| `job.model` | string | Model used (body model, else the integration's saved model). |
| `job.status` | string | submitting, queued, running, completed, failed, uncertain or cancelled. |
| `job.provider_id` | string\|null | Provider request id of a media job (null for writing). |
| `job.result` | object\|null | Provider output as returned (writing: the completion; media: the result once completed). |
| `job.error` | string\|null | "Invalid writing input", or the uncertain-outcome message; provider bodies are never echoed. |
| `job.created_at / job.updated_at` | timestamp | Lifecycle timestamps. |

**Errors**

- `400` {"error":"Invalid creative request","details":<zod flatten()>}: body not matching the schema (unknown key, bad requestId, provider or model), or no model in the body and none saved on the integration.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"No account"} when the request has no account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `409` {"error":"Request ID belongs to different input"}: requestId reused with a different body.
- `413` Body larger than 128 KiB ({"error":"Request body is too large"}).
- `422` {"error":"Configure an active provider integration first"} (no active integration or missing key / secret) or {"error":"Creative generation requires the official provider base URL"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `503` {"error":"Creative jobs are unavailable"} when storage fails; these routes keep their own 5xx statuses (a failure to load the account scope answers 503 {"error":"Authentication scope is temporarily unavailable"}).
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.

**Gotchas**

- The body is strict (only requestId, provider, model, input) and limited to 128 KiB.
- Always read job.status, even on 202: an invalid writing input is saved as failed ("Invalid writing input"); a provider call whose outcome is unknown is saved as uncertain.
- Provider calls may cost money. There is no automatic retry, spending cap or cancel endpoint. After a lost response, replay the SAME requestId and body; never send a new requestId to resolve an uncertain job before checking provider usage.
- Each provider call is bounded to 20 seconds and a 1 MiB response; the integration must use the official provider base URL.
- Media jobs: poll with POST /v1/integrations/creative/jobs/:id/poll until completed, failed or cancelled. The result keeps the provider's own output; upload or import approved media separately.

##### `GET /v1/integrations/creative/jobs/:id`

**Scope** `integrations.read` - **Read a creative job**

Read one saved creative job (status, result, error) without contacting the provider. A job stuck in submitting for more than 60 seconds is marked uncertain by this read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Creative job id of this account. |

**Response** `200`

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "provider": "fal",
    "model": "YOUR_VERIFIED_MODEL_ID",
    "status": "queued",
    "provider_id": "provider-request-id",
    "result": null,
    "error": null,
    "created_at": "2026-10-18T12:00:00Z",
    "updated_at": "2026-10-18T12:00:00Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Creative job id. |
| `job.request_id` | uuid | Your idempotency key. |
| `job.provider` | string | fal, higgsfield, openai or anthropic. |
| `job.model` | string | Model used (body model, else the integration's saved model). |
| `job.status` | string | submitting, queued, running, completed, failed, uncertain or cancelled. |
| `job.provider_id` | string\|null | Provider request id of a media job (null for writing). |
| `job.result` | object\|null | Provider output as returned (writing: the completion; media: the result once completed). |
| `job.error` | string\|null | "Invalid writing input", or the uncertain-outcome message; provider bodies are never echoed. |
| `job.created_at / job.updated_at` | timestamp | Lifecycle timestamps. |

**Errors**

- `400` {"error":"Invalid creative request","details":...}: :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"No account"} when the request has no account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `404` {"error":"Generation not found"}: no job with this id in the account.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `503` {"error":"Creative jobs are unavailable"} when storage fails; these routes keep their own 5xx statuses (a failure to load the account scope answers 503 {"error":"Authentication scope is temporarily unavailable"}).
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.

**Gotchas**

- Statuses: submitting, queued, running, completed, failed, uncertain, cancelled. Use the poll endpoint to refresh a queued or running media job.
- uncertain means the provider may or may not have received the request: check provider usage before creating a new request.

##### `POST /v1/integrations/creative/jobs/:id/poll`

**Scope** `integrations.write` - **Poll a creative media job**

Refresh a queued or running media job from its saved provider handle and save the new status and result. A job in any other status is returned as saved without contacting the provider.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Creative job id of this account. |

**Response** `200`

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "provider": "fal",
    "model": "YOUR_VERIFIED_MODEL_ID",
    "status": "queued",
    "provider_id": "provider-request-id",
    "result": null,
    "error": null,
    "created_at": "2026-10-18T12:00:00Z",
    "updated_at": "2026-10-18T12:00:00Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Creative job id. |
| `job.request_id` | uuid | Your idempotency key. |
| `job.provider` | string | fal, higgsfield, openai or anthropic. |
| `job.model` | string | Model used (body model, else the integration's saved model). |
| `job.status` | string | submitting, queued, running, completed, failed, uncertain or cancelled. |
| `job.provider_id` | string\|null | Provider request id of a media job (null for writing). |
| `job.result` | object\|null | Provider output as returned (writing: the completion; media: the result once completed). |
| `job.error` | string\|null | "Invalid writing input", or the uncertain-outcome message; provider bodies are never echoed. |
| `job.created_at / job.updated_at` | timestamp | Lifecycle timestamps. |

**Errors**

- `400` {"error":"Invalid creative request","details":...}: :id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"No account"} when the request has no account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `404` {"error":"Generation not found"}: no job with this id in the account.
- `409` {"error":"Provider request is not available"}: the job has no saved provider handle (writing job or failed submission).
- `422` {"error":"Configure an active provider integration first"} or {"error":"Creative generation requires the official provider base URL"}: the integration was disabled or changed.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `502` {"error":"Provider status unavailable. Retry polling; do not resubmit."}
- `503` {"error":"Creative jobs are unavailable"} when storage fails; these routes keep their own 5xx statuses (a failure to load the account scope answers 503 {"error":"Authentication scope is temporarily unavailable"}).
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.

**Gotchas**

- Each poll of a queued or running job calls the provider; back off between polls.
- On 502, retry polling later; never resubmit the job.

##### `GET /v1/integrations/friendlies/keys`

**Scope** `integrations.read` - **List API key identities for Friendlies pricing**

Returns the identity of the account's API keys (id, name, active), sorted by name and id, so a Friendlies USD cost can be set per key (PUT /v1/integrations/friendlies, config.unitCosts). Never returns key material and needs no key-management permission.

*No parameters.*

**Response**

```json
{
  "keys": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "name": "Partner key",
      "active": true
    }
  ]
}
```

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Key material is never returned. Only owned key identity and activity are exposed.

##### `GET /v1/integrations/friendlies/metrics`

**Scope** `integrations.read` - **Friendlies analytics**

Track recorded Friendlies attempts, approved volume and USD costs per API key within an inclusive date range. Excludes Friendlies from ordinary approval and ROAS metrics.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | ISO datetime; default `today UTC` | no | Inclusive start instant. An ISO datetime with Z (an offset or a bare day is a 400). Default: from = today 00:00 UTC, to = now. |
| `to` | ISO datetime; default `now` | no | Inclusive end instant; must not precede from. An ISO datetime with Z (an offset or a bare day is a 400). Default: from = today 00:00 UTC, to = now. |
| `limit` | integer; default `50` | no | Attempt rows per page, from 1 to 500. |
| `offset` | integer; default `0` | no | Nonnegative attempt offset. |

**Response**

```json
{
  "range": {
    "from": "2026-10-17T00:00:00.000Z",
    "to": "2026-10-17T23:59:59.999Z"
  },
  "metrics": {
    "active": true,
    "attempts": 2,
    "sales": 1,
    "amountCents": 3000,
    "amountCurrency": "USD",
    "costCents": 250,
    "discountCents": 90,
    "reserveCents": 300,
    "netCostCents": 640,
    "missingCostAttempts": 0,
    "costCurrency": "USD",
    "groups": [
      {
        "kind": "apiKey",
        "key": "00000000-0000-4000-8000-000000000001",
        "attempts": 2,
        "sales": 1,
        "amountCents": 3000,
        "amountCurrency": "USD",
        "costCents": 250,
        "discountCents": 90,
        "reserveCents": 300,
        "netCostCents": 640,
        "missingCostAttempts": 0
      }
    ]
  },
  "keys": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "name": "Partner alpha",
      "active": true
    }
  ],
  "attempts": [
    {
      "id": "00000000-0000-4000-8000-000000000002",
      "order_id": "friendly-1",
      "created_at": "2026-10-17T12:00:00.000Z",
      "status": "approved",
      "is_success": true,
      "amount_cents": 3000,
      "currency": "USD",
      "api_key_id": "00000000-0000-4000-8000-000000000001",
      "api_key_name": "Partner alpha",
      "cost_cents": 125,
      "discount_cents": 90,
      "reserve_cents": 300,
      "net_cost_cents": 515
    }
  ],
  "total": 2,
  "limit": 50,
  "offset": 0
}
```

| response field | type | description |
|---|---|---|
| `range` | object | Inclusive UTC date bounds. |
| `metrics` | object | All matching attempts and approved sales, approved amount, cost and net cost, plus groups by API key and reporting dimensions. |
| `metrics.netCostCents` | integer\|null | USD attempt cost plus approved discount and reserve; null if a tariff is missing or non-USD payment fees need conversion. |
| `keys` | array | Owned API key identities only: id, name, active. No credentials. |
| `attempts` | array | Current page of live Friendlies transactions, newest first. Amount and payment fees retain transaction currency; attempt cost and net cost are USD, null when unavailable. |
| `total` | integer | Matching attempts across all pages. |
| `limit` | integer | Page size. |
| `offset` | integer | Page offset. |

**Errors**

- `400` {"error":"Invalid range or pagination"} for a malformed from / to / limit / offset; {"error":"Invalid range"} when from is after to.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `404` {"error":"Friendlies integration inactive"} when Friendlies is not enabled and configured for the account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Account tenancy and ATRI view permissions apply equally to summary and attempt ledger.
- One cost per recorded transaction, approved or declined; MID cascades and idempotent replays do not add a cost. Current configured rates apply to historical rows.
- Friendlies never use 3DS or enroll in subscriptions; ordinary approval rates, Straight ROAS and Blended ROAS exclude Friendlies.
- Approved amount is null for mixed currencies. Net cost is null when USD cannot be computed honestly.
- Attempts are paginated; metrics and groups always cover the entire selected period.

##### `POST /v1/integrations/google_ads/conversion-actions`

**Scope** `integrations.write` - **Google Ads - list the conversion actions ("Test connection")**

v3.9.18 - the conversion actions of ONE Google Ads customer, read-only (OAuth refresh, then a GAQL search of conversion_action, removed ones left out) with the account's Google Ads credentials: the saved ones, overridden by what the Configure form holds (like POST /v1/integrations/:key/test). The Integrations card's "Conversion actions" tab and the store tag modal's action picker read it; `uploadable` = type UPLOAD_CLICKS and ENABLED, what a tag's server upload can target. A completed call is 200 with ok true / false.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `customerId` | string | no | The customer to list (10 digits, dashes accepted). Empty = the integration's loginCustomerId (the manager account). |
| `config` | object; default `{}` | no | Non-secret settings for THIS call (loginCustomerId), over the saved config. |
| `secrets` | object; default `{}` | no | developerToken / clientId / clientSecret / refreshToken typed in the form (max 4096 each), over the saved ones; a blank one falls back to the saved value. |

**Request body**

```json
{
  "customerId": "123-456-7890"
}
```

**Response**

```json
{
  "ok": true,
  "customerId": "1234567890",
  "ms": 412,
  "actions": [
    {
      "id": "987654321",
      "name": "Purchase (import)",
      "type": "UPLOAD_CLICKS",
      "status": "ENABLED",
      "category": "PURCHASE",
      "resourceName": "customers/1234567890/conversionActions/987654321",
      "uploadable": true
    },
    {
      "id": "111222333",
      "name": "Website purchase",
      "type": "WEBPAGE",
      "status": "ENABLED",
      "category": "PURCHASE",
      "resourceName": "customers/1234567890/conversionActions/111222333",
      "uploadable": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Google answered the list. |
| `customerId` | string | The customer listed (10 digits). |
| `actions[]` | object[] | { id, name, type, status, category, resourceName, uploadable } - uploadable first, then by name; [] when ok is false. |
| `status / error` | number / string | ok false only: Google's HTTP status (0 = network / timeout) and its error as one line ('401 authenticationError.OAUTH_TOKEN_INVALID: ...', 'oauth 400 invalid_grant: ...'), redacted of every credential. |
| `ms` | number | Elapsed. |

**Errors**

- `400` {"error":"Invalid","details":...} - customerId (given or the manager account) is not ten digits, or a malformed body.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `422` {"error":"Google Ads credentials incomplete: <field>"} - save (or type) the four credentials first; no Google call is made.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Never returns a credential. Bounded by a 10 s timeout per Google call.
- It is a POST (it may carry typed secrets), so the audit log records it although nothing changes.
- Reading a MANAGER account lists only the actions it owns (cross-account conversion tracking); a store tag needs the CLIENT customer that owns its action.

##### `GET /v1/integrations/pilot/sync`

**Scope** `integrations.read` - **Pilot spend sync: status**

The Sync tab of the Pilot card: what the account holds in pilot_spend_daily (days synced, first and last Pilot day, closed days, last write), whether the Pilot integration will run (active), whether a sync job is queued or running, the last error, and the most recent sync job the caller may see. Read-only; never calls Pilot.

*No parameters.*

**Response**

```json
{
  "daysSynced": 31,
  "firstDay": "2026-10-24",
  "lastDay": "2026-11-23",
  "lastSyncAt": "2026-11-23T13:10:04.512Z",
  "closedDays": 30,
  "active": true,
  "running": false,
  "lastError": null,
  "lastJob": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "22222222-3333-4444-8555-666666666666",
    "origin": "manual",
    "kind": "backfill",
    "range_from": "2026-10-24",
    "range_to": "2026-11-23",
    "timezone": "America/New_York",
    "status": "success",
    "stage": "done",
    "total": 31,
    "processed": 31,
    "succeeded": 31,
    "failed": 0,
    "skipped": 0,
    "refresh_utm": true,
    "cancel_requested": false,
    "refresh_intent_at": null,
    "refresh_before": null,
    "refresh_job_id": null,
    "warning": null,
    "error": null,
    "failures": 0,
    "available_at": "2026-11-23T12:58:10.101Z",
    "created_at": "2026-11-23T12:58:10.101Z",
    "updated_at": "2026-11-23T12:58:41.870Z",
    "finished_at": "2026-11-23T12:58:41.870Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `daysSynced` | integer | Distinct Pilot days holding a total row for the account. |
| `firstDay / lastDay` | string (YYYY-MM-DD) \| null | Earliest and latest synced Pilot day (Pilot profile timezone). |
| `lastSyncAt` | string (ISO-8601) \| null | Last write of a total row; null before the first sync. |
| `closedDays` | integer | Days the daily close re-read and marked closed; the others are "so far" snapshots. |
| `active` | boolean | The Pilot integration is enabled and its API key saved: the scheduler syncs this account. false = nothing is synced. |
| `running` | boolean | One of the listed jobs is queued or running. |
| `lastError` | string \| null | error, else warning, of the most recent listed job; null when none. |
| `lastJob` | object \| null | The most recent job the caller may see (active jobs first), or null. Jobs are listed per exact caller: a manual job is visible only to the principal that started it; scheduler jobs are visible to unrestricted account administrators. |
| `lastJob.id` | uuid | Job id. |
| `lastJob.request_id` | uuid | The requestId it was admitted with. |
| `lastJob.origin` | "manual" \| "scheduler" \| "live" | Who started it. |
| `lastJob.kind` | "hourly" \| "close" \| "preclose" \| "backfill" \| "live" | hourly = today + yesterday; backfill = an explicit or configured range; close / preclose / live = scheduler passes. |
| `lastJob.range_from / range_to` | string (YYYY-MM-DD) \| null | The backfill range, null otherwise. |
| `lastJob.timezone` | string \| null | Pilot report timezone once known. |
| `lastJob.status` | "queued" \| "running" \| "success" \| "partial" \| "failed" \| "cancelled" | State. |
| `lastJob.stage` | "plan" \| "refresh" \| "refresh_wait" \| "days" \| "evidence" \| "done" | Current step. |
| `lastJob.total / processed / succeeded / failed / skipped` | integer | Day counters. |
| `lastJob.refresh_utm / cancel_requested` | boolean | Whether the utm evidence is refreshed; whether a cancel was asked. |
| `lastJob.refresh_intent_at / refresh_before / refresh_job_id` | string \| null | Live Report refresh bookkeeping. |
| `lastJob.warning / error` | string \| null | Last warning and terminal error (typed Pilot errors such as "UNAUTHENTICATED: ..."). |
| `lastJob.failures` | integer | Retry count. |
| `lastJob.available_at / created_at / updated_at / finished_at` | string (ISO-8601) \| null | Timestamps. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account; {"error":"A signed-in account is required"}, or a recheck under lock that failed: "Pilot account access changed", "Pilot API key access changed" (the key was deactivated or moved meanwhile), "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `500` {"error":"A required data table is unavailable."} when the Pilot tables are missing, or {"error":"Internal Server Error","requestId":"..."}.
- `503` {"error":"The database is temporarily unavailable - please retry in a moment."} (with retry-after: 1) when the database cannot be reached.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} past the 10-second control budget (the control deadline carries the database timeout code, so it is answered as a timeout).

**Gotchas**

- The scheduler syncs every active account on its own (hourly today + yesterday, a daily close, and a first backfill of up to 92 days for a newly enabled account); POST /v1/integrations/pilot/sync only asks for an extra pass.
- lastJob and running reflect the jobs the caller may see (see lastJob). Another principal's running manual job still blocks a new one with 409.
- Pilot days are keyed in the Pilot profile's timezone; the dashboard metrics sum the days whose key falls in the range's calendar days.
- The full job list, one job with its days, cancel and per-day errors are under /v1/integrations/pilot/sync-jobs.

##### `POST /v1/integrations/pilot/sync`

**Scope** `integrations.write` - **Pilot spend sync: run now**

Queues a durable Pilot sync job for the caller's account: with no range the hourly pass (today + yesterday in the Pilot timezone); with from and to a backfill of that range (at most 92 days). Answers 202 at once; poll GET /v1/integrations/pilot/sync or GET /v1/integrations/pilot/sync-jobs/:jobId. Same handler as POST /v1/integrations/pilot/sync-jobs.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid | no | Idempotency key, per account and caller. The same requestId with the same request returns the existing job (202); with a different range or kind, or from another principal, 409 "Request ID belongs to another sync". Omitted = a new random id. |
| `from` | string YYYY-MM-DD | no | First Pilot day of a backfill. Send from and to together (one alone is a 400). from <= to, at most 92 days, to not after tomorrow (UTC). |
| `to` | string YYYY-MM-DD | no | Last Pilot day of the backfill. |

**Request body**

```json
{
  "requestId": "33333333-4444-4555-8666-777777777777",
  "from": "2026-10-24",
  "to": "2026-11-23"
}
```

**Response** `202`

```json
{
  "jobId": "11111111-2222-4333-8444-555555555555",
  "kind": "backfill",
  "range": {
    "from": "2026-10-24",
    "to": "2026-11-23"
  },
  "job": {
    "id": "11111111-2222-4333-8444-555555555555",
    "request_id": "33333333-4444-4555-8666-777777777777",
    "origin": "manual",
    "kind": "backfill",
    "range_from": "2026-10-24",
    "range_to": "2026-11-23",
    "status": "queued",
    "stage": "plan",
    "total": 0,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "error": null,
    "created_at": "2026-11-23T12:58:10.101Z",
    "finished_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | The job id. |
| `kind` | "hourly" \| "backfill" | hourly without a range, backfill with one. |
| `range` | {from, to} \| null | The validated range, null for the hourly pass. |
| `job` | object | The job (same fields as lastJob in GET /v1/integrations/pilot/sync). |

**Errors**

- `400` {"error":"Invalid sync parameters"} (an unknown field, requestId not a uuid, a day longer than 10 characters); {"error":"from / to must be YYYY-MM-DD"} (also when only one is sent), {"error":"from must be before to"}, {"error":"Range too large (max 92 days)"}, {"error":"to is in the future"}.
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"} when the key's scopes lack integrations.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"A signed-in account is required"}, or a recheck under lock that failed: "Pilot account access changed", "Pilot API key access changed" (the key was deactivated or moved meanwhile), "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `409` {"error":"A Pilot sync is already queued or running for this account"} (one manual job per account at a time, whoever started it); {"error":"Request ID belongs to another sync"}.
- `422` {"error":"Enable Pilot and save an API key first"}: the integration is off or has no API key.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Durable Pilot sync is not enabled"} (background jobs are off on this deployment) or {"error":"Required storage for Pilot sync is unavailable. Complete the current database migrations."}.
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} past the 10-second control budget (the control deadline carries the database timeout code, so it is answered as a timeout).

**Gotchas**

- 202 means queued, not done: poll until status is success, partial, failed or cancelled.
- A job calls Pilot with the account's own key; every day is replaced in one transaction, so re-running is idempotent.
- The 409 for a running job carries no job id in the body: list the jobs (GET /v1/integrations/pilot/sync-jobs) to find it.
- This route takes no account parameter: the account is the caller's.

##### `GET /v1/integrations/pilot/sync-capabilities`

**Scope** `integrations.read` - **Read Pilot sync availability**

Tell whether a durable Pilot spend sync can be admitted now: true when background workers run and the Pilot sync storage exists. Does not check the Pilot integration itself.

*No parameters.*

**Response**

```json
{
  "enabled": true
}
```

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- enabled true does not guarantee admission: POST /v1/integrations/pilot/sync-jobs still needs Pilot enabled with an API key (else 422).

##### `GET /v1/integrations/pilot/sync-jobs`

**Scope** `integrations.read` - **List Pilot sync jobs**

List the 25 most recent Pilot sync jobs of the account visible to the caller (active first, then newest): the caller's own manual jobs plus the automatic (scheduler, live) jobs.

*No parameters.*

**Response**

```json
{
  "jobs": [
    {
      "id": "00000000-0000-4000-8000-000000000001",
      "request_id": "00000000-0000-4000-8000-000000000002",
      "origin": "manual",
      "kind": "backfill",
      "range_from": "2026-09-01",
      "range_to": "2026-09-30",
      "timezone": null,
      "status": "queued",
      "stage": "plan",
      "total": 0,
      "processed": 0,
      "succeeded": 0,
      "failed": 0,
      "skipped": 0,
      "refresh_utm": false,
      "cancel_requested": false,
      "refresh_intent_at": null,
      "refresh_before": null,
      "refresh_job_id": null,
      "warning": null,
      "error": null,
      "failures": 0,
      "available_at": "2026-11-20T10:00:00.000Z",
      "created_at": "2026-11-20T10:00:00.000Z",
      "updated_at": "2026-11-20T10:00:00.000Z",
      "finished_at": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `jobs[].id` | uuid | Sync job id. |
| `jobs[].request_id` | uuid | Idempotency key. |
| `jobs[].origin` | string | manual, scheduler or live. |
| `jobs[].kind` | string | backfill (a from/to range) or hourly (the recent days). |
| `jobs[].range_from / range_to` | YYYY-MM-DD\|null | Backfill range. |
| `jobs[].status` | string | queued, running, success, partial, failed or cancelled. |
| `jobs[].stage` | string | plan, refresh, refresh_wait, days, evidence or done. |
| `jobs[].total / processed / succeeded / failed / skipped` | integer | Day counters. |
| `jobs[].warning / error` | string\|null | Last warning or error message. |
| `jobs[].cancel_requested, refresh_utm, refresh_intent_at, refresh_before, refresh_job_id, timezone, failures, available_at, created_at, updated_at, finished_at` | mixed | Worker bookkeeping and timestamps. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Partial days stay committed; a day with no Pilot snapshot is skipped and the existing spend is preserved. Job metadata is kept 30 days. Reading and cancelling work while workers are paused.

##### `POST /v1/integrations/pilot/sync-jobs`

**Scope** `integrations.write` - **Start a Pilot spend sync**

Queue a durable Pilot (TikTok ad spend) sync for the account: with from and to, a backfill of those days; without them, an hourly sync of the recent days. Returns 202 with the job. Replaying the same requestId with the same parameters returns the existing job.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `requestId` | uuid; default `a random uuid` | no | Idempotency key per account and caller. Omitted: a new id is generated, so a retry is only deduplicated when you send the same id. Same id with different parameters: 409. |
| `from` | string (YYYY-MM-DD) | no | First day of a backfill. Send from and to together (one alone is a 400). Range at most 92 days, from <= to. |
| `to` | string (YYYY-MM-DD) | no | Last day of a backfill; at most tomorrow (UTC). |

**Request body**

```json
{
  "requestId": "00000000-0000-4000-8000-000000000002",
  "from": "2026-09-01",
  "to": "2026-09-30"
}
```

**Response** `202`

```json
{
  "jobId": "00000000-0000-4000-8000-000000000001",
  "kind": "backfill",
  "range": {
    "from": "2026-09-01",
    "to": "2026-09-30"
  },
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "origin": "manual",
    "kind": "backfill",
    "range_from": "2026-09-01",
    "range_to": "2026-09-30",
    "timezone": null,
    "status": "queued",
    "stage": "plan",
    "total": 0,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "refresh_utm": false,
    "cancel_requested": false,
    "refresh_intent_at": null,
    "refresh_before": null,
    "refresh_job_id": null,
    "warning": null,
    "error": null,
    "failures": 0,
    "available_at": "2026-11-20T10:00:00.000Z",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null
  }
}
```

| response field | type | description |
|---|---|---|
| `jobId` | uuid | The job id. |
| `kind` | string | backfill or hourly. |
| `range` | object\|null | {from,to} for a backfill, null for hourly. |
| `job.id` | uuid | Sync job id. |
| `job.request_id` | uuid | Idempotency key. |
| `job.origin` | string | manual, scheduler or live. |
| `job.kind` | string | backfill (a from/to range) or hourly (the recent days). |
| `job.range_from / range_to` | YYYY-MM-DD\|null | Backfill range. |
| `job.status` | string | queued, running, success, partial, failed or cancelled. |
| `job.stage` | string | plan, refresh, refresh_wait, days, evidence or done. |
| `job.total / processed / succeeded / failed / skipped` | integer | Day counters. |
| `job.warning / error` | string\|null | Last warning or error message. |
| `job.cancel_requested, refresh_utm, refresh_intent_at, refresh_before, refresh_job_id, timezone, failures, available_at, created_at, updated_at, finished_at` | mixed | Worker bookkeeping and timestamps. |

**Errors**

- `400` {"error":"Invalid sync parameters"} (body shape), {"error":"from / to must be YYYY-MM-DD"}, {"error":"from must be before to"}, {"error":"Range too large (max 92 days)"} or {"error":"to is in the future"}.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `409` {"error":"Request ID belongs to another sync"}, {"error":"A Pilot sync is already queued or running for this account"} or {"error":"Pilot queue is full"}.
- `422` {"error":"Enable Pilot and save an API key first"}.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.
- `503` {"error":"Durable Pilot sync is not enabled","requestId":"<id>"} when background workers are off, or {"error":"Required storage for Pilot sync is unavailable. Complete the current database migrations.","requestId":"<id>"} when the Pilot sync storage is not migrated (Retry-After: 1; check sync-capabilities first).

**Gotchas**

- Only one manual sync may be queued or running per account; a second answers 409.
- The body is strict: unknown keys answer 400.
- Partial days stay committed; a day with no Pilot snapshot is skipped and the existing spend is preserved. Job metadata is kept 30 days. Reading and cancelling work while workers are paused.

##### `GET /v1/integrations/pilot/sync-jobs/:jobId`

**Scope** `integrations.read` - **Read a Pilot sync job**

Read one Pilot sync job with its per-day results (day, status, error, rows written, invariant check, capture time).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Sync job id. A non-uuid answers 400 {"error":"Invalid sync ID"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "origin": "manual",
    "kind": "backfill",
    "range_from": "2026-09-01",
    "range_to": "2026-09-30",
    "timezone": null,
    "status": "partial",
    "stage": "plan",
    "total": 30,
    "processed": 30,
    "succeeded": 28,
    "failed": 0,
    "skipped": 2,
    "refresh_utm": false,
    "cancel_requested": false,
    "refresh_intent_at": null,
    "refresh_before": null,
    "refresh_job_id": null,
    "warning": null,
    "error": null,
    "failures": 0,
    "available_at": "2026-11-20T10:00:00.000Z",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": null
  },
  "days": [
    {
      "day": "2026-09-01",
      "status": "success",
      "error": null,
      "rows_written": 14,
      "invariant_ok": true,
      "captured_at": "2026-11-20T10:02:00.000Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `job.id` | uuid | Sync job id. |
| `job.request_id` | uuid | Idempotency key. |
| `job.origin` | string | manual, scheduler or live. |
| `job.kind` | string | backfill (a from/to range) or hourly (the recent days). |
| `job.range_from / range_to` | YYYY-MM-DD\|null | Backfill range. |
| `job.status` | string | queued, running, success, partial, failed or cancelled. |
| `job.stage` | string | plan, refresh, refresh_wait, days, evidence or done. |
| `job.total / processed / succeeded / failed / skipped` | integer | Day counters. |
| `job.warning / error` | string\|null | Last warning or error message. |
| `job.cancel_requested, refresh_utm, refresh_intent_at, refresh_before, refresh_job_id, timezone, failures, available_at, created_at, updated_at, finished_at` | mixed | Worker bookkeeping and timestamps. |
| `days[]` | object[] | One per planned day in order: day, status (pending, success, skipped, failed), error, rows_written, invariant_ok, captured_at. |

**Errors**

- `400` {"error":"Invalid sync ID"}: jobId is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `404` {"error":"Pilot sync not found"}: not a job of this account visible to the caller.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Partial days stay committed; a day with no Pilot snapshot is skipped and the existing spend is preserved. Job metadata is kept 30 days. Reading and cancelling work while workers are paused.

##### `POST /v1/integrations/pilot/sync-jobs/:jobId/cancel`

**Scope** `integrations.write` - **Cancel a Pilot sync job**

Cancel a queued or running Pilot sync job (status cancelled at once). Days already committed stay; a remote refresh already sent to Pilot cannot be recalled. A finished job is returned unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Sync job id. A non-uuid answers 400 {"error":"Invalid sync ID"}. |

**Response**

```json
{
  "job": {
    "id": "00000000-0000-4000-8000-000000000001",
    "request_id": "00000000-0000-4000-8000-000000000002",
    "origin": "manual",
    "kind": "backfill",
    "range_from": "2026-09-01",
    "range_to": "2026-09-30",
    "timezone": null,
    "status": "cancelled",
    "stage": "plan",
    "total": 0,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "skipped": 0,
    "refresh_utm": false,
    "cancel_requested": true,
    "refresh_intent_at": null,
    "refresh_before": null,
    "refresh_job_id": null,
    "warning": null,
    "error": null,
    "failures": 0,
    "available_at": "2026-11-20T10:00:00.000Z",
    "created_at": "2026-11-20T10:00:00.000Z",
    "updated_at": "2026-11-20T10:00:00.000Z",
    "finished_at": "2026-11-20T10:05:00.000Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `job` | object | The job after the cancel, same fields as the list. |

**Errors**

- `400` {"error":"Invalid sync ID"}: jobId is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `404` {"error":"Pilot sync not found"}: not a job of this account visible to the caller.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- Partial days stay committed; a day with no Pilot snapshot is skipped and the existing spend is preserved. Job metadata is kept 30 days. Reading and cancelling work while workers are paused.

##### `GET /v1/integrations/pilot/sync-jobs/:jobId/errors`

**Scope** `integrations.read` - **List the failed or skipped days of a Pilot sync**

List the days of one Pilot sync job that failed or were skipped, with the reason, in day order.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `jobId` | uuid | **yes** | Sync job id. A non-uuid answers 400 {"error":"Invalid sync ID"}. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `offset` | integer; default `0` | no | Rows to skip, clamped to 0..107 (a non-number reads as 0). |
| `limit` | integer; default `100` | no | Rows to return, clamped to 1..100 (a non-number reads as 100). |

**Response**

```json
{
  "errors": [
    {
      "itemId": "2026-09-14",
      "reason": "Pilot has no snapshot for this day; existing data was preserved"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `errors[].itemId` | YYYY-MM-DD | The day. |
| `errors[].reason` | string | The saved error, or "Pilot has no snapshot for this day; existing data was preserved" for a skipped day without one. |

**Errors**

- `400` {"error":"Invalid sync ID"}: jobId is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} when the key is unknown or revoked.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no paid or granted platform subscription.
- `403` {"error":"<reason>"} when access changed: "A signed-in account is required", "Pilot account access changed", "Pilot API key access changed", "Pilot author access changed", "Pilot account or role changed", "Pilot grants changed".
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<scope>"} when the key lacks this operation's scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key has no active owner; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan does not include that module.
- `404` {"error":"Pilot sync not found"}: not a job of this account visible to the caller.
- `429` Per-IP rate limit exceeded (a fixed number of requests per minute); back off, then retry.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure; a read is safe to retry.
- `503` {"error":"Server busy, retry"} (Retry-After: 1) when the server is at capacity, or the database is momentarily unavailable; retry after a second.
- `503` {"error":"Authentication scope is temporarily unavailable","requestId":"<id>"} (Retry-After: 1) when the account scope could not be loaded; retry after a second.

**Gotchas**

- There is no total or hasMore: page until fewer than limit rows come back.

##### `GET /v1/integrations/pilot/targets`

**Scope** `integrations.read` - **Pilot campaign targets - list**

v3.9.3 Pilot - the Mapping tab: every Pilot campaign with spend in the last 30 days (∪ every stored target row), its effective target on the dashboard (a Store row host, a Product row URL, 'ignored', or null = unmapped) and the evidence the sync computed for it (the suggestions). Attribution rule: a campaign's spend lands in ONE bucket - the manual target when the operator set one (source 'manual'), else the sync's auto target (source 'auto': the destination URL / host carrying >= 80 % of the campaign's spend per Pilot's byProduct, else the store host >= 80 % of the account's sales whose transaction_attribution.utm_id = the campaign id), else nowhere (counted in the cards' spend, on no row).

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "campaign_id": "1801234567890123456",
      "campaign_name": "[12] - Widget Pro",
      "spend_cents_30d": 152070,
      "target_kind": "product",
      "target_key": "myshop.example/products/widget-pro",
      "source": "auto",
      "suggestions": [
        { "kind": "product", "key": "myshop.example/products/widget-pro", "score": 1, "why": "pilot_destination" },
        { "kind": "store", "key": "myshop.example", "score": 1, "why": "pilot_destination" }
      ]
    },
    {
      "campaign_id": "1801234567890123459",
      "campaign_name": "(03/09) - Awareness",
      "spend_cents_30d": 6000,
      "target_kind": null,
      "target_key": null,
      "source": "auto",
      "suggestions": [
        { "kind": "store", "key": "myshop.example", "score": 0.62, "why": "utm_id" },
        { "kind": "store", "key": "other.example", "score": 0.38, "why": "utm_id" }
      ]
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | Most 30-day spend first, then by campaign id. |
| `rows[].campaign_id` | string | Pilot byCampaign[].id (the TikTok campaign id - the value the checkout sends as utm_id). |
| `rows[].campaign_name` | string \| null | As Pilot names it. |
| `rows[].spend_cents_30d` | integer | Σ of the campaign's daily spend rows over the last 30 Pilot days (0 for a stored target without recent spend). |
| `rows[].target_kind` | enum: product\|store\|ignored \| null | The EFFECTIVE target: 'product' (target_key = the product URL as host/path, matched to a Product row's url normalised - and counted on that host's Store row too), 'store' (target_key = the host, matched to a Store row exactly, then by registrable host), 'ignored' (excluded from every figure, the cards included), null = unmapped (in the cards' spend, on no row). |
| `rows[].target_key` | string \| null | Normalised: a host (lower-case, no www.) or host/path (no scheme, query, trailing slash). |
| `rows[].source` | enum: auto\|manual \| null | manual = set through PUT (wins, never overwritten by the sync); auto = the sync's; null = the campaign has spend but no target row yet (the sync writes one on its next pass over that campaign). |
| `rows[].suggestions[]` | {kind: 'product'\|'store', key, score: 0..1, why: 'pilot_destination'\|'utm_id'}[] | The evidence, best first: pilot_destination = the share of the campaign's spend on that URL / host per Pilot's byProduct (a destination's spend is split across the campaigns it names, by their spend); utm_id = the share of the account's last-30-day sales carrying the campaign id as utm_id, by store host (refreshed at the daily close and on a backfill). An auto target needs a score >= 0.8. |

**Errors**

- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.read"} when the key's scopes lack integrations.read; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Required storage for Pilot is unavailable. Complete the current database migrations."}: the Pilot tables are missing (deployment issue).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- A campaign whose ads land on several product URLs with none >= 80 % gets a store-level auto target when the host is >= 80 % (its spend reaches the Store row, no Product row); pick a product target by hand to place it on a Product row.

##### `PUT /v1/integrations/pilot/targets`

**Scope** `integrations.write` - **Pilot campaign targets - manual overrides**

v3.9.3 Pilot - set where a campaign's spend lands (source becomes 'manual': the sync never overwrites it), or reset a campaign to the sync's auto target (target_kind null -> source 'auto', the stored suggestions decide again). 1..500 rows per call; a campaign unknown to the spend table gets a row too (mapping ahead of the first spend). Answers the count written and the refreshed list (the GET's shape).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `rows` | object[] (1..500) | **yes** | [{ campaign_id, target_kind, target_key }]. Unknown top-level fields are refused (strict). |
| `rows[].campaign_id` | string (1..64) | **yes** | Pilot's campaign id. |
| `rows[].target_kind` | enum: product\|store\|ignored \| null | **yes** | product / store need a target_key; ignored needs none; null = back to auto. |
| `rows[].target_key` | string (<= 2048) \| null | no | store: a host (any spelling - 'https://www.Shop.com/' is stored as 'shop.com'); product: a URL or host/path (stored normalised: lower-case host, no scheme / www. / query / trailing slash - the Product row's url normalises the same way). Ignored for 'ignored' and null. |

**Request body**

```json
{
  "rows": [
    { "campaign_id": "1801234567890123459", "target_kind": "store", "target_key": "www.myshop.example" },
    { "campaign_id": "1801234567890123460", "target_kind": "product", "target_key": "https://myshop.example/products/widget-pro?utm_source=tiktok" },
    { "campaign_id": "1801234567890123461", "target_kind": "ignored" },
    { "campaign_id": "1801234567890123456", "target_kind": null }
  ]
}
```

**Response**

```json
{
  "updated": 4,
  "rows": [
    {
      "campaign_id": "1801234567890123459",
      "campaign_name": "(03/09) - Awareness",
      "spend_cents_30d": 6000,
      "target_kind": "store",
      "target_key": "myshop.example",
      "source": "manual",
      "suggestions": []
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `updated` | integer | Rows written (a null-kind reset of a campaign without a row counts 0). |
| `rows` | object[] | The refreshed list - GET /v1/integrations/pilot/targets. |

**Errors**

- `400` {"error":"Invalid","details":<zod>} - rows missing / empty / > 500, an unknown kind, an unknown field; {"error":"target_key required for a product target", campaign_id} when a product / store row has no usable key (a blank, or a key that normalises to nothing).
- `401` Missing or invalid credential: {"error":"Missing bearer token"} or {"error":"Invalid API key"}.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"}: the account has no active platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"} when the key's scopes lack integrations.write; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"Forbidden for your role"} for role refund or a member without a role; {"error":"No account"} when the caller has no account.
- `429` {"error":"Rate limit exceeded, retry in 1 minute"}: more than 300 requests per minute from one IP (RATE_LIMIT_DEFAULT, in memory per instance).
- `503` {"error":"Required storage for Pilot is unavailable. Complete the current database migrations."}: the Pilot tables are missing (deployment issue).
- `500` {"error":"Internal Server Error","requestId":"..."} for an unexpected failure.

**Gotchas**

- The whole call is one transaction: a bad key in row 3 rolls back rows 1-2 (400).
- A manual row keeps its suggestions from the sync (the mapping tab still shows the evidence); a manual row set BEFORE the campaign was ever synced starts with [].
- Changing a target changes the next GET /v1/metrics read immediately (no re-sync): attribution is computed at read time from the campaign rows and the targets.
- The audit log records 'update' / objectType 'integration' / page Integrations (objectId null: the path holds no id).

##### `GET /v1/integrations/product-matching/metrics`

**Scope** `integrations.read` - **Get smart product matching analytics**

Analytics of the Smart product matching integration over a date range: how many gateway attempts described the charge to the gateway as a matched basket from the storefront catalog versus the generic filler line, with the approvals of each, per storefront host (the MID's bank page). Computed over the caller's tenant scope.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | string (ISO 8601 with Z); default `today 00:00 UTC` | no | Start of the metrics window, inclusive. The metrics window itself is read only from an ISO datetime with Z (for example 2026-11-01T00:00:00Z): a bare day or an offset passes the filter validation but makes the window fall back to today (00:00 UTC to now). |
| `to` | string (ISO 8601 with Z); default `now` | no | End of the metrics window, inclusive. The metrics window itself is read only from an ISO datetime with Z (for example 2026-11-01T00:00:00Z): a bare day or an offset passes the filter validation but makes the window fall back to today (00:00 UTC to now). |
| `tz` | string | no | Date filter: IANA timezone the days and hours are read in. Max 64 characters. |
| `hour` | CSV | no | Date filter: CSV of hours 00-23 in tz (needs tz). CSV of hours 0 to 23 (one or two digits each), max 200 characters; an invalid entry is a 400. Needs a valid tz (400 "hour needs a valid tz"). |
| `status` | CSV (closed list) | no | Transaction filter: Charge status (failed = declined + error, completed = with an outcome). Allowed values: approved, failed, declined, error, unknown, pending, duplicate, completed, chargeback, rdr, ethoca. Max 400 characters; an unknown value is a 400. |
| `source` | CSV (closed list) | no | Transaction filter: straight (sale + recovery) / subscription (rebill), or the raw buckets. Allowed values: sale, rebill, recovery, pre-auth, friendlies, straight, subscription, upsell. Max 100 characters; an unknown value is a 400. |
| `pass` | CSV (closed list) | no | Transaction filter: initial / cascade. Allowed values: initial, cascade. Max 40 characters; an unknown value is a 400. |
| `method` | CSV (closed list) | no | Transaction filter: card / wallet / wire. Allowed values: card, wallet, wire. Max 40 characters; an unknown value is a 400. |
| `population` | CSV (closed list) | no | Transaction filter: live / test / imported (reports: live only). Allowed values: live, test, imported. Max 40 characters; an unknown value is a 400. |
| `credentialMode` | CSV (closed list) | no | Transaction filter: Wire: mit / cit. Allowed values: mit, cit. Max 20 characters; an unknown value is a 400. |
| `threeDs` | CSV (closed list) | no | Transaction filter: 3DS outcome. Allowed values: applied, applied-other, attempted, reserved, holdout, excluded, rule, none, not-run, frictionless, challenge, attempt, data-only. Max 400 characters; an unknown value is a 400. |
| `declineCategory` | string | no | Transaction filter: Decline-engine category. Max 1000 characters. |
| `declineSeverity` | CSV (closed list) | no | Transaction filter: soft / hard. Allowed values: soft, hard. Max 40 characters; an unknown value is a 400. |
| `amountMin` | string (integer cents) | no | Transaction filter: Amount >= (cents). A whole number of cents, 1 to 12 digits. |
| `amountMax` | string (integer cents) | no | Transaction filter: Amount <= (cents). A whole number of cents, 1 to 12 digits. Must not be lower than amountMin (400 "amountMax is before amountMin"). |
| `currency` | CSV | no | Transaction filter: ISO-4217 currency. CSV of 3-letter currency codes, max 200 characters; an invalid entry is a 400. |
| `gatewayTxnId` | string | no | Transaction filter: Gateway transaction id (exact, CSV). Max 4000 characters. |
| `authCode` | string | no | Transaction filter: Auth code of any attempt (exact, CSV). Max 1000 characters. |
| `descriptor` | string | no | Transaction filter: Descriptor contains (sent statement descriptor, MID soft descriptor or name). Max 128 characters. |
| `pricePoint` | CSV (closed list) | no | Transaction filter: Price bucket. Allowed values: 1. < $25, 2. $25-49, 3. $50-74, 4. $75-99, 5. $100-149, 6. $150-199, 7. $200+. Max 400 characters; an unknown value is a 400. |
| `product` | string | no | Transaction filter: Basket product name / slug / ref. Max 4000 characters. |
| `productSlug` | string | no | Transaction filter: Basket product slug. Max 4000 characters. |
| `productKey` | string | no | Transaction filter: Product per store: <host>\|<ref>. Max 4000 characters. |
| `accountId` | CSV | no | Routing filter: Gateway: MID ids, wallet:<walletProviderId>, none. CSV of gateway (MID) UUIDs, wallet:<walletProviderUuid>, wire:<bankAccountUuid> or none, max 4000 characters; an invalid entry is a 400. |
| `walletProvider` | CSV of UUIDs | no | Routing filter: Wallet provider ids (API alias of accountId=wallet:<id>). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `gatewayType` | string | no | Routing filter: a gateway type (the gatewayType values returned by GET /v1/accounts). Max 100 characters. |
| `category` | CSV of UUIDs | no | Routing filter: Any category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `primaryCategory` | CSV of UUIDs | no | Routing filter: Primary category of the final MID (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atri` | CSV of UUIDs | no | Routing filter: ATRI reached (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `atriFinal` | CSV of UUIDs | no | Routing filter: ATRI the order ended on (ids). Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `processor` | CSV of UUIDs | no | Routing filter: Processor ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `acquiringBank` | CSV of UUIDs | no | Routing filter: Acquiring bank ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `company` | CSV of UUIDs | no | Routing filter: Company ids, none. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `gatewayMcc` | string | no | Routing filter: Final MID MCC. Max 1000 characters. |
| `gatewayBin` | string | no | Routing filter: Final MID acquirer BIN. Max 1000 characters. |
| `brand` | string | no | Card filter: Payment method: Visa / Mastercard / Amex / Discover / Apple Pay / Google Pay / Other. Max 200 characters. |
| `paysource` | string | no | Card filter: APPLEPAY / GOOGLEPAY (wallet payload). Max 100 characters. |
| `funding` | string | no | Card filter: Prepaid / Debit / Credit / Charge card (or a wallet). Max 200 characters. |
| `cardType` | string | no | Card filter: bin_info card type (or a wallet). Max 200 characters. |
| `cardLevel` | string | no | Card filter: bin_info card level (or a wallet). Max 4000 characters. |
| `issuer` | string | no | Card filter: Issuing bank (RFC-4180 CSV). Max 4000 characters. |
| `bin` | CSV | no | Card filter: CSV of 6-digit BINs or a wallet label. CSV of 6-digit BINs or the wallet labels Apple Pay / Google Pay, max 4000 characters; an invalid entry is a 400. |
| `first6` | string (digits) | no | Card filter: Card prefix (1-6 digits). 1 to 6 digits. |
| `last4` | string (digits) | no | Card filter: Card suffix (1-4 digits). 1 to 4 digits. |
| `country` | string | no | Customer filter: Billing country (ISO-2, inherited from the sale). Max 2000 characters. |
| `storefront` | string | no | Customer filter: Store host bucket, (direct). Max 4000 characters. |
| `traffic` | string | no | Customer filter: Traffic source, (direct/organic). Max 2000 characters. |
| `utmSource` | string | no | Customer filter: UTM source (case-insensitive). Max 4000 characters. |
| `utmCampaign` | string | no | Customer filter: UTM campaign (case-insensitive). Max 4000 characters. |
| `device` | string | no | Customer filter: Mobile / Tablet / Desktop. Max 200 characters. |
| `os` | string | no | Customer filter: Operating system. Max 200 characters. |
| `browser` | string | no | Customer filter: Browser. Max 200 characters. |
| `ipType` | CSV (closed list) | no | Customer filter: IPv4 / IPv6. Allowed values: IPv4, IPv6. Max 40 characters; an unknown value is a 400. |
| `ip` | string | no | Customer filter: CSV of client IPs. Max 2000 characters. |
| `email` | string | no | Customer filter: E-mail contains. Max 200 characters. |
| `phone` | string | no | Customer filter: Phone contains. Max 40 characters. |
| `firstName` | string | no | Customer filter: First name contains. Max 120 characters. |
| `lastName` | string | no | Customer filter: Last name contains. Max 120 characters. |
| `customerEmail` | string | no | Client filter: Client e-mail (exact, CSV). Max 4000 characters. |
| `customerThreeDs` | CSV (closed list) | no | Client filter: Customer authentication inventory now; single/double count proofs obtained, including used proofs. Allowed values: with-ready, without-ready, single, double, ready-for-rebill. Max 200 characters; an unknown value is a 400. |
| `clientBlacklisted` | enum | no | Client filter: Blacklisted (e-mail or card). One of: true, false. |
| `clientLiveSub` | enum | no | Client filter: Has a live (active / paused) subscription. One of: true, false. |
| `clientOrdersMin` | string (integer) | no | Client filter: Lifetime orders >=. A whole number, 1 to 12 digits. |
| `clientOrdersMax` | string (integer) | no | Client filter: Lifetime orders <=. A whole number, 1 to 12 digits. Must not be lower than clientOrdersMin (400 "clientOrdersMax is before clientOrdersMin"). |
| `clientLtvMin` | string (integer) | no | Client filter: Lifetime value >= (cents). A whole number, 1 to 12 digits. |
| `clientLtvMax` | string (integer) | no | Client filter: Lifetime value <= (cents). A whole number, 1 to 12 digits. Must not be lower than clientLtvMin (400 "clientLtvMax is before clientLtvMin"). |
| `clientFirstFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientFirstTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: First seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientFirstFrom (400 "clientFirstTo is before clientFirstFrom"). |
| `clientLastFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `clientLastTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Client filter: Last seen to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before clientLastFrom (400 "clientLastTo is before clientLastFrom"). |
| `checkout` | CSV of UUIDs | no | Transaction filter: Checkout ids at sale; none for unattributed / legacy. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `flow` | CSV of UUIDs | no | Transaction filter: Flow ids from the immutable checkout session version; none for direct checkout / legacy. Account scoped. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `affiliate` | CSV of UUIDs | no | Transaction filter: Affiliate ids from immutable payment attribution; none for no affiliate. Requires the account feature and rejects unknown or foreign ids. Comma-separated UUIDs or none; max 4000 characters; a malformed entry is a 400. |
| `subscription` | CSV of UUIDs | no | Subscription filter: Subscription product ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `cycle` | CSV | no | Subscription filter: Charge cycle (0 = the straight sale). CSV of cycle numbers (1 to 3 digits each), max 200 characters; an invalid entry is a 400. |
| `cycleMin` | string (integer) | no | Subscription filter: Charge cycle >=. A whole number, 1 to 6 digits. |
| `cycleMax` | string (integer) | no | Subscription filter: Charge cycle <=. A whole number, 1 to 6 digits. Must not be lower than cycleMin (400 "cycleMax is before cycleMin"). |
| `engine` | CSV (closed list) | no | Subscription filter: subscription / legacy / external. Allowed values: subscription, legacy, external. Max 60 characters; an unknown value is a 400. |
| `subStatus` | CSV (closed list) | no | Subscription filter: Sub status. Allowed values: active, paused, failed, cancelled, completed, expired. Max 400 characters; an unknown value is a 400. |
| `attachedBy` | CSV (closed list) | no | Subscription filter: auto / manual / legacy / optin. Allowed values: auto, manual, legacy, optin. Max 60 characters; an unknown value is a 400. |
| `due` | enum | no | Subscription filter: Next charge: overdue / 24h / 7d. One of: overdue, 24h, 7d. |
| `endCause` | string | no | Subscription filter: End cause. Max 1000 characters. |
| `subCreatedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subCreatedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub created to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subCreatedFrom (400 "subCreatedTo is before subCreatedFrom"). |
| `subEndedFrom` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended from. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. |
| `subEndedTo` | string (ISO 8601 instant or YYYY-MM-DD) | no | Subscription filter: Sub ended to. An ISO instant with any offset (2026-11-01T00:00:00Z, 2026-11-01T00:00:00+02:00) or a day YYYY-MM-DD read in tz; max 40 characters. Must not be before subEndedFrom (400 "subEndedTo is before subEndedFrom"). |
| `schedule` | CSV of UUIDs | no | Schedule filter: Schedule (day) ids. Comma-separated UUIDs; max 4000 characters; a malformed entry is a 400. |
| `scheduleStatus` | CSV (closed list) | no | Schedule filter: Schedule status. Allowed values: scheduled, processing, partial, paused, done, cancelled. Max 400 characters; an unknown value is a 400. |
| `scheduleType` | CSV (closed list) | no | Schedule filter: subscription / auto / manual. Allowed values: subscription, auto, manual. Max 60 characters; an unknown value is a 400. |
| `dayFrom` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day from (YYYY-MM-DD). A day YYYY-MM-DD. |
| `dayTo` | string (YYYY-MM-DD) | no | Schedule filter: Schedule run day to (YYYY-MM-DD). A day YYYY-MM-DD. Must not be before dayFrom (400 "dayTo is before dayFrom"). |
| `entryStatus` | CSV (closed list) | no | Schedule filter: Charge state of the schedule entry. Allowed values: scheduled, processing, rebill_success, declined, blocked, rebill_failed, rejected, cancelled, missed. Max 400 characters; an unknown value is a 400. |
| `entryReason` | string | no | Schedule filter: Charge reason (decline reason of the entry). Max 4000 characters. |
| `refund` | CSV (closed list) | no | Refund filter: Refund event kind. Allowed values: refund, chargeback, rdr, ethoca. Max 100 characters; an unknown value is a 400. |
| `refundBasis` | enum | no | Refund filter: Refund event dated by refund (default) / charge. One of: refund, charge. |
| `refunded` | CSV (closed list) | no | Refund filter: Refunded state flag. Allowed values: true, false. Max 20 characters; an unknown value is a 400. |
| `refundStatus` | CSV (closed list) | no | Refund filter: Refund row status. Allowed values: approved, pending, declined, error, unknown, cancelled. Max 80 characters; an unknown value is a 400. |
| `refundTest` | enum | no | Refund filter: Test refunds: exclude (= absent) / include / only. One of: exclude, include, only. |
| `q` | string | no | Search filter: The page's identity search. Max 200 characters. |

**Response**

```json
{
  "range": {
    "from": "2026-09-19T00:00:00.000Z",
    "to": "2026-09-19T12:44:10.221Z"
  },
  "metrics": {
    "attempts": 2400,
    "matched": 1900,
    "matchedApproved": 1450,
    "genericApproved": 310,
    "byStorefront": [
      {
        "host": "example.com",
        "attempts": 2100,
        "matched": 1850,
        "matchedApproved": 1410,
        "genericApproved": 160,
        "catalogProducts": 42,
        "mids": 6
      },
      {
        "host": "(no bank page)",
        "attempts": 300,
        "matched": 50,
        "matchedApproved": 40,
        "genericApproved": 150,
        "catalogProducts": 0,
        "mids": 2
      }
    ]
  }
}
```

| response field | type | description |
|---|---|---|
| `range` | object | Effective from/to (defaults applied on missing/invalid input). |
| `metrics.attempts` | integer | Gateway ATTEMPTS that reached a MID (v3.9 section 1 ATTEMPT_BASE_SQL: every non-skipped outcome - approved, declined, error, timeout) on LIVE transactions in the range that carried line items - cascade retries count individually. |
| `metrics.matched` | integer | Attempts whose line items came from the storefront catalog (marker _basket=catalog, or the content heuristic for older payloads). |
| `metrics.matchedApproved` | integer | Matched attempts that approved. |
| `metrics.genericApproved` | integer | Non-matched (generic filler) attempts that approved. |
| `metrics.byStorefront` | array | Per host, sorted by attempts desc: {host, attempts, matched, matchedApproved, genericApproved, catalogProducts, mids}. |
| `metrics.byStorefront[].host` | string | Host of the MID's bank_page, or '(no bank page)'. |
| `metrics.byStorefront[].catalogProducts` | integer | Active storefront_products rows whose storefront host equals this host. |
| `metrics.byStorefront[].mids` | integer | Distinct MIDs that attempted under this host. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten()>} for an unknown query parameter or an invalid filter value.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Strict query: every key of the unified filter catalog is accepted (listed in params); an unknown parameter is a 400.
- The unit is a gateway attempt, not a transaction: a cascade of 3 MIDs on one order is 3 attempts.
- `host` comes from the MID's bank_page URL, not from the order's storefrontUrl - a MID without a bank page lands in '(no bank page)'.
- Old payloads (before the `_basket` marker) are classified by content: one line whose description is the filler ('Online Order' on NMI, 'Order' on Convesio, or the order's own description) = generic. A single catalog product at qty 1 priced at the amount counts as matched.
- catalogProducts counts active catalog rows for that host platform-wide (not tenant-filtered) - it tells you whether a catalog exists, not who owns it.
- Attempts without stored line items (request_sent lacking item_description_1 / lineItems) are not counted at all.
- Generic AR = genericApproved / (attempts - matched); matched AR = matchedApproved / matched.
- Filter admission is scoped to the effective account and current permissions. Disabled known affiliates remain reportable. Malformed, missing or foreign affiliate IDs return an error, never an unfiltered response. No store uses canonical immutable standalone order context; missing historical storefront data alone does not mean No store.

##### `GET /v1/integrations/thesupportcare/logs`

**Scope** `integrations.read` - **List recent TheSupportCare sends**

Returns the account's 50 most recent TheSupportCare (customer-service confirmation) hand-offs from the unified send journal: one row per send attempt with its status, latency, error, the customer email and order id that were sent, and the order id TSC answered with. Read-only; no query parameters.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "id": 812345,
      "event_id": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
      "shop_id": "shop_3f2a91c4",
      "mode": "external",
      "status": "sent",
      "status_code": 200,
      "ms": 412,
      "error": null,
      "created_at": "2026-09-19T11:02:44.118Z",
      "email": "jane.doe@example.com",
      "crm_order_id": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
      "total": 49.99,
      "merchant": "Acme Store",
      "test_mode": null,
      "tsc_order_id": "TSC-99812"
    },
    {
      "id": 812101,
      "event_id": "ord_01J8QY0A2B3C4D5E6F7G8H9J0K",
      "shop_id": "shop_3f2a91c4",
      "mode": "external",
      "status": "failed",
      "status_code": 401,
      "ms": 240,
      "error": "http_401",
      "created_at": "2026-09-19T10:41:02.007Z",
      "email": "john@example.com",
      "crm_order_id": "ord_01J8QY0A2B3C4D5E6F7G8H9J0K",
      "total": 19.99,
      "merchant": "Acme Store",
      "test_mode": null,
      "tsc_order_id": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Newest first, max 50, only sends with target "tsc" attributed to the caller's account (unified_send_log.account_email). |
| `rows[].id` | integer | unified_send_log id (openable with GET /v1/unified/sends/:id, super_admin only). |
| `rows[].event_id` | string | The unified event id (= the checkout order id for order.approved). |
| `rows[].mode` | enum: shadow\|external | shadow = computed, nothing sent; external = really sent. |
| `rows[].status` | enum: computed\|sent\|failed\|skipped | Outcome of the attempt. |
| `rows[].status_code` | integer\|null | HTTP status returned by TSC (null when not sent / network error). |
| `rows[].ms` | integer\|null | Round-trip latency in ms. |
| `rows[].error` | string\|null | e.g. 'http_401', 'http_200 success=false', 'timeout', or the skip reason. |
| `rows[].email` | string\|null | Customer email as sent in the payload. |
| `rows[].crm_order_id` | string\|null | Order reference sent to TSC. |
| `rows[].total` | number\|null | Order total AS SENT to TSC - in major units (49.99), NOT cents. |
| `rows[].merchant` | string\|null | Shop name sent as merchant_name. |
| `rows[].test_mode` | string\|null | 'true' (string, from JSON text) when the send was a test_mode payload, else null. |
| `rows[].tsc_order_id` | string\|null | TSC's own order id parsed from its response (data.order_id); null when absent or non-JSON. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- POST /v1/integrations/thesupportcare/test is NOT journaled here - it calls TSC directly without writing a send-log row.
- `total` is in dollars (the payload TSC received), unlike the rest of the API which uses integer cents.
- Only sends attributed to the account appear; sends the platform made with the env fallback key for unattributed orders belong to the platform owner account.
- The 50 rows include shadow-mode "computed" rows (mode shadow) - filter on mode/status client-side if you only want real deliveries.

##### `POST /v1/integrations/thesupportcare/test`

**Scope** `integrations.write` - **Test TheSupportCare credentials**

Posts a test_mode order payload to the account's configured TheSupportCare createOrder endpoint with the saved API key and account id. TSC validates the credentials and the payload but creates no order, sends no email and no SMS. Returns the HTTP outcome, latency and the first 1000 characters of TSC's response. No body is read.

*No parameters.*

**Response**

```json
{
  "ok": true,
  "status": 200,
  "ms": 388,
  "error": null,
  "response": "{\"success\":true,\"data\":{\"order_id\":\"TSC-TEST-4471\",\"test_mode\":true}}",
  "accountId": "example-account",
  "url": "https://tracking.getsupportcare.com/api/createOrder"
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | true only when TSC answered 2xx AND its JSON body has success:true. |
| `status` | integer | HTTP status from TSC; 0 on network error / timeout. |
| `ms` | integer | Round-trip latency in ms. |
| `error` | string\|null | null on success; 'http_<status>' (+ ' success=false' when the body said so) or the fetch error message ('This operation was aborted' on timeout). |
| `response` | string | Raw response body, first 1000 chars ('' on network error). |
| `accountId` | string | The X-Account-Id header value used (config.accountId). |
| `url` | string | The endpoint called (config.apiUrl, else the platform default TSC_API_URL). |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"integrations"} when the account's plan lacks the integrations module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `422` {"error":"Enable TheSupportCare and save an API key + account id first"} when the integration is off or apiKey / accountId is missing.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Wrong credentials are a 200 with ok:false and status 401/403 - always read `ok`, never the HTTP status of this route.
- The integration must be ENABLED, not just saved - a disabled entry is 422 even with valid credentials. Enable it with PUT /v1/integrations/thesupportcare first.
- Payload: test_mode:true, one line item 'Credentials test' at 1.00 USD, email = the caller (the account e-mail for an API key call), crm_order_id 'test-<epoch ms>', send_email true / send_sms false - TSC creates nothing in test mode.
- Bounded by TSC_TIMEOUT_MS (default 30 s) - the request can take that long before answering status 0.
- Not journaled: this test does not appear in GET /v1/integrations/thesupportcare/logs nor in the unified send log.
- It is a POST, so the audit log records an admin mutation ('create' on page Integrations) although nothing is written.

##### `GET /v1/platformpay`

**Scope** `integrations.read` - **Read PlatformPay settings and 24h send stats**

Per-account configuration (each account has its own; not a platform operator route). Read this account's PlatformPay export settings (the secret is replaced by secret_key_set) and the rolling last-24-hours send counters.

*No parameters.*

**Response**

```json
{
  "settings": {
    "owner_email": "owner@example.com",
    "enabled": true,
    "send_pct": 100,
    "success_enabled": true,
    "failed_enabled": true,
    "url": "https://platformpay.example.com/api3/order/import_order.php",
    "user_id": "1001",
    "secret_key_set": true,
    "updated_at": "2026-11-20T17:02:11.884Z",
    "updated_by": "owner@example.com"
  },
  "stats": {
    "sent_24h": 412,
    "ok_24h": 389,
    "failed_24h": 23
  }
}
```

| response field | type | description |
|---|---|---|
| `settings` | object\|null | The account's settings, or null until its first save (not configured means disabled). |
| `settings.owner_email` | string | The account the settings belong to. |
| `settings.enabled` | boolean | Master switch. When false nothing is forwarded and nothing is logged. |
| `settings.send_pct` | integer 0-100 | Percentage of eligible orders forwarded (random sampling per order). A percent, not money. |
| `settings.success_enabled` | boolean | Forward approved charges. |
| `settings.failed_enabled` | boolean | Forward declined charges. |
| `settings.url` | string | PlatformPay import endpoint. The sender POSTs the order both as the query string and as a form body to this URL. |
| `settings.user_id` | string | PlatformPay account id sent as user_id. |
| `settings.secret_key_set` | boolean | Whether a secret_key is stored. The value itself is only returned by GET /v1/platformpay/credentials. |
| `settings.updated_at` | string (ISO 8601) | Last save that changed at least one field. |
| `settings.updated_by` | string\|null | E-mail of whoever made that save (the account owner e-mail for a key). |
| `stats.sent_24h` | integer | Send attempts logged in the last 24 hours (skipped orders are never logged). |
| `stats.ok_24h` | integer | Attempts PlatformPay acknowledged with success = 1 (dry-run rows count here). |
| `stats.failed_24h` | integer | Attempts whose ok is not true (false or null). |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `integrations`) when the plan lacks the integrations module. `No account` when the request carries no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Sends recorded before per-account settings existed (no owner) are counted only for the platform owner account.
- Only attempts are logged. Orders skipped by policy (switch off, outcome toggle off, sampling, rebills, wallet charges, no card data, or a card already forwarded once for this account) leave no row.
- In dry-run mode rows are written with ok = true, http_status null, duration_ms 0 and error `dry-run (not sent)` although nothing left the server.
- stats is a fixed rolling 24-hour window with no parameter. sent_24h always equals ok_24h + failed_24h.
- enabled = true with send_pct = 0 (or both outcome toggles off) is accepted and silently forwards nothing.

##### `GET /v1/platformpay/credentials`

**Scope** `integrations.write` - **Read the stored PlatformPay secret_key**

Per-account configuration (each account has its own; not a platform operator route). Reveal the stored PlatformPay secret_key in clear ("" when none is stored). The general read and the settings save only return secret_key_set.

*No parameters.*

**Response**

```json
{
  "secret_key": "pp_test_example_secret"
}
```

| response field | type | description |
|---|---|---|
| `secret_key` | string | The stored value, "" when unset or never configured. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"integrations.write"}: the key lacks integrations.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- The answer carries a live secret: it is sent with `cache-control: no-store` and `pragma: no-cache`. Never log or cache it.
- Each call that returns a stored value writes one audit row (action `view_secret`, the field name, never the value). Nothing stored means no audit row.

##### `GET /v1/platformpay/sends`

**Scope** `integrations.read` - **List PlatformPay send attempts**

Per-account configuration (each account has its own; not a platform operator route). Page through this account's PlatformPay send log, newest first, with a total for pagination.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | Rows per page, 1-10000. Coerced from the query string; out of range is a 400, not clamped. |
| `offset` | integer; default `0` | no | Rows to skip, 0 or more. |

**Response**

```json
{
  "sends": [
    {
      "id": "6f1c2d9e-40ab-4f77-9d31-2b5a8c0e7d14",
      "created_at": "2026-11-20T09:14:52.301Z",
      "order_id": "ORD-10001",
      "transaction_id": "11111111-1111-4111-8111-111111111111",
      "sent_as": "success",
      "ok": true,
      "http_status": 200,
      "error": null,
      "duration_ms": 412
    },
    {
      "id": "a41b77e0-9c3d-4f18-b6aa-1d0e5c9f2743",
      "created_at": "2026-11-20T09:12:03.998Z",
      "order_id": "ORD-10000",
      "transaction_id": null,
      "sent_as": "declined",
      "ok": false,
      "http_status": 200,
      "error": "platformpay success!=1 (http 200): {\"success\":0,\"message\":\"invalid secret_key\"}",
      "duration_ms": 233
    }
  ],
  "total": 1284
}
```

| response field | type | description |
|---|---|---|
| `sends[].id` | uuid | Log row id. |
| `sends[].created_at` | string (ISO 8601) | When the attempt finished. |
| `sends[].order_id` | string\|null | Order id forwarded as custom1. |
| `sends[].transaction_id` | uuid\|null | Transaction id when known (best effort). |
| `sends[].sent_as` | success \| declined | The outcome reported to PlatformPay. |
| `sends[].ok` | boolean\|null | Only true means delivered. |
| `sends[].http_status` | integer\|null | Final HTTP status after up to 10 redirects; null when the request failed before a response or on dry-run rows. |
| `sends[].error` | string\|null | Failure detail, or `dry-run (not sent)`. |
| `sends[].duration_ms` | integer\|null | Duration of the attempt; 0 on dry-run rows. |
| `total` | integer | Row count of the log for this account (see gotchas). |

**Errors**

- `400` `Invalid` with `details`: limit outside 1-10000, a negative or non-integer offset.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `integrations`) when the plan lacks the integrations module. `No account` when the request carries no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- total is count(*) over the returned page: an offset past the last row answers sends [] and total 0. Read total from a page that has rows.
- Sends recorded before per-account settings existed (no owner) are counted only for the platform owner account.
- Only attempts are logged. Orders skipped by policy (switch off, outcome toggle off, sampling, rebills, wallet charges, no card data, or a card already forwarded once for this account) leave no row.
- In dry-run mode rows are written with ok = true, http_status null, duration_ms 0 and error `dry-run (not sent)` although nothing left the server.
- ok is true only when PlatformPay answered success = 1; ok false often comes with http_status 200 (the refusal is in the body). error is cut to 500 characters of the upstream body and 2000 characters overall.
- Ordering is created_at descending with no tie-breaker; deep offsets over live traffic can repeat or skip rows. The card hash is never returned.

##### `PATCH /v1/platformpay/settings`

**Scope** `integrations.write` - **Update PlatformPay settings**

Per-account configuration (each account has its own; not a platform operator route). Partially update this account's PlatformPay export settings (created on first save with the column defaults), then return the refreshed settings and the 24h stats.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | no | Master switch. Also mirrored into the account's integrations list (provider platformpay). Omit to keep. |
| `send_pct` | integer | no | Whole number 0-100: percentage of eligible orders to forward. Out of range or a fraction is a 400. Omit to keep. |
| `success_enabled` | boolean | no | Forward approved charges. Omit to keep. |
| `failed_enabled` | boolean | no | Forward declined charges. Omit to keep. |
| `url` | string | no | Absolute URL, at most 512 characters. Omit to keep. |
| `user_id` | string | no | PlatformPay account id, 1-64 characters. Omit to keep. |
| `secret_key` | string | no | Server-to-server secret, at most 256 characters. "" erases the stored secret. Omit to keep. |

**Request body**

```json
{
  "enabled": true,
  "send_pct": 25,
  "success_enabled": true,
  "failed_enabled": false
}
```

**Response**

```json
{
  "settings": {
    "owner_email": "owner@example.com",
    "enabled": true,
    "send_pct": 25,
    "success_enabled": true,
    "failed_enabled": false,
    "url": "https://platformpay.example.com/api3/order/import_order.php",
    "user_id": "1001",
    "secret_key_set": true,
    "updated_at": "2026-11-20T17:02:11.884Z",
    "updated_by": "owner@example.com"
  },
  "stats": {
    "sent_24h": 412,
    "ok_24h": 389,
    "failed_24h": 23
  }
}
```

| response field | type | description |
|---|---|---|
| `settings` | object\|null | The account's settings, or null until its first save (not configured means disabled). |
| `settings.secret_key_set` | boolean | Whether a secret_key is stored. The value itself is only returned by GET /v1/platformpay/credentials. |
| `settings.updated_at` | string (ISO 8601) | Last save that changed at least one field. |
| `settings.updated_by` | string\|null | E-mail of whoever made that save (the account owner e-mail for a key). |
| `stats` | object | The same 24-hour counters as the GET; they say nothing about this save. |

**Errors**

- `400` `Invalid` with `details` (zod flatten): a wrong type, send_pct not an integer 0-100, url not absolute or over 512, empty or over-long user_id, secret_key over 256, or no JSON body at all.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `integrations`) when the plan lacks the integrations module. `No account` when the request carries no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Unknown keys are silently dropped (the schema is not strict). A body with only misspelled keys, or {}, answers 200 with nothing changed and updated_at untouched: compare the returned settings with what you meant to write.
- secret_key has no minimum: "" passes and erases the secret, after which PlatformPay rejects every forward.
- A save clears the 30-second settings cache, so the change applies to the next charge.
- The response never echoes the secret (secret_key_set only).

##### `GET /v1/storefronts`

**Scope** `routing.read` - **List storefront catalogs**

List the bank-page product catalogs this account can manage, each with its active product count and the number of this account's MIDs whose bank page resolves to that host.

*No parameters.*

**Response**

```json
{
  "storefronts": [
    {
      "id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "host": "shop.example.com",
      "name": "Example Shop",
      "created_at": "2026-11-14T09:12:44.318Z",
      "product_count": 2,
      "gateway_count": 3
    },
    {
      "id": "8c21b6d0-9e5f-4a17-bb3c-1d740e9af256",
      "host": "outdoor.example.com",
      "name": null,
      "created_at": "2026-11-20T16:03:07.902Z",
      "product_count": 0,
      "gateway_count": 1
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `storefronts` | object[] | Catalogs visible to this account, sorted by host. |
| `storefronts[].id` | uuid | Storefront id used by the other storefront routes. |
| `storefronts[].host` | string | Normalised host: no scheme, path or leading `wallet.`, lowercased. |
| `storefronts[].name` | string\|null | Optional label. |
| `storefronts[].created_at` | string (ISO 8601) | Creation time. |
| `storefronts[].product_count` | integer | Active products. |
| `storefronts[].gateway_count` | integer | This account's MIDs billing under this host. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- This is the MID bank-page product-description catalog (the products described to the gateway), not an ecommerce store. Build sellable stores and products with the /v1/checkouts routes.
- A catalog is used at charge time only when the account's Smart product matching integration is on (on by default) and the MID's own product matching override is true (the default).
- No pagination, filter or single-item read: list and match the normalised `host` client-side. An account with none gets [].
- product_count counts active products only; GET /v1/storefronts/:id/products also returns inactive ones.
- gateway_count counts this account's MIDs whose bank page (scheme, path and a leading `wallet.` stripped, lowercased) equals the host, whatever their matching override.
- A MID creation or bank-page change creates an empty catalog for its host automatically.
- Response names are snake_case (created_at, price_cents) while writes use camelCase (priceCents).

##### `POST /v1/storefronts`

**Scope** `routing.write` - **Create a storefront catalog for a host**

Create an empty catalog for a bank-page host, owned by this account. Answers 201.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `host` | string | **yes** | Bank-page host, 3-256 characters as sent (checked before normalisation). Stored normalised: trimmed, scheme removed, everything after the first "/" removed, a leading `wallet.` removed, lowercased. |
| `name` | string | no | Label, at most 128 characters; trimmed, "" stored as null. |

**Request body**

```json
{
  "host": "https://wallet.shop.example.com/checkout",
  "name": "Example Shop"
}
```

**Response** `201`

```json
{
  "storefront": {
    "id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
    "host": "shop.example.com",
    "name": "Example Shop",
    "created_at": "2026-11-14T09:12:44.318Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `storefront.id` | uuid | New storefront id. |
| `storefront.host` | string | Normalised host actually stored. |
| `storefront.name` | string\|null | Trimmed label or null. |
| `storefront.created_at` | string (ISO 8601) | Creation time. |

**Errors**

- `400` `Invalid` with `details` (zod flatten) for a missing, short or long host or a long name; `A host is required, e.g. kids-active.com` when the host normalises to an empty string.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module. `No account` when the request carries no account.
- `409` `A storefront for this URL already exists.` (the host is unique across the platform).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Read storefront.host back: the stored host is the normalised one.
- A new catalog has no products: add them with PUT /v1/storefronts/:id/products.
- A catalog is used at charge time only when the account's Smart product matching integration is on (on by default) and the MID's own product matching override is true (the default).
- Another account's catalog answers 404. Host uniqueness is global: a 409 on create does not give access to the other catalog.

##### `PATCH /v1/storefronts/:id`

**Scope** `routing.write` - **Rename a storefront or change its host**

Update the label and/or the host of a visible catalog. Changing the host points the whole product list at the MIDs of the new host.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Storefront id from GET /v1/storefronts. A non-UUID is a 400, not a 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `host` | string | no | New host, 3-256 characters as sent, normalised as on create. Omit to keep. |
| `name` | string | no | New label, at most 128 characters; "" clears it to null. null is rejected. Omit to keep. |

**Request body**

```json
{
  "name": "Example Shop EU"
}
```

**Response**

```json
{
  "storefront": {
    "id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
    "host": "shop.example.com",
    "name": "Example Shop EU",
    "created_at": "2026-11-14T09:12:44.318Z"
  }
}
```

| response field | type | description |
|---|---|---|
| `storefront.id` | uuid | Unchanged id. |
| `storefront.host` | string | Normalised host now stored. |
| `storefront.name` | string\|null | Label or null. |
| `storefront.created_at` | string (ISO 8601) | Original creation time. |

**Errors**

- `400` `Invalid` with `details` for a bad field; `A value has an invalid format.` when :id is not a UUID. `A host is required.` when the host normalises to empty; `No fields to update` when neither host nor name is sent.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module.
- `404` `Not found` when the catalog does not exist or is not visible to this account.
- `409` `A record with these details already exists.` when the new host already has a catalog.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Send only what changes; unknown keys are dropped.
- The 409 text differs from the create route: match on the status code.
- The whole catalog cache is cleared so the change applies to the next charge.
- Another account's catalog answers 404. Host uniqueness is global: a 409 on create does not give access to the other catalog.

##### `DELETE /v1/storefronts/:id`

**Scope** `routing.write` - **Delete a storefront and its catalog**

Permanently delete a visible catalog and all its products. MIDs billing under that host fall back to the generic charge description from the next charge.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Storefront id from GET /v1/storefronts. A non-UUID is a 400, not a 404. |

**Response** `204`

```json
204 No Content (empty body)
```

| response field | type | description |
|---|---|---|
| `(none)` | void | 204 No Content with an empty body. Any client that unconditionally JSON-parses the response will throw on success. |

**Errors**

- `400` `A value has an invalid format.` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module.
- `404` `Not found` when the catalog does not exist, is not visible to this account, or was already deleted.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Success is 204 with an empty body.
- No undo: products are deleted with the catalog. To stop matching reversibly, turn off the MID's product matching override or the account's Smart product matching integration instead.
- Deletion is not blocked by MIDs still using the host; check gateway_count first.

##### `GET /v1/storefronts/:id/products`

**Scope** `routing.read` - **List a storefront's products**

Read the whole product list of one catalog, active and inactive, in stored order.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Storefront id from GET /v1/storefronts. A non-UUID is a 400, not a 404. |

**Response**

```json
{
  "products": [
    {
      "id": "a1d47c68-0f32-4b95-8e77-2c9b5d130ae4",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Training cones set",
      "price_cents": 1499,
      "active": true,
      "position": 0
    },
    {
      "id": "c5b93e11-8a20-47f6-90dd-6e14b7c02f89",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Shin guards, pair",
      "price_cents": 2250,
      "active": true,
      "position": 1
    },
    {
      "id": "7e08f4a3-15cd-4b62-a9f1-3308d5be7c40",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Mesh bib",
      "price_cents": 899,
      "active": false,
      "position": 2
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `products` | object[] | Rows sorted by position, then price_cents. |
| `products[].id` | uuid | Row id. Not stable: every replace deletes and re-inserts the rows. |
| `products[].storefront_id` | uuid | The storefront id. |
| `products[].title` | string | Line description sent to the gateway when the product is in a basket. |
| `products[].price_cents` | integer | Unit price in integer cents (written as priceCents). |
| `products[].active` | boolean | Inactive products are kept and returned but never used at charge time. |
| `products[].position` | integer | Zero-based order from the last replace; read-only. |

**Errors**

- `400` `A value has an invalid format.` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module.
- `404` `Not found` when the catalog does not exist or is not visible to this account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Inactive products are included; filter on active to get what the matcher uses.
- price_cents is integer cents: 1499 is 14.99.
- Product ids change on every replace; never keep them.
- Another account's catalog answers 404. Host uniqueness is global: a 409 on create does not give access to the other catalog.

##### `PUT /v1/storefronts/:id/products`

**Scope** `routing.write` - **Replace a storefront's product list**

Replace the whole catalog of a visible storefront in one transaction: existing rows are deleted and the sent list is inserted in order. This is the only way to add, edit, reorder, deactivate or remove products.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Storefront id from GET /v1/storefronts. A non-UUID is a 400, not a 404. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `products` | object[] | **yes** | The complete new list, at most 500 items. [] empties the catalog. Array order becomes position. |
| `products[].title` | string | **yes** | 1-256 characters; trimmed and cut to 256 when stored. |
| `products[].priceCents` | integer | **yes** | Unit price in integer cents, 1-10000000. |
| `products[].active` | boolean; default `true` | no | false keeps the row but excludes it from matching. |

**Request body**

```json
{
  "products": [
    {
      "title": "Training cones set",
      "priceCents": 1499
    },
    {
      "title": "Shin guards, pair",
      "priceCents": 2250,
      "active": true
    },
    {
      "title": "Mesh bib",
      "priceCents": 899,
      "active": false
    }
  ]
}
```

**Response**

```json
{
  "products": [
    {
      "id": "a1d47c68-0f32-4b95-8e77-2c9b5d130ae4",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Training cones set",
      "price_cents": 1499,
      "active": true,
      "position": 0
    },
    {
      "id": "c5b93e11-8a20-47f6-90dd-6e14b7c02f89",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Shin guards, pair",
      "price_cents": 2250,
      "active": true,
      "position": 1
    },
    {
      "id": "7e08f4a3-15cd-4b62-a9f1-3308d5be7c40",
      "storefront_id": "3f9a1c2e-7b44-4d81-9c0a-5e6d2f8b1a33",
      "title": "Mesh bib",
      "price_cents": 899,
      "active": false,
      "position": 2
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `products` | object[] | The catalog re-read after the replace, same shape as GET. |
| `products[].id` | uuid | Row id. Not stable: every replace deletes and re-inserts the rows. |
| `products[].storefront_id` | uuid | The storefront id. |
| `products[].title` | string | Line description sent to the gateway when the product is in a basket. |
| `products[].price_cents` | integer | Unit price in integer cents (written as priceCents). |
| `products[].active` | boolean | Inactive products are kept and returned but never used at charge time. |
| `products[].position` | integer | Zero-based order from the last replace; read-only. |

**Errors**

- `400` `Invalid` with `details` (zod flatten): products missing or over 500 items, a bad title, or priceCents not a positive integer up to 10000000; `A value has an invalid format.` when :id is not a UUID.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route; `Your subscription does not include this tool.` (code `subscription_module_required`, module `stores`) when the plan lacks the stores module.
- `404` `Not found` (checked before any write).
- `504` The replace exceeded its 10-second statement timeout; nothing changed.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Whole-list replace: anything omitted is deleted. To change one price, read the list, edit it, send it all back. Unknown keys such as id or position are dropped.
- Do not echo the response back: it uses price_cents, the request needs priceCents.
- Matching at charge time uses active products only and always reconciles to the charge amount: an exact basket of at most 10 units first; else the fewest-unit basket just under the amount plus one `Processing & handling` line (at most 30 percent of the amount and 2500 cents); else the single product with the closest price billed at the amount. Amounts above 200000 cents get no basket (generic line).
- Products at the same price are interchangeable; which title is billed is chosen deterministically from the order id (rebills rotate).
- Replaces of the same catalog are serialized: one waiting more than 2 seconds for the lock fails with a 500 and changes nothing.
- A catalog is used at charge time only when the account's Smart product matching integration is on (on by default) and the MID's own product matching override is true (the default).

#### Monitoring and alerts

Uptime monitoring of the store domains, alert destinations, and the reconciliation of gateway records.

- The monitor statuses (Active, Muted, Unverified, Integration disabled) and "N domains down" are derived in the browser from `GET /v1/uptime/monitors` and `GET /v1/uptime/events`.

##### `GET /v1/reconciliation`

**Scope** `operations.read` - **Get reconciliation gaps**

Returns the latest stored snapshot of each reconciliation check of the caller's account: stuck_pending (charges pending for more than 30 minutes, 3-D Secure parks excluded), parked_expired (3-D Secure parks still present more than 1 hour after their session expired, meaning the hourly sweep is not running), overdue_recheck (ConvesioPay rechecks overdue by more than 30 minutes), approved_no_mid (approved card charges of the last 7 days with no final gateway recorded, wallets excluded), refund_not_flagged (transactions with a successful refund in the last 7 days whose refunded amount is below the sum of their successful refunds). Read-only: it does not re-run the checks. Snapshots are written hourly by the background job and on demand by POST /v1/reconciliation/run.

*No parameters.*

**Response**

```json
{
  "gaps": [
    {
      "gap_type": "stuck_pending",
      "label": "Charges stuck in pending > 30 min (never finalized)",
      "count": 2,
      "sample": [
        "ORD-100482",
        "ORD-100455"
      ],
      "checked_at": "2026-11-20T14:00:03.412Z"
    },
    {
      "gap_type": "approved_no_mid",
      "label": "Approved CARD charges with no final MID recorded (last 7d)",
      "count": 1,
      "sample": [
        "ORD-100377"
      ],
      "checked_at": "2026-11-20T14:00:03.412Z"
    },
    {
      "gap_type": "overdue_recheck",
      "label": "ConvesioPay rechecks overdue > 30 min (should have fired/cleared)",
      "count": 0,
      "sample": [],
      "checked_at": "2026-11-20T14:00:03.412Z"
    },
    {
      "gap_type": "parked_expired",
      "label": "3DS parks unswept > 1 h after session expiry (the hourly sweep is not running)",
      "count": 0,
      "sample": [],
      "checked_at": "2026-11-20T14:00:03.412Z"
    },
    {
      "gap_type": "refund_not_flagged",
      "label": "Successful refunds not reflected on their transaction (last 7d)",
      "count": 0,
      "sample": [],
      "checked_at": ""
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `gaps` | object[] | One entry per check: the latest stored snapshot of each type, plus a zero entry for every check never run for the account. Sorted by count descending, so key on gap_type, never on position. |
| `gaps[].gap_type` | string | 'stuck_pending' \| 'parked_expired' \| 'overdue_recheck' \| 'approved_no_mid' \| 'refund_not_flagged' (a stored type that no longer has a check is returned with its slug as label). |
| `gaps[].label` | string | Human description of the check, from the server constants (not stored). |
| `gaps[].count` | integer | Number of the account's offending transactions at snapshot time. |
| `gaps[].sample` | string[] | Up to 5 order_id values of offending transactions (the account's own only), newest first (overdue_recheck: the most overdue first). |
| `gaps[].checked_at` | string | ISO 8601 time of the snapshot, or the empty string "" for a check never run for the account. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} when the read fails.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.
- `504` {"error":"The request took too long and was cancelled - narrow the range and retry."} when the 5-second read budget is exceeded.

**Gotchas**

- No parameters: no filter, no date range, no pagination.
- Up to one hour stale: it reads the last snapshot. Call POST /v1/reconciliation/run first for live numbers.
- Sorted by count descending, so the array order changes between calls. Key on gap_type.
- checked_at is the empty string "" for a check never run for the account (count 0, sample []). Do not parse it as a date without checking.
- Only the latest snapshot per check is exposed; the 30 days of history kept in the table are not readable through the API.
- The read has a 5-second budget; beyond it the answer is 504.
- A count above 0 is an inconsistency to investigate, not something this route fixes: it never modifies transactions or refunds.

##### `POST /v1/reconciliation/run`

**Scope** `operations.write` - **Run reconciliation now**

Runs the five reconciliation checks of the caller's account now (stuck_pending (charges pending for more than 30 minutes, 3-D Secure parks excluded), parked_expired (3-D Secure parks still present more than 1 hour after their session expired, meaning the hourly sweep is not running), overdue_recheck (ConvesioPay rechecks overdue by more than 30 minutes), approved_no_mid (approved card charges of the last 7 days with no final gateway recorded, wallets excluded), refund_not_flagged (transactions with a successful refund in the last 7 days whose refunded amount is below the sum of their successful refunds)), stores the five results as one atomic snapshot and returns them. The same routine runs hourly for every account; use this route for an on-demand refresh. It measures only: it never modifies transactions or refunds.

*No parameters.*

**Response**

```json
{
  "gaps": [
    {
      "gap_type": "stuck_pending",
      "label": "Charges stuck in pending > 30 min (never finalized)",
      "count": 2,
      "sample": [
        "ORD-100482",
        "ORD-100455"
      ],
      "checked_at": "2026-11-20T14:37:11.908Z"
    },
    {
      "gap_type": "parked_expired",
      "label": "3DS parks unswept > 1 h after session expiry (the hourly sweep is not running)",
      "count": 0,
      "sample": [],
      "checked_at": "2026-11-20T14:37:11.908Z"
    },
    {
      "gap_type": "overdue_recheck",
      "label": "ConvesioPay rechecks overdue > 30 min (should have fired/cleared)",
      "count": 0,
      "sample": [],
      "checked_at": "2026-11-20T14:37:11.908Z"
    },
    {
      "gap_type": "approved_no_mid",
      "label": "Approved CARD charges with no final MID recorded (last 7d)",
      "count": 1,
      "sample": [
        "ORD-100377"
      ],
      "checked_at": "2026-11-20T14:37:11.908Z"
    },
    {
      "gap_type": "refund_not_flagged",
      "label": "Successful refunds not reflected on their transaction (last 7d)",
      "count": 0,
      "sample": [],
      "checked_at": "2026-11-20T14:37:11.908Z"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `gaps` | object[] | Exactly 5 entries in the fixed check order: stuck_pending, parked_expired, overdue_recheck, approved_no_mid, refund_not_flagged. |
| `gaps[].gap_type` | string | 'stuck_pending' \| 'parked_expired' \| 'overdue_recheck' \| 'approved_no_mid' \| 'refund_not_flagged'. |
| `gaps[].label` | string | Human description of the check, from the server constants (not stored). |
| `gaps[].count` | integer | Number of the account's offending transactions at snapshot time. |
| `gaps[].sample` | string[] | Up to 5 order_id values of offending transactions (the account's own only), newest first (overdue_recheck: the most overdue first). |
| `gaps[].checked_at` | string | ISO 8601 time of the snapshot written by this run; the same value on all 5 entries. |

**Errors**

- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `409` {"error":"Reconciliation already running"} when another run holds the account lock.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry. {"error":"Reconciliation could not complete; previous snapshots remain available"} when the run fails, times out or the run queue is full.

**Gotchas**

- No body is read and there are no options: every call runs all five checks.
- Atomic: either all five results are saved as the new snapshot, or none is and the previous snapshot stays the one GET /v1/reconciliation returns.
- Concurrent runs for the same account on the same server instance share one computation; a run already holding the account lock (another instance) makes this call answer 409. Retry after a few seconds.
- Synchronous with a 25-second budget (20-second statement timeout). On a very large account it can fail with 503 and leave the previous snapshot in place.
- Each successful run appends five rows; snapshots older than 30 days are pruned by the background job. Safe to retry, but not a no-op.
- The fixed check order here differs from the count-descending order of GET /v1/reconciliation. Key on gap_type.
- approved_no_mid and refund_not_flagged only look at the last 7 days; stuck_pending has no lower time bound.

##### `GET /v1/uptime/contacts`

**Scope** `monitoring.read` - **List alert destinations**

The account's uptime alert destinations (Telegram, e-mail, SMS) and the state of the account Telegram integration.

*No parameters.*

**Response**

```json
{
  "contacts": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "owner_email": "owner@example.com",
      "kind": "email",
      "value": "oncall@example.com",
      "label": "On call",
      "enabled": true,
      "verified_at": null,
      "on_down": true,
      "on_up": true,
      "on_ssl": true,
      "created_at": "2026-11-20T12:00:00.000Z",
      "integration_id": null,
      "integration_status": null
    }
  ],
  "telegramIntegration": {
    "id": "account-telegram",
    "name": "Account Telegram",
    "configured": true,
    "enabled": true,
    "available": true,
    "status": "ready",
    "chatId": "-1001234567890"
  }
}
```

| response field | type | description |
|---|---|---|
| `contacts[]` | object[] | Destinations by kind then creation: same fields as contact in POST /v1/uptime/contacts. |
| `telegramIntegration` | object | id (account-telegram), name, configured, enabled, available, status (ready\|not_configured\|disabled), chatId. |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Only enabled AND verified destinations subscribed to the event kind receive alerts.

##### `POST /v1/uptime/contacts`

**Scope** `monitoring.write` - **Add an alert destination**

Add a destination, or update the one with the same kind and value (re-enabling it). An e-mail, SMS or Telegram chat destination is created unverified and a one-time code is sent to it at once (through the account's own senders); it receives no alert until confirmed with POST /v1/uptime/contacts/verify. Selecting the account Telegram integration (kind telegram + integration_id account-telegram) needs no code.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string (telegram\|email\|sms) | **yes** | Destination kind. |
| `integration_id` | string (account-telegram) | no | Only with kind telegram and without value: bind the account Telegram integration. |
| `value` | string (3..320) | no | Required unless integration_id: e-mail address, SMS number in E.164 (+ and 8 to 15 digits), or numeric Telegram chat id. |
| `label` | string (max 120) | no | Display label. |
| `on_down` | boolean; default `true` | no | Alert when a monitor goes down. |
| `on_up` | boolean; default `true` | no | Alert when it recovers. |
| `on_ssl` | boolean; default `true` | no | Alert on certificate problems. |

**Request body**

```json
{
  "kind": "email",
  "value": "oncall@example.com",
  "label": "On call"
}
```

**Response**

```json
{
  "contact": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "email",
    "value": "oncall@example.com",
    "label": "On call",
    "enabled": true,
    "verified_at": null,
    "on_down": true,
    "on_up": true,
    "on_ssl": true,
    "created_at": "2026-11-20T12:00:00.000Z",
    "integration_id": null,
    "integration_status": null
  },
  "verification": {
    "ok": true,
    "required": true
  }
}
```

| response field | type | description |
|---|---|---|
| `contact` | object | id, owner_email, kind (telegram\|email\|sms), value (for the account Telegram integration: its chat id), label, enabled, verified_at, on_down, on_up, on_ssl, created_at, integration_id (account-telegram or null), integration_status (ready\|not_configured\|disabled for telegram, else null). |
| `verification` | object | {ok, error?, required}: required false for an already verified or integration destination; ok false with error (for example "no e-mail provider configured on the account") when the code could not be sent. |

**Errors**

- `400` not a valid <kind> destination.
- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the strict body fails validation (an unknown key, a missing value, both value and integration_id, or kind not telegram, email or sms).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `409` The account Telegram integration is not configured; or The account Telegram integration is disabled.
- `500` {"error":"could not save the contact"} (the insert returned no row).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- The verification send uses the account's own e-mail or SMS sender and may be billed.

##### `PATCH /v1/uptime/contacts/:id`

**Scope** `monitoring.write` - **Update an alert destination**

Change the label, enabled state or event subscriptions of a destination. The recipient, binding and verification cannot change here.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Destination id. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `enabled` | boolean | no | Enable or disable. |
| `label` | string (max 120) | no | Display label. |
| `on_down` | boolean | no | Down alerts. |
| `on_up` | boolean | no | Recovery alerts. |
| `on_ssl` | boolean | no | Certificate alerts. |

**Request body**

```json
{
  "enabled": false
}
```

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID or the strict body fails validation (an empty body, with the message "Choose a setting to update", or an unknown key).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `404` not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- At least one field is required.

##### `DELETE /v1/uptime/contacts/:id`

**Scope** `monitoring.write` - **Delete an alert destination**

Delete a destination of the account.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Destination id. |

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `404` not found.
- `503` Authentication scope is temporarily unavailable.

##### `POST /v1/uptime/contacts/:id/resend`

**Scope** `monitoring.write` - **Resend a destination code**

Send the pending one-time code of an unverified destination again.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Destination id. |

**Response**

```json
{
  "verification": {
    "ok": true
  }
}
```

| response field | type | description |
|---|---|---|
| `verification` | object | {ok, error?}; error "nothing to verify" when the destination is verified, unknown or of another account. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- An unknown id answers 200 with ok false, not 404.

##### `POST /v1/uptime/contacts/test`

**Scope** `monitoring.write` - **Send a test alert to a destination**

Send one real test alert to a destination as typed (saved or not) through the account's own senders. Creates, verifies and enables nothing.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `kind` | string (telegram\|email\|sms) | **yes** | Destination kind. |
| `value` | string (max 320; 3..320 for email and sms) | no | Recipient; required for email and sms. For telegram, omitted or empty uses the account Telegram integration chat. |

**Request body**

```json
{
  "kind": "sms",
  "value": "+15555550100"
}
```

**Response**

```json
{
  "test": {
    "ok": false,
    "error": "No SMS provider configured on the account"
  }
}
```

| response field | type | description |
|---|---|---|
| `test` | object | {ok, error?}: a refused send is HTTP 200 with ok false. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the strict body fails validation (an unknown key, kind not telegram, email or sms, or a missing or too short value for email or sms).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- It spends the account senders (a billed SMS segment, an e-mail, a Telegram message).

##### `POST /v1/uptime/contacts/verify`

**Scope** `monitoring.write` - **Verify a destination**

Confirm an unverified destination with the code that was sent to it.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string (8..128) | **yes** | The one-time code received by the destination. |
| `contact_id` | uuid | no | When given, the code must belong to this destination. |

**Request body**

```json
{
  "token": "Xy7k2Qp9Lm3Ns8Vt1Rw6Zb4Hc0Jd5Fg",
  "contact_id": "11111111-1111-4111-8111-111111111111"
}
```

**Response**

```json
{
  "contact": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "email",
    "value": "oncall@example.com",
    "label": "On call",
    "enabled": true,
    "verified_at": "2026-11-20T12:05:00.000Z",
    "on_down": true,
    "on_up": true,
    "on_ssl": true,
    "created_at": "2026-11-20T12:00:00.000Z",
    "integration_id": null,
    "integration_status": null
  }
}
```

| response field | type | description |
|---|---|---|
| `contact` | object | id, owner_email, kind (telegram\|email\|sms), value (for the account Telegram integration: its chat id), label, enabled, verified_at, on_down, on_up, on_ssl, created_at, integration_id (account-telegram or null), integration_status (ready\|not_configured\|disabled for telegram, else null). |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the strict body fails validation (an unknown key, token not 8 to 128 characters, contact_id not a UUID).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `404` unknown or already used code.
- `503` Authentication scope is temporarily unavailable.

##### `GET /v1/uptime/events`

**Scope** `monitoring.read` - **List uptime events**

The latest alerts the vendor reported for the account's monitors, recorded before any notification, with how many destinations received each.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer (1..500); default `50` | no | Events to return, newest received first. |
| `all` | string (true) | no | Platform super admin only: every account. Ignored for everyone else. |

**Response**

```json
{
  "events": [
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "monitor_id": "11111111-1111-4111-8111-111111111111",
      "host": "shop.example.com",
      "kind": "store",
      "alert_type": "down",
      "detail": "Connection Timeout",
      "duration_s": null,
      "occurred_at": "2026-11-01T04:27:00.000Z",
      "received_at": "2026-11-01T04:27:05.000Z",
      "notified": 2,
      "notify_error": null
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `events[]` | object[] | id, monitor_id, host, kind, alert_type (down\|up\|ssl...), detail, duration_s, occurred_at, received_at, notified (destinations reached), notify_error (sanitised per channel, for example "sms: Delivery failed"). |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when limit is not an integer from 1 to 500.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A retried vendor callback lands on the same event, so one outage never appears or notifies twice.

##### `GET /v1/uptime/monitors`

**Scope** `monitoring.read` - **List uptime monitors**

The account's uptime monitors (one per host it serves: store, checkout or infrastructure), created with the store and reconciled every 15 minutes, with their last known state.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `all` | string (true) | no | Platform super admin only: every account. Ignored for everyone else. |

**Response**

```json
{
  "monitors": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "owner_email": "owner@example.com",
      "shop_id": "22222222-2222-4222-8222-222222222222",
      "host": "shop.example.com",
      "url": "https://shop.example.com/",
      "kind": "store",
      "provider_monitor_id": "804298298",
      "keyword": "site-header",
      "interval_s": 300,
      "enabled": true,
      "last_state": "up",
      "last_state_at": "2026-11-20T04:30:00.000Z",
      "synced_at": "2026-11-20T10:15:00.000Z",
      "last_error": null,
      "created_at": "2026-11-01T12:00:00.000Z"
    }
  ],
  "configured": true,
  "callbackConfigured": true
}
```

| response field | type | description |
|---|---|---|
| `monitors[]` | object[] | id, owner_email, shop_id, host, url, kind (store\|checkout\|infra), provider_monitor_id, keyword, interval_s, enabled, last_state (unknown\|up\|down\|paused), last_state_at, synced_at, last_error, created_at; ordered by kind and host. |
| `configured` | boolean | The uptime vendor is configured on this deployment. |
| `callbackConfigured` | boolean | The vendor callback address is configured (without it no monitor is created). |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A monitor alerts when its keyword is missing or the status is outside 2xx/3xx.

##### `POST /v1/uptime/monitors/:id/test`

**Scope** `monitoring.write` - **Send a test alert for a monitor**

Send a real recovery-worded test alert for one of the account's monitors to its verified destinations subscribed to recovery alerts. Sends real messages.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Monitor id. |

**Response**

```json
{
  "sent": 2,
  "attempted": 3,
  "errors": [
    "sms: Delivery failed"
  ]
}
```

| response field | type | description |
|---|---|---|
| `sent / attempted` | integer | Destinations reached / tried. |
| `errors[]` | string[] | Per-destination failure texts. |

**Errors**

- `400` `Invalid request` with `details.issues` (one {path, code, message} per problem) when the path id is not a UUID.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `404` not found.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- Do not use it as a health check: every call sends messages.

#### Members

The members of the account, their roles, passwords and visible ATRIs.

##### `GET /v1/users`

**Scope** `users.read` - **List account members**

Every member of the account (the owner and its sub-account logins) with their role and ban state, plus context: the account e-mail, whether the caller is the owner, who the caller is, its role, and whether passwords can be set on this deployment.

*No parameters.*

**Response**

```json
{
  "roles": [
    {
      "email": "owner@example.com",
      "role": "admin",
      "parent_email": null,
      "created_at": "2026-04-27T17:05:12.443Z",
      "updated_at": "2026-04-27T17:05:12.443Z",
      "banned_at": null,
      "banned_by": null,
      "ban_message": null
    },
    {
      "email": "analyst@example.com",
      "role": "user",
      "parent_email": "owner@example.com",
      "created_at": "2026-04-27T17:05:12.443Z",
      "updated_at": "2026-04-27T17:05:12.443Z",
      "banned_at": null,
      "banned_by": null,
      "ban_message": null
    }
  ],
  "account": "owner@example.com",
  "isOwner": true,
  "canCreateAccounts": false,
  "self": "owner@example.com",
  "myRole": "admin",
  "canSetPassword": true
}
```

| response field | type | description |
|---|---|---|
| `roles[]` | object[] | Members, owner first, then by role text and e-mail: email, role, parent_email, created_at, updated_at, banned_at, banned_by, ban_message. |
| `account` | string \| null | Account (owner) e-mail. |
| `isOwner` | boolean | The caller is the account owner (always true for a key). |
| `canCreateAccounts` | boolean | True only for the owner of the platform owner's account. |
| `self` | string \| null | The caller's e-mail (for a key: the account owner's e-mail). |
| `myRole` | string \| null | Effective role (admin for a key). |
| `canSetPassword` | boolean | false means password operations will answer 503 on this deployment. |

**Errors**

- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A banned member stays listed with banned_at set.
- The caller's own row is included.

##### `POST /v1/users/password`

**Scope** `users.write` - **Set a member's password**

Create or reset the login password of a member of this account, without changing its role. The member's previous password stops working.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 200) | **yes** | Member e-mail. |
| `password` | string (8..72 chars, at most 72 UTF-8 bytes) | **yes** | New password. |

**Request body**

```json
{
  "email": "analyst@example.com",
  "password": "example-Passw0rd"
}
```

**Response**

```json
{
  "ok": true,
  "created": false
}
```

| response field | type | description |
|---|---|---|
| `created` | boolean | A login did not exist and was created. |

**Errors**

- `400` Invalid (details: zod flatten).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team). Granting a login gives the whole account: only an API key with every permission may do it (a key with a restricted scope list). Or: An API key cannot set the main account owner's password.
- `404` Not a member of your account.
- `502` The authentication service refused the operation: set password failed (N); create user failed (N); list users failed (N); or Invalid authentication directory response.
- `503` Authentication scope is temporarily unavailable. Supabase service role key not configured (set SUPABASE_SERVICE_ROLE_KEY); Authentication service unavailable. Try again.; or Authentication directory lookup limit reached.

**Gotchas**

- Live sessions of the member are not revoked by a password change.

##### `PUT /v1/users/role`

**Scope** `users.write` - **Add a member or change its role**

Create a sub-account member of this account with a role, or change an existing member's role. With password, the login is created (new member) or its password set (existing member) before the role is written.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 200) | **yes** | Member e-mail (lowercased). |
| `role` | string (admin\|refund\|user) | **yes** | admin = full control of the account; user = account data, read mostly; refund = refund pages only. super_admin cannot be assigned. |
| `password` | string (8..72 chars, at most 72 UTF-8 bytes) | no | Login password. Without it the member gets a role but no working login. |

**Request body**

```json
{
  "email": "analyst@example.com",
  "role": "user",
  "password": "example-Passw0rd"
}
```

**Response**

```json
{
  "user": {
    "email": "analyst@example.com",
    "role": "user",
    "parent_email": "owner@example.com",
    "created_at": "2026-04-27T17:05:12.443Z",
    "updated_at": "2026-04-27T17:05:12.443Z",
    "banned_at": null,
    "banned_by": null,
    "ban_message": null
  },
  "passwordSet": true,
  "created": true
}
```

| response field | type | description |
|---|---|---|
| `user` | object | Member row: email, role (super_admin\|admin\|refund\|user), parent_email (the account owner; null for the owner), created_at, updated_at, banned_at, banned_by, ban_message. |
| `passwordSet` | boolean | A password was sent and set. |
| `created` | boolean | A new login was created. |

**Errors**

- `400` Invalid (details: zod flatten).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team). Granting a login gives the whole account: only an API key with every permission may do it (a key with a restricted scope list).
- `409` You cannot modify your own account; This email already belongs to another account; The main account user role cannot be changed here; Cannot demote the last admin; This login already exists. Its password was not changed. (a new member whose e-mail already has a login); or This account membership changed. Refresh and try again.
- `502` The authentication service refused the operation: set password failed (N); create user failed (N); list users failed (N); or Invalid authentication directory response.
- `503` Authentication scope is temporarily unavailable. Supabase service role key not configured (set SUPABASE_SERVICE_ROLE_KEY); Authentication service unavailable. Try again.; or Authentication directory lookup limit reached.

**Gotchas**

- The login is provisioned before the role is written: after a 5xx, read GET /v1/users before retrying.
- No invitation or confirmation e-mail is sent.

##### `DELETE /v1/users/role`

**Scope** `users.write` - **Remove a member**

Remove a sub-account member from this account (its role row and ATRI grants). The owner cannot be removed and the last admin-level member is protected. The member's login itself is not deleted; it simply has no access any more.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 200) | **yes** | Member e-mail. |

**Request body**

```json
{
  "email": "analyst@example.com"
}
```

**Response**

```json
{
  "ok": true
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. No information about what was cascaded is returned. |

**Errors**

- `400` Invalid (details: zod flatten). A client that drops DELETE bodies gets this.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team).
- `404` Not a member of your account.
- `409` You cannot modify your own account; Cannot remove the main account user; or Cannot remove the last admin.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A DELETE with a JSON body: send Content-Type: application/json and keep the body.
- Resources the member owned personally (keys, MIDs, ATRIs created under its own e-mail) lose their owner.
- A second call for the same e-mail answers 404.

##### `GET /v1/users/trips`

**Scope** `users.read` - **Read a member's ATRI view grants**

A member's ATRI view restriction (the ATRIs its pages show) and the account's ATRIs to pick from. An empty grants list means no restriction (every ATRI).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 200) | **yes** | Member e-mail. |

**Response**

```json
{
  "grants": [
    {
      "trip_id": "11111111-1111-4111-8111-111111111111",
      "name": "US Primary Pool",
      "trip_type": "classic",
      "active": true,
      "granted_at": "2026-11-11T09:03:17.556Z"
    }
  ],
  "trips": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "name": "US Primary Pool",
      "trip_type": "classic",
      "active": true
    },
    {
      "id": "22222222-2222-4222-8222-222222222222",
      "name": "EU Cascade",
      "trip_type": "cascade",
      "active": false
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `grants[]` | object[] | trip_id, name, trip_type, active, granted_at. [] = unrestricted. |
| `trips[]` | object[] | The account's ATRIs: id, name, trip_type, active (note id here vs trip_id in grants). |

**Errors**

- `400` Invalid (details: zod flatten).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team).
- `404` Not a member of your account.
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- The restriction narrows what a member login sees; API keys are never restricted by it.

##### `PUT /v1/users/trips`

**Scope** `users.write` - **Replace a member's ATRI view grants**

Replace a member's whole ATRI view restriction with exactly these ATRIs of the account. [] removes the restriction (the member then sees every ATRI). Applies from the member's next request.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `email` | string (e-mail, max 200) | **yes** | Member e-mail. |
| `tripIds` | array of uuid (max 500) | **yes** | ATRIs of this account, without duplicates; [] = no restriction. |

**Request body**

```json
{
  "email": "analyst@example.com",
  "tripIds": [
    "11111111-1111-4111-8111-111111111111"
  ]
}
```

**Response**

```json
{
  "ok": true,
  "count": 1
}
```

| response field | type | description |
|---|---|---|
| `ok` | boolean | Always true on 200. |
| `count` | integer | Echo of tripIds.length — the size of the set you SENT, not a count of rows actually inserted (the insert uses ON CONFLICT DO NOTHING, so duplicates would insert fewer). |

**Errors**

- `400` Invalid (details: zod flatten).
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned). Your subscription does not include this tool. (code subscription_module_required, module team).
- `404` Not a member of your account; or Unknown ATRI (an id not of this account, or a duplicate id).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- A full replacement: omitted grants are removed. There is no way to express "see no ATRI".

#### Account and billing

The account settings (alert thresholds, Telegram, account-wide switches) and the Kontrol platform subscription: plan, renewal, plan changes and invoices.

##### `GET /v1/platform-subscription`

**Scope** `billing.read` - **Read platform subscription and offers**

Reads the Kontrol platform subscription of the caller's main account: its entitlement (paid, unpaid or granted), the offer in force, every active offer, the current terms and automatic billing text that onboarding accepts, and, when the caller may manage billing, the billing schedule, the last 12 invoices, the saved company profile and the billing lifecycle (paid period, next renewal, pending plan change, pending payment, version and capabilities). Sub-accounts read their parent's subscription.

*No parameters.*

**Response**

```json
{
  "subscription": {
    "status": "paid",
    "accountEmail": "owner@example.com",
    "source": "provider",
    "paidUntil": "2026-12-17T12:00:00.000Z",
    "plan": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "isOwner": false,
    "canManageBilling": false
  },
  "setupNeeded": false,
  "plan": {
    "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
    "revision": 1,
    "name": "Standard",
    "description": "",
    "amountCents": 79900,
    "currency": "USD",
    "intervalMonths": 1,
    "active": true,
    "modules": [
      "stores",
      "products",
      "checkouts",
      "flows",
      "pages",
      "affiliates",
      "payments",
      "subscriptions",
      "reports",
      "recovery",
      "integrations",
      "api",
      "team"
    ],
    "limits": {
      "stores": 5,
      "monthlySalesUsdCents": 25000000
    },
    "fxRates": {
      "USD": 1
    },
    "monthlyAmountCents": 79900,
    "usageBasisPoints": 0,
    "features": [
      "Stores and themes",
      "Products",
      "Checkouts",
      "Flows",
      "Funnel pages",
      "Affiliates",
      "Payment configuration",
      "Customer subscriptions",
      "Reports",
      "Cart recovery",
      "Integrations",
      "API key management",
      "Team members"
    ],
    "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $799.00 USD every month for the Standard subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
  },
  "plans": [
    {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      },
      "monthlyAmountCents": 79900,
      "usageBasisPoints": 0,
      "features": [
        "Stores and themes",
        "Products",
        "Checkouts",
        "Flows",
        "Funnel pages",
        "Affiliates",
        "Payment configuration",
        "Customer subscriptions",
        "Reports",
        "Cart recovery",
        "Integrations",
        "API key management",
        "Team members"
      ],
      "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $799.00 USD every month for the Standard subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
    }
  ],
  "checkoutAvailable": false,
  "onboarding": {
    "termsVersion": "2026-11-02.1",
    "termsUrl": "https://kontrolcheckout.com/legal/terms/",
    "privacyUrl": "https://kontrolcheckout.com/legal/privacy/",
    "automaticBillingVersion": "2026-11-02.1",
    "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $799.00 USD every month for the Standard subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
  },
  "billing": null
}
```

| response field | type | description |
|---|---|---|
| `subscription.status` | paid \| unpaid \| granted | granted is an explicit grant by a platform administrator (source manual); it never asserts a payment. Expiry and revocation of a grant are applied on every request. |
| `subscription.source` | bootstrap \| provider \| manual \| null | Where the entitlement comes from. |
| `subscription.paidUntil` | string \| null | End of the paid period, or the expiry of a manual grant. |
| `subscription.plan` | object | The assigned offer snapshot, present when the account has an assignment. |
| `subscription.isOwner` | boolean | True only when the caller may manage billing (then equal to canManageBilling). |
| `subscription.canManageBilling` | boolean | Whether billing is included and the billing routes of this group are open to the caller. |
| `setupNeeded` | boolean | True when the calling login has no account yet: POST /v1/platform-subscription/onboarding completes it. |
| `plan` | object | The offer shown to the caller, with monthlyAmountCents, usageBasisPoints (0), features (module labels) and automaticBillingText. |
| `plans` | object[] | Every active offer, in the same shape. |
| `onboarding` | object | termsVersion, termsUrl, privacyUrl, automaticBillingVersion and the automaticBillingText of plan. |
| `billing` | object \| null | schedule, invoices, profile, consentNeeded, paymentReadiness, lifecycle; null when canManageBilling is false. |
| `billing.lifecycle` | object | version, schedule, currentPlan, accessManaged, period, nextRenewalAt, renewalAmountCents, currency, intervalMonths, currentInvoiceId, mandate, pendingChange, pendingPayment, capabilities {cancelRenewal, resumeRenewal, proposePlanChange}, paymentReadiness. Null dates and amounts mean no scheduled charge. |
| `billing.lifecycle.accessManaged` | boolean | True for a manual, revoked or expired assignment: do not offer payment preparation or renewal there. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- billing is null whenever subscription.canManageBilling is false. When present it holds schedule, invoices (last 12), profile, consentNeeded, paymentReadiness and lifecycle; lifecycle.version is the expectedVersion of the plan-change routes.
- plan is, in this order: the amount of the open invoice or accepted mandate of an unpaid owner using billing, else the assigned offer, else the legacy Kontrol plan (id kontrol-monthly). A paid account keeps its current snapshot until a changed bill is paid.
- plan.monthlyAmountCents is the amount per intervalMonths (legacy field name), not a normalized monthly price. checkoutAvailable is always false.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `POST /v1/platform-subscription/cancel`

**Scope** `billing.write` - **Cancel the platform subscription renewal**

Stops the renewal of the main account. A paid period keeps access until its end (cancelAtPeriodEnd true, accessUntil set); an unpaid signup is canceled at once. Prepared attempts still awaiting a provider are failed, open invoices without a submitted payment are voided and a pending plan change is canceled when no payment of it was submitted.

*No parameters.*

**Request body**

```json
{}
```

**Response**

```json
{
  "cancelAtPeriodEnd": true,
  "accessUntil": "2026-12-17T12:00:00.000Z"
}
```

| response field | type | description |
|---|---|---|
| `cancelAtPeriodEnd` | boolean | True when a paid period remains. |
| `accessUntil` | string \| null | End of that paid period, else null. |

**Errors**

- `400` {"error":"Invalid cancellation request."}: the body is not empty (send {} or nothing).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `403` {"error":"The main account is unavailable.","code":"account_unavailable"}.
- `409` {"error":"No subscription renewal is scheduled.","code":"subscription_not_started"}: onboarding was never completed.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- Resume with POST /v1/platform-subscription/resume.
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `POST /v1/platform-subscription/checkout`

**Scope** `billing.write` - **Prepare the platform subscription invoice**

Prepares the one outstanding invoice of the main account at the accepted mandate amount and cadence, with a durable payment attempt in status awaiting_provider. Repeated preparation reuses the open invoice and its active attempt. No payment is sent: the account stays unpaid.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `idempotencyKey` | string (uuid) | **yes** | Account-scoped retry key. The same key returns the invoice and attempt of the first call. Strict body: card data, amounts or a status are refused. |

**Request body**

```json
{
  "idempotencyKey": "00000000-0000-4000-8000-000000000071"
}
```

**Response**

```json
{
  "invoice": {
    "id": "00000000-0000-4000-8000-000000000021",
    "account_email": "owner@example.com",
    "mandate_id": "00000000-0000-4000-8000-000000000031",
    "kind": "initial",
    "amount_cents": 79900,
    "currency": "USD",
    "period_start": "2026-11-17T12:00:00.000Z",
    "period_end": "2026-12-17T12:00:00.000Z",
    "due_at": "2026-11-17T12:00:00.000Z",
    "status": "open",
    "paid_at": null,
    "provider": null,
    "provider_payment_id": null,
    "plan_snapshot": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "seller_snapshot": {
      "name": "Example Seller FZCO",
      "brand": "Kontrol",
      "address": "1 Example Street, Dubai",
      "email": "billing@example.com"
    },
    "created_at": "2026-11-17T12:00:00.000Z",
    "updated_at": "2026-11-17T12:00:00.000Z"
  },
  "attempt": {
    "id": "00000000-0000-4000-8000-000000000061",
    "invoice_id": "00000000-0000-4000-8000-000000000021",
    "status": "awaiting_provider",
    "failure_code": null
  },
  "paymentReadiness": {
    "available": false,
    "code": "provider_not_connected",
    "message": "Card payments will be available when the payment provider is connected."
  },
  "checkoutAvailable": false
}
```

| response field | type | description |
|---|---|---|
| `invoice` | object | The open invoice row: id, account_email, mandate_id, kind (initial \| renewal), amount_cents, currency, period_start, period_end, due_at, status, paid_at, provider, provider_payment_id, plan_snapshot, seller_snapshot, created_at, updated_at. |
| `attempt` | object | id, invoice_id, status (awaiting_provider, pending, requires_action, failed, succeeded), failure_code. |
| `paymentReadiness` | object | available false, code provider_not_connected. |

**Errors**

- `400` {"error":"A valid checkout request ID is required.","code":"invalid_checkout"}.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `403` {"error":"The main account is unavailable.","code":"account_unavailable"}.
- `409` billing_access_managed "This account is managed by an administrator. Contact them to change its subscription."; subscription_already_paid "Your current subscription period is already paid."; billing_consent_required "Complete your account and subscription details first." (no schedule) or "Accept the current subscription terms before continuing." (mandate of older terms); renewal_canceled "Subscription renewal is canceled."; invoice_not_due "The next subscription payment is not due yet.".
- `429` Rate limited: 10 requests per minute per client IP.

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- The invoice price and cadence come from the immutable accepted mandate: editing an offer never changes an existing contract.
- An initial invoice starts now; a renewal invoice starts at the scheduled next_invoice_at and is refused before it (invoice_not_due).
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `GET /v1/platform-subscription/invoices`

**Scope** `billing.read` - **List platform subscription invoices**

Lists the existing platform subscription invoices of the main account, paged and sorted. Manual grants create no invoice; open and void invoices are never payments.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `25` | no | Rows per page, 1 to 100. |
| `offset` | integer; default `0` | no | Rows to skip, 0 to 1000000. |
| `status` | string | no | open, paid or void. |
| `sortBy` | string; default `created_at` | no | id, plan_name, created_at, status, amount_cents, currency, due_at or paid_at. |
| `sortDir` | string; default `desc` | no | asc or desc. Ties are broken by id in the same direction; nulls last. |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000021",
      "account_email": "owner@example.com",
      "mandate_id": "00000000-0000-4000-8000-000000000031",
      "kind": "initial",
      "amount_cents": 79900,
      "currency": "USD",
      "period_start": "2026-11-17T12:00:00.000Z",
      "period_end": "2026-12-17T12:00:00.000Z",
      "due_at": "2026-11-17T12:00:00.000Z",
      "status": "open",
      "paid_at": null,
      "provider": null,
      "provider_payment_id": null,
      "plan_snapshot": {
        "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
        "revision": 1,
        "name": "Standard",
        "description": "",
        "amountCents": 79900,
        "currency": "USD",
        "intervalMonths": 1,
        "active": true,
        "modules": [
          "stores",
          "products",
          "checkouts",
          "flows",
          "pages",
          "affiliates",
          "payments",
          "subscriptions",
          "reports",
          "recovery",
          "integrations",
          "api",
          "team"
        ],
        "limits": {
          "stores": 5,
          "monthlySalesUsdCents": 25000000
        },
        "fxRates": {
          "USD": 1
        }
      },
      "seller_snapshot": {
        "name": "Example Seller FZCO",
        "brand": "Kontrol",
        "address": "1 Example Street, Dubai",
        "email": "billing@example.com"
      },
      "created_at": "2026-11-17T12:00:00.000Z",
      "updated_at": "2026-11-17T12:00:00.000Z"
    }
  ],
  "total": 1,
  "limit": 25,
  "offset": 0
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Invoice rows: id, account_email, mandate_id, kind, amount_cents, currency, period_start, period_end, due_at, status, paid_at, provider, provider_payment_id, plan_snapshot, seller_snapshot, created_at, updated_at. |
| `total` | integer | Rows matching the status filter. |
| `limit` | integer | Applied limit. |
| `offset` | integer | Applied offset. |

**Errors**

- `400` {"error":"Invalid invoice pagination."}: a value out of range or an unknown query key (the query is strict).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `404` {"error":"Main account not found.","code":"account_not_found"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Read one invoice with GET /v1/platform-subscription/invoices/:id and its PDF with GET /v1/platform-subscription/invoices/:id/pdf.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `GET /v1/platform-subscription/invoices/:id`

**Scope** `billing.read` - **Read a platform subscription invoice**

Reads one saved invoice with the billing profile and plan snapshot of its mandate and every payment attempt made on it, newest first.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Invoice id of this main account. |

**Response**

```json
{
  "invoice": {
    "id": "00000000-0000-4000-8000-000000000021",
    "account_email": "owner@example.com",
    "mandate_id": "00000000-0000-4000-8000-000000000031",
    "kind": "initial",
    "amount_cents": 79900,
    "currency": "USD",
    "period_start": "2026-11-17T12:00:00.000Z",
    "period_end": "2026-12-17T12:00:00.000Z",
    "due_at": "2026-11-17T12:00:00.000Z",
    "status": "open",
    "paid_at": null,
    "provider": null,
    "provider_payment_id": null,
    "plan_snapshot": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "seller_snapshot": {
      "name": "Example Seller FZCO",
      "brand": "Kontrol",
      "address": "1 Example Street, Dubai",
      "email": "billing@example.com"
    },
    "created_at": "2026-11-17T12:00:00.000Z",
    "updated_at": "2026-11-17T12:00:00.000Z"
  },
  "profile": {
    "firstName": "Jane",
    "lastName": "Example",
    "telegram": "@jane_example",
    "companyName": "Example Commerce LLC",
    "companyAddress": "10 Example Road, Dubai",
    "estimatedMonthlyVolume": "25k_100k"
  },
  "attempts": [
    {
      "id": "00000000-0000-4000-8000-000000000061",
      "status": "awaiting_provider",
      "failure_code": null,
      "provider": null,
      "created_at": "2026-11-17T12:00:01.000Z",
      "updated_at": "2026-11-17T12:00:01.000Z"
    }
  ],
  "mandate": {
    "id": "00000000-0000-4000-8000-000000000031",
    "acceptedAt": "2026-11-17T11:58:00.000Z",
    "plan": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "amountCents": 79900,
    "currency": "USD",
    "intervalMonths": 1
  }
}
```

| response field | type | description |
|---|---|---|
| `invoice` | object | The invoice row (see the list). |
| `profile` | object \| null | Company profile recorded with the mandate. |
| `attempts` | object[] | id, status, failure_code, provider, created_at, updated_at, newest first. |
| `mandate` | object | id, acceptedAt, plan, amountCents, currency, intervalMonths. |

**Errors**

- `400` {"error":"Invalid invoice ID."}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `404` {"error":"Invoice not found.","code":"invoice_not_found"}: unknown id or an invoice of another account; {"error":"Main account not found.","code":"account_not_found"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- Account ownership is checked before any record is read: another account's invoice answers the same 404 as an unknown id.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `GET /v1/platform-subscription/invoices/:id/pdf`

**Scope** `billing.read` - **Download a platform subscription invoice PDF**

Downloads an existing invoice as an A4 PDF (Content-Type application/pdf, Content-Disposition attachment; filename="Kontrol-Invoice-<id>.pdf"). The document shows PAID, OPEN or VOID, the invoice id, issue and due dates, service period, issuer and bill-to recorded on the invoice, the plan, the billing interval and the amount.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | string (uuid) | **yes** | Invoice id of this main account. |

**Response**

```json
Binary application/pdf body (attachment; filename="Kontrol-Invoice-00000000-0000-4000-8000-000000000021.pdf").
```

**Errors**

- `400` {"error":"Invalid invoice ID."}: id is not a UUID.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `404` {"error":"Invoice not found.","code":"invoice_not_found"}: unknown id or an invoice of another account; {"error":"Main account not found.","code":"account_not_found"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- A download of an existing record, never a payment confirmation: an open invoice says it does not confirm payment or grant access.
- No tax breakdown is recorded; issuer or buyer details missing from the record are printed as not recorded, never invented.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `POST /v1/platform-subscription/onboarding`

**Scope** `billing.write` - **Complete account setup and accept subscription terms**

Makes the calling login its own unpaid main account (or completes the missing profile of an existing main account), records the company profile and an immutable automatic billing mandate for the selected offer (price, currency, cadence, modules, limits and FX snapshot), and creates a billing-mode plan assignment that does not grant access by itself. Accepting new terms voids any open invoice, stops prepared payment attempts and cancels a pending plan change. A sub-account is never promoted.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `planId` | string (uuid) | no | An active offer id from plans of GET /v1/platform-subscription. Send it with planRevision. Omitted: the standard offer, accepted only while it is still revision 1 at 79900 cents per month. |
| `planRevision` | integer | no | Positive revision of the selected offer; must equal its current revision (409 plan_changed otherwise). Must be omitted when planId is omitted. |
| `acceptTerms` | boolean (true) | **yes** | Must be the literal true. |
| `acceptAutomaticBilling` | boolean (true) | **yes** | Must be the literal true: consent to the automaticBillingText of the selected offer. |
| `termsVersion` | string | **yes** | Must equal onboarding.termsVersion of GET /v1/platform-subscription (currently 2026-11-02.1). |
| `profile` | object | **yes** | Company profile. Strict: any other key is refused. |
| `profile.firstName` | string | **yes** | Trimmed, 1 to 80 characters. |
| `profile.lastName` | string | **yes** | Trimmed, 1 to 80 characters. |
| `profile.telegram` | string | **yes** | Trimmed, 2 to 100 characters. |
| `profile.companyName` | string | **yes** | Trimmed, 1 to 160 characters. |
| `profile.companyAddress` | string | **yes** | Trimmed, 5 to 1000 characters. |
| `profile.estimatedMonthlyVolume` | string | **yes** | One of pre_launch, under_25k, 25k_100k, 100k_500k, 500k_1m, over_1m. |

**Request body**

```json
{
  "planId": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
  "planRevision": 1,
  "acceptTerms": true,
  "acceptAutomaticBilling": true,
  "termsVersion": "2026-11-02.1",
  "profile": {
    "firstName": "Jane",
    "lastName": "Example",
    "telegram": "@jane_example",
    "companyName": "Example Commerce LLC",
    "companyAddress": "10 Example Road, Dubai",
    "estimatedMonthlyVolume": "25k_100k"
  }
}
```

**Response**

```json
{
  "subscription": {
    "status": "unpaid",
    "accountEmail": "owner@example.com",
    "source": null,
    "paidUntil": null,
    "plan": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "isOwner": true,
    "canManageBilling": true
  },
  "setupNeeded": false,
  "plan": {
    "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
    "revision": 1,
    "name": "Standard",
    "description": "",
    "amountCents": 79900,
    "currency": "USD",
    "intervalMonths": 1,
    "active": true,
    "modules": [
      "stores",
      "products",
      "checkouts",
      "flows",
      "pages",
      "affiliates",
      "payments",
      "subscriptions",
      "reports",
      "recovery",
      "integrations",
      "api",
      "team"
    ],
    "limits": {
      "stores": 5,
      "monthlySalesUsdCents": 25000000
    },
    "fxRates": {
      "USD": 1
    },
    "monthlyAmountCents": 79900,
    "usageBasisPoints": 0,
    "features": [
      "Stores and themes",
      "Products",
      "Checkouts",
      "Flows",
      "Funnel pages",
      "Affiliates",
      "Payment configuration",
      "Customer subscriptions",
      "Reports",
      "Cart recovery",
      "Integrations",
      "API key management",
      "Team members"
    ],
    "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $799.00 USD every month for the Standard subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
  },
  "plans": [
    {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      },
      "monthlyAmountCents": 79900,
      "usageBasisPoints": 0,
      "features": [
        "Stores and themes",
        "Products",
        "Checkouts",
        "Flows",
        "Funnel pages",
        "Affiliates",
        "Payment configuration",
        "Customer subscriptions",
        "Reports",
        "Cart recovery",
        "Integrations",
        "API key management",
        "Team members"
      ],
      "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $799.00 USD every month for the Standard subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
    }
  ],
  "checkoutAvailable": false,
  "onboarding": {
    "termsVersion": "2026-11-02.1",
    "termsUrl": "https://kontrolcheckout.com/legal/terms/",
    "privacyUrl": "https://kontrolcheckout.com/legal/privacy/",
    "automaticBillingVersion": "2026-11-02.1",
    "automaticBillingText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method USD 799 each month, beginning when I activate my subscription and on each monthly renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales."
  }
}
```

| response field | type | description |
|---|---|---|
| `subscription` | object | The new state: status unpaid until a payment is verified, isOwner and canManageBilling true. |
| `plan` | object | The assigned offer. |
| `plans` | object[] | Every active offer. |

**Errors**

- `400` {"error":"Check your account details and accept the current terms.","code":"invalid_onboarding","details":<zod flatten>}: a missing or extra field, a consent that is not true, an old termsVersion.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"This account is not available for signup.","code":"account_unavailable"}: the login is banned.
- `403` {"error":"Onboarding creates the account of a new login. Sign in with that login to complete it; an API key cannot.","code":"human_session_required"}: onboarding provisions an account for the calling login itself, so an API key is refused before the body is read.
- `404` {"error":"Subscription offer not found.","code":"plan_not_found"}: unknown planId.
- `409` plan_archived "Choose an available subscription offer."; plan_changed "The subscription offer changed. Refresh and accept its current terms."; existing_account_membership "This login already belongs to an account. Sign in to continue."; billing_access_managed "This account is managed by an administrator. Contact them to change its subscription."; subscription_active "An active subscription cannot be replaced through onboarding."; billing_payment_pending "Wait for the submitted payment to finish before changing subscription details."; account_exists "This email already belongs to a provisioned account. Sign in with its existing login."; identity_changed "This account is already connected to another login.".
- `429` Rate limited: 5 requests per minute per client IP.
- `503` {"error":"Account setup is temporarily unavailable.","code":"signup_unavailable"}: the identity service could not be reached.

**Gotchas**

- 201 when the main account was created, 200 when an existing main account completed or replaced its terms. The answer has no billing key and its onboarding is the default terms object.
- The body is strict: email, role, parentEmail, status or any other extra key answers 400. No password is accepted here.
- The account, auth user id, server time, request IP and user agent, the exact mandate text and the profile snapshot are recorded with a SHA-256 evidence hash. Retrying the same current terms does not create a second mandate.
- An active paid period, a manual or revoked assignment, or a submitted payment blocks onboarding (409).
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `GET /v1/platform-subscription/plan-change`

**Scope** `billing.read` - **Review a proposed plan change**

Reads the plan change a platform administrator proposed for the main account (its exact offer snapshot and automatic billing text) with the current billing version and terms version that acceptance must echo.

*No parameters.*

**Response**

```json
{
  "change": {
    "id": "00000000-0000-4000-8000-000000000044",
    "accountEmail": "owner@example.com",
    "state": "proposed",
    "plan": {
      "id": "00000000-0000-4000-8000-000000000051",
      "revision": 2,
      "name": "Growth",
      "description": "",
      "amountCents": 149900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "mandateText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $1,499.00 USD every month for the Growth subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales.",
    "effectiveAt": "2026-12-17T12:00:00.000Z",
    "requestedBy": "operator@example.com",
    "reason": "Upgrade agreed with the account",
    "createdAt": "2026-11-20T09:00:00.000Z",
    "acceptedAt": null
  },
  "billingVersion": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "termsVersion": "2026-11-02.1"
}
```

| response field | type | description |
|---|---|---|
| `change` | object \| null | id, accountEmail, state (proposed \| accepted), plan (offer snapshot), mandateText, effectiveAt, requestedBy, reason, createdAt, acceptedAt. |
| `billingVersion` | string | 64 hex characters: send it as expectedVersion. |
| `termsVersion` | string | Send it as termsVersion when accepting. |

**Errors**

- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `404` {"error":"Main account not found.","code":"account_not_found"}.
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- change is null when nothing is pending. state proposed waits for acceptance; state accepted takes effect when the renewal invoice of the new terms is paid.
- Accept with POST /v1/platform-subscription/plan-change/accept, refuse or withdraw with POST /v1/platform-subscription/plan-change/decline.
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `POST /v1/platform-subscription/plan-change/accept`

**Scope** `billing.write` - **Accept a proposed plan change**

Records a new immutable mandate for the proposed offer, bound to the recorded account owner, and makes it the billing schedule's mandate. Open invoices are voided and prepared attempts failed. Access and paid invoices do not change until the renewal invoice of the new terms is paid; there is no immediate charge and no proration.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedVersion` | string | **yes** | The 64 lower-case hex characters of billing.lifecycle.version (GET /v1/platform-subscription) or billingVersion (GET /v1/platform-subscription/plan-change). A stale value answers 409 billing_changed. |
| `requestId` | string (uuid) | **yes** | Your retry identity. Resending the same requestId with the same payload returns the saved result of the first call; the same requestId with another payload answers 409 billing_request_conflict. |
| `changeId` | string (uuid) | **yes** | change.id from GET /v1/platform-subscription/plan-change. |
| `acceptTerms` | boolean (true) | **yes** | Must be the literal true. |
| `acceptAutomaticBilling` | boolean (true) | **yes** | Must be the literal true: consent to change.mandateText. |
| `termsVersion` | string | **yes** | Must equal termsVersion of GET /v1/platform-subscription/plan-change (currently 2026-11-02.1). |

**Request body**

```json
{
  "expectedVersion": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "requestId": "00000000-0000-4000-8000-000000000081",
  "changeId": "00000000-0000-4000-8000-000000000044",
  "acceptTerms": true,
  "acceptAutomaticBilling": true,
  "termsVersion": "2026-11-02.1"
}
```

**Response**

```json
{
  "billing": {
    "version": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "schedule": {
      "account_email": "owner@example.com",
      "mandate_id": "00000000-0000-4000-8000-000000000031",
      "state": "active",
      "billing_anchor": "2026-11-17T12:00:00.000Z",
      "next_invoice_at": "2026-12-17T12:00:00.000Z",
      "cancel_at_period_end": false
    },
    "currentPlan": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "accessManaged": false,
    "period": {
      "start": "2026-11-17T12:00:00.000Z",
      "end": "2026-12-17T12:00:00.000Z"
    },
    "nextRenewalAt": "2026-12-17T12:00:00.000Z",
    "renewalAmountCents": 79900,
    "currency": "USD",
    "intervalMonths": 1,
    "currentInvoiceId": "00000000-0000-4000-8000-000000000021",
    "mandate": {
      "id": "00000000-0000-4000-8000-000000000031",
      "acceptedAt": "2026-11-17T11:58:00.000Z",
      "plan": {
        "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
        "revision": 1,
        "name": "Standard",
        "description": "",
        "amountCents": 79900,
        "currency": "USD",
        "intervalMonths": 1,
        "active": true,
        "modules": [
          "stores",
          "products",
          "checkouts",
          "flows",
          "pages",
          "affiliates",
          "payments",
          "subscriptions",
          "reports",
          "recovery",
          "integrations",
          "api",
          "team"
        ],
        "limits": {
          "stores": 5,
          "monthlySalesUsdCents": 25000000
        },
        "fxRates": {
          "USD": 1
        }
      },
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1
    },
    "pendingChange": {
      "id": "00000000-0000-4000-8000-000000000044",
      "accountEmail": "owner@example.com",
      "state": "accepted",
      "plan": {
        "id": "00000000-0000-4000-8000-000000000051",
        "revision": 2,
        "name": "Growth",
        "description": "",
        "amountCents": 149900,
        "currency": "USD",
        "intervalMonths": 1,
        "active": true,
        "modules": [
          "stores",
          "products",
          "checkouts",
          "flows",
          "pages",
          "affiliates",
          "payments",
          "subscriptions",
          "reports",
          "recovery",
          "integrations",
          "api",
          "team"
        ],
        "limits": {
          "stores": 5,
          "monthlySalesUsdCents": 25000000
        },
        "fxRates": {
          "USD": 1
        }
      },
      "mandateText": "I authorise Kontrol (NOCOMP FZCO) to charge my saved payment method $1,499.00 USD every month for the Growth subscription, beginning when I activate it and on each renewal, until I cancel renewal. Applicable taxes are shown before payment. There is no percentage fee on sales.",
      "effectiveAt": "2026-12-17T12:00:00.000Z",
      "requestedBy": "operator@example.com",
      "reason": "Upgrade agreed with the account",
      "createdAt": "2026-11-20T09:00:00.000Z",
      "acceptedAt": "2026-11-24T10:00:00.000Z"
    },
    "pendingPayment": false,
    "capabilities": {
      "cancelRenewal": true,
      "resumeRenewal": false,
      "proposePlanChange": true
    },
    "paymentReadiness": {
      "available": false,
      "code": "provider_not_connected",
      "message": "Card payments will be available when the payment provider is connected."
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `billing` | object | The billing lifecycle after the change (same shape as billing.lifecycle of GET /v1/platform-subscription); pendingChange.state is accepted. |

**Errors**

- `400` {"error":"Review and accept the current plan and automatic billing terms."}: a missing, extra or invalid field, a consent that is not true, another termsVersion.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `403` {"error":"Only the recorded account owner can accept these terms.","code":"billing_identity_mismatch"}.
- `403` {"error":"The main account is banned.","code":"account_unavailable"}.
- `403` {"error":"Accepting new billing terms authorizes automatic charges and is recorded against the login of the account owner. Sign in to the dashboard to accept them; an API key cannot.","code":"human_session_required"}: the mandate is recorded against the owner login, so an API key is refused.
- `404` {"error":"Main account not found.","code":"account_not_found"}.
- `409` {"error":"The platform administrator keeps its existing access.","code":"platform_owner_protected"}.
- `409` {"error":"This request ID was already used for another operation.","code":"billing_request_conflict"}.
- `409` {"error":"Subscription billing changed. Refresh before continuing.","code":"billing_changed"}: expectedVersion is not the current billing version.
- `409` billing_action_unavailable "The subscription is no longer available for this change."; plan_change_unavailable "The subscription change is no longer awaiting acceptance."; plan_archived "This subscription offer is no longer available."; billing_payment_pending "Wait for the submitted payment before changing subscription terms."; billing_changed "The billing schedule changed. Ask for an updated proposal.".
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- Strict body: any extra key answers 400.
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `POST /v1/platform-subscription/plan-change/decline`

**Scope** `billing.write` - **Decline or withdraw a plan change**

Refuses a proposed plan change, or withdraws accepted future terms before their payment is submitted (the schedule returns to the previous mandate and its open invoices are voided).

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `expectedVersion` | string | **yes** | The 64 lower-case hex characters of billing.lifecycle.version (GET /v1/platform-subscription) or billingVersion (GET /v1/platform-subscription/plan-change). A stale value answers 409 billing_changed. |
| `requestId` | string (uuid) | **yes** | Your retry identity. Resending the same requestId with the same payload returns the saved result of the first call; the same requestId with another payload answers 409 billing_request_conflict. |
| `reason` | string | **yes** | Audit reason, trimmed, 1 to 1000 characters. |

**Request body**

```json
{
  "expectedVersion": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "requestId": "00000000-0000-4000-8000-000000000082",
  "reason": "Keeping the current plan"
}
```

**Response**

```json
{
  "billing": {
    "version": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "schedule": {
      "account_email": "owner@example.com",
      "mandate_id": "00000000-0000-4000-8000-000000000031",
      "state": "active",
      "billing_anchor": "2026-11-17T12:00:00.000Z",
      "next_invoice_at": "2026-12-17T12:00:00.000Z",
      "cancel_at_period_end": false
    },
    "currentPlan": {
      "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
      "revision": 1,
      "name": "Standard",
      "description": "",
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1,
      "active": true,
      "modules": [
        "stores",
        "products",
        "checkouts",
        "flows",
        "pages",
        "affiliates",
        "payments",
        "subscriptions",
        "reports",
        "recovery",
        "integrations",
        "api",
        "team"
      ],
      "limits": {
        "stores": 5,
        "monthlySalesUsdCents": 25000000
      },
      "fxRates": {
        "USD": 1
      }
    },
    "accessManaged": false,
    "period": {
      "start": "2026-11-17T12:00:00.000Z",
      "end": "2026-12-17T12:00:00.000Z"
    },
    "nextRenewalAt": "2026-12-17T12:00:00.000Z",
    "renewalAmountCents": 79900,
    "currency": "USD",
    "intervalMonths": 1,
    "currentInvoiceId": "00000000-0000-4000-8000-000000000021",
    "mandate": {
      "id": "00000000-0000-4000-8000-000000000031",
      "acceptedAt": "2026-11-17T11:58:00.000Z",
      "plan": {
        "id": "bbfc2030-b5e5-4d90-b613-d026a6d7a001",
        "revision": 1,
        "name": "Standard",
        "description": "",
        "amountCents": 79900,
        "currency": "USD",
        "intervalMonths": 1,
        "active": true,
        "modules": [
          "stores",
          "products",
          "checkouts",
          "flows",
          "pages",
          "affiliates",
          "payments",
          "subscriptions",
          "reports",
          "recovery",
          "integrations",
          "api",
          "team"
        ],
        "limits": {
          "stores": 5,
          "monthlySalesUsdCents": 25000000
        },
        "fxRates": {
          "USD": 1
        }
      },
      "amountCents": 79900,
      "currency": "USD",
      "intervalMonths": 1
    },
    "pendingChange": null,
    "pendingPayment": false,
    "capabilities": {
      "cancelRenewal": true,
      "resumeRenewal": false,
      "proposePlanChange": true
    },
    "paymentReadiness": {
      "available": false,
      "code": "provider_not_connected",
      "message": "Card payments will be available when the payment provider is connected."
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `billing` | object | The billing lifecycle after the change; pendingChange is null. |

**Errors**

- `400` {"error":"A current billing version, request ID and reason are required."}: a missing, extra or invalid field.
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `403` {"error":"The main account is banned.","code":"account_unavailable"}.
- `404` {"error":"Main account not found.","code":"account_not_found"}.
- `409` {"error":"The platform administrator keeps its existing access.","code":"platform_owner_protected"}.
- `409` {"error":"This request ID was already used for another operation.","code":"billing_request_conflict"}.
- `409` {"error":"Subscription billing changed. Refresh before continuing.","code":"billing_changed"}: expectedVersion is not the current billing version.
- `409` plan_change_unavailable "No subscription change is pending."; billing_payment_pending "The changed subscription has a submitted payment. Wait for its final result.".
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- Strict body: any extra key answers 400.
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.
- Called with an API key, the decline is recorded with the key as its actor.

##### `POST /v1/platform-subscription/resume`

**Scope** `billing.write` - **Resume the platform subscription renewal**

Turns renewal back on with the account's current mandate. During a paid period it only clears the cancellation. After a completed cancellation it restarts billing: open invoices are voided, prepared attempts failed, the schedule returns to pending activation and an expired paid status becomes unpaid. Nothing is charged.

*No parameters.*

**Request body**

```json
{}
```

**Response**

```json
{
  "renewalEnabled": true
}
```

| response field | type | description |
|---|---|---|
| `renewalEnabled` | boolean | Always true on success. |

**Errors**

- `400` {"error":"Invalid renewal request."}: the body is not empty (send {} or nothing).
- `401` {"error":"Missing bearer token"} without an Authorization: Bearer header; {"error":"Invalid API key"} for an unknown or revoked key.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key lacks that scope; {"error":"Banned","message":"..."} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's account has no active owner.
- `403` {"error":"Only the main account owner can manage billing.","code":"account_owner_required"}: the caller is not the owner of the main account (a sub-account member, a banned login).
- `403` {"error":"The main account is unavailable.","code":"account_unavailable"}.
- `409` billing_access_managed "This account is managed by an administrator. Contact them to change its subscription."; billing_consent_required "Complete your account and subscription details first." or "Accept the current subscription terms before continuing."; billing_payment_pending "Wait for the submitted payment to finish before restarting your subscription.".
- `429` Rate limited: 300 requests per minute per client IP (the API default).

**Gotchas**

- There is no connected payment provider: no endpoint of this API takes card data or sends a sale, and none can mark an account paid. paymentReadiness.available is false with code provider_not_connected.
- A manual or revoked assignment cannot resume self-serve billing (409 billing_access_managed).
- Refusals of this route answer {"error":"<sentence>","code":"<code>"}, except the 400s that carry only an error sentence.
- Answers carry cache-control: private, no-store.
- Reachable while the account is unpaid (no 402): billing recovery stays available.

##### `GET /v1/settings`

**Scope** `settings.read` - **Read account settings**

Returns the account's settings: timezone, the Apple Pay, BIN scrub, wallet product matching, rebill dispatch and blacklist switches, the routing rules (card cooldown, cascade policy, dead gateway auto-disable, BIN scrub floor), the health alert thresholds and Telegram destination, the BIN map, brand sync and BIN audit settings, and the cross-account rebill permission.

*No parameters.*

**Response**

```json
{
  "timezone": "America/New_York",
  "binScrubEnabled": true,
  "walletProductMatching": false,
  "rebillDispatchEnabled": true,
  "blacklistEnabled": true,
  "blacklistRefundAutoAdd": true,
  "cardCooldownEnabled": true,
  "cardCooldownHours": 4,
  "cascadeOnTimeout": true,
  "cascadeMaxDepth": 5,
  "cascadeMaxPerCategory": 3,
  "deadMidEnabled": true,
  "deadMidWindowHours": 24,
  "deadMidMinAttempts": 20,
  "deadMidMinDeadSignals": 3,
  "binScrubArThresholdPct": 10,
  "convesioIntegrationId": "",
  "alertsEnabled": true,
  "alertsTelegramBotToken": "",
  "alertsTelegramChatId": "-1000000000000",
  "alertsWindowHours": 1,
  "alertsMinCharges": 20,
  "alertsArFloorPct": 40,
  "alertsMidArFloorPct": 30,
  "alertsErrorRatePct": 20,
  "alertsCapWarnPct": 90,
  "binMapEnabled": true,
  "binMapMinBinAttempts": 20,
  "binMapMinMidAttempts": 10,
  "binMapMinArPct": 50,
  "brandSyncEnabled": true,
  "brandSyncWindowHours": 168,
  "binScrubAuditEnabled": true,
  "binScrubAuditWindowHours": 720,
  "binScrubAuditMinAttempts": 50,
  "binScrubAuditMinNetLossCents": 0,
  "binScrubAuditAutoEnforce": false,
  "rebillCrossAccountAllowed": false,
  "applePayEnabled": true,
  "alertsTelegramBotTokenSet": true
}
```

| response field | type | description |
|---|---|---|
| `timezone` | string | IANA zone of the account: the daily window of the 'round_robin' dispatch and the dashboard clock. Default 'America/New_York'. |
| `applePayEnabled` | boolean | ACCOUNT-WIDE Apple Pay switch (account_settings.apple_pay_enabled, migration 130, default true). false = GET /v1/checkouts/:shopId/routing answers applePay false for every store of the account (applePayGlobal carries this value), POST /wallet/sessions refuses every Apple session on one of the account's wallet providers with { eligible: false, reason: 'apple_pay_disabled' }, POST /wallet/sessions/:id/charge answers 403 for an Apple session already open and the hosted /s/:id page renders a fallback instead of the sheet. Nothing on the shops' routing rows or on the providers' apple_pay_enabled flags is touched; Google Pay is not affected. Flipped from /wallet-providers. |
| `binScrubEnabled / binScrubArThresholdPct` | boolean / integer 0..100 | The BIN-scrub master switch of the account and its approval-rate floor. |
| `walletProductMatching` | boolean | Describe wallet charges to the gateway as a basket matched from the bank page's Storefronts catalog (with the 'smart_product_matching' integration on). |
| `rebillDispatchEnabled / rebillCrossAccountAllowed` | boolean | The subscription engine's kill switch for the account, and whether other accounts' API keys may rebill this account's customers (card on file). |
| `blacklistEnabled / blacklistRefundAutoAdd` | boolean | Blacklist checks on the charge path; auto-add a customer to the blacklist on refund. |
| `cardCooldownEnabled / cardCooldownHours` | boolean / integer 1..168 | The same-card cooldown between two sales. |
| `cascadeOnTimeout / cascadeMaxDepth / cascadeMaxPerCategory` | boolean / integer 1..20 / integer 0..20 | The failover cascade policy of the account. |
| `deadMidEnabled / deadMidWindowHours / deadMidMinAttempts / deadMidMinDeadSignals` | boolean / integers | Dead-MID auto-disable thresholds. |
| `convesioIntegrationId` | string | The account's ConvesioPay integration id (wallet provider provisioning). |
| `alertsEnabled / alertsTelegramBotToken / alertsTelegramChatId / alertsWindowHours / alertsMinCharges / alertsArFloorPct / alertsMidArFloorPct / alertsErrorRatePct / alertsCapWarnPct` | boolean / strings / integers | Health alerts: the Telegram destination and the thresholds. v3.9.8 item 7 — alertsTelegramBotToken is always "" here and alertsTelegramBotTokenSet says whether one is stored; the value is read through GET /v1/settings/credentials (admin, audited). |
| `binMapEnabled / binMapMinBinAttempts / binMapMinMidAttempts / binMapMinArPct` | boolean / integers | The BIN → MID routing map. |
| `brandSyncEnabled / brandSyncWindowHours` | boolean / integer 1..720 | Card-brand support sync per MID. |
| `binScrubAuditEnabled / binScrubAuditWindowHours / binScrubAuditMinAttempts / binScrubAuditMinNetLossCents / binScrubAuditAutoEnforce` | boolean / integers / boolean | The BIN money audit (recompute window, minimum attempts, net-loss floor, auto-enforce). |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- alertsTelegramBotToken is always "" here; alertsTelegramBotTokenSet tells whether one is stored. The stored token is never returned to an API key.
- A new account gets the platform defaults on its first read (timezone America/New_York, applePayEnabled true, the others from the platform configuration).
- Served from a 30-second per-process cache; on a database error the route answers 200 with the last cached values or the defaults.

##### `PATCH /v1/settings`

**Scope** `settings.write` - **Update account settings**

Partial update of the account settings: send only the fields to change (at least one). The full settings object is returned as read back after the write.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `timezone` | string (IANA zone, 1-64, trimmed) | no | Account timezone: day boundaries of the dashboard and reports, and the round_robin daily window. Checked with Intl; an unknown zone answers 400. |
| `binScrubEnabled` | boolean | no | BIN scrub switch (refuse charges on BINs the scrub rules block). |
| `walletProductMatching` | boolean | no | Wallet smart product matching switch. |
| `rebillDispatchEnabled` | boolean | no | Subscription rebill dispatch switch: false stops scheduled rebills of the account from being sent. |
| `blacklistEnabled` | boolean | no | Check the blacklist before charging. |
| `blacklistRefundAutoAdd` | boolean | no | Add a refunded customer to the blacklist automatically. |
| `cardCooldownEnabled` | boolean | no | Refuse a card again for cardCooldownHours after a decline (card_cooldown rejection). |
| `cardCooldownHours` | integer (1-168) | no | Card cooldown length in hours. |
| `cascadeOnTimeout` | boolean | no | Treat a gateway timeout as a decline and fail over to the next gateway. |
| `cascadeMaxDepth` | integer (1-20) | no | Maximum gateways tried for one charge. |
| `cascadeMaxPerCategory` | integer (0-20) | no | Maximum gateways of the same category tried for one charge. |
| `deadMidEnabled` | boolean | no | Auto-disable a gateway that keeps returning account-level dead errors. |
| `deadMidWindowHours` | integer (1-720) | no | Dead gateway detection window in hours. |
| `deadMidMinAttempts` | integer (1-10000) | no | Attempts needed in the window before a gateway can be disabled. |
| `deadMidMinDeadSignals` | integer (1-10000) | no | Dead errors needed in the window to disable a gateway. |
| `binScrubArThresholdPct` | integer (0-100) | no | Approval rate floor (percent) used by the BIN scrub. |
| `convesioIntegrationId` | string (0-128, trimmed) | no | ConvesioPay integration id of the account. |
| `alertsEnabled` | boolean | no | Health alerts switch (Telegram). |
| `alertsTelegramBotToken` | string (0-128, trimmed) | no | Telegram bot token for health alerts. Write-only through this API: GET and PATCH answer "" with alertsTelegramBotTokenSet. Sending the 8-character bullet mask back unchanged is ignored. |
| `alertsTelegramChatId` | string (0-64, trimmed) | no | Telegram chat id that receives the alerts. |
| `alertsWindowHours` | integer (1-168) | no | Window in hours the alert checks look at. |
| `alertsMinCharges` | integer (1-100000) | no | Minimum charges in the window before an approval rate alert can fire. |
| `alertsArFloorPct` | integer (0-100) | no | Account approval rate floor (percent). |
| `alertsMidArFloorPct` | integer (0-100) | no | Per-gateway approval rate floor (percent). |
| `alertsErrorRatePct` | integer (0-100) | no | Error rate ceiling (percent). |
| `alertsCapWarnPct` | integer (0-100) | no | Warn when a gateway reaches this percent of its cap. |
| `binMapEnabled` | boolean | no | BIN to gateway routing map switch. |
| `binMapMinBinAttempts` | integer (1-100000) | no | BIN map: attempts needed on a BIN. |
| `binMapMinMidAttempts` | integer (1-100000) | no | BIN map: attempts needed on a gateway for that BIN. |
| `binMapMinArPct` | integer (0-100) | no | BIN map: minimum approval rate (percent). |
| `brandSyncEnabled` | boolean | no | Card brand support sync switch. |
| `brandSyncWindowHours` | integer (1-720) | no | Brand support sync window in hours. |
| `binScrubAuditEnabled` | boolean | no | BIN scrub money audit switch (recompute scrub rules from results). |
| `binScrubAuditWindowHours` | integer (1-8760) | no | BIN scrub audit window in hours. |
| `binScrubAuditMinAttempts` | integer (1-100000) | no | BIN scrub audit: attempts needed. |
| `binScrubAuditMinNetLossCents` | integer (>= 0) | no | BIN scrub audit: minimum net loss in cents. |
| `binScrubAuditAutoEnforce` | boolean | no | Apply the audit verdicts automatically. |
| `rebillCrossAccountAllowed` | boolean | no | May other accounts' API keys rebill this account's customers (card on file). |
| `applePayEnabled` | boolean | no | Account-wide Apple Pay switch: false turns Apple Pay off for every checkout and every wallet provider of the account (GET /v1/checkouts/:shopId/routing answers applePay false and Apple Pay sessions are refused). |

**Request body**

```json
{
  "timezone": "Europe/Paris",
  "cardCooldownHours": 6,
  "applePayEnabled": false
}
```

**Response**

```json
{
  "timezone": "Europe/Paris",
  "binScrubEnabled": true,
  "walletProductMatching": false,
  "rebillDispatchEnabled": true,
  "blacklistEnabled": true,
  "blacklistRefundAutoAdd": true,
  "cardCooldownEnabled": true,
  "cardCooldownHours": 6,
  "cascadeOnTimeout": true,
  "cascadeMaxDepth": 5,
  "cascadeMaxPerCategory": 3,
  "deadMidEnabled": true,
  "deadMidWindowHours": 24,
  "deadMidMinAttempts": 20,
  "deadMidMinDeadSignals": 3,
  "binScrubArThresholdPct": 10,
  "convesioIntegrationId": "",
  "alertsEnabled": true,
  "alertsTelegramBotToken": "",
  "alertsTelegramChatId": "-1000000000000",
  "alertsWindowHours": 1,
  "alertsMinCharges": 20,
  "alertsArFloorPct": 40,
  "alertsMidArFloorPct": 30,
  "alertsErrorRatePct": 20,
  "alertsCapWarnPct": 90,
  "binMapEnabled": true,
  "binMapMinBinAttempts": 20,
  "binMapMinMidAttempts": 10,
  "binMapMinArPct": 50,
  "brandSyncEnabled": true,
  "brandSyncWindowHours": 168,
  "binScrubAuditEnabled": true,
  "binScrubAuditWindowHours": 720,
  "binScrubAuditMinAttempts": 50,
  "binScrubAuditMinNetLossCents": 0,
  "binScrubAuditAutoEnforce": false,
  "rebillCrossAccountAllowed": false,
  "applePayEnabled": false,
  "alertsTelegramBotTokenSet": true
}
```

| response field | type | description |
|---|---|---|
| `(the whole settings object)` | object | The account's settings after the write, read back from the UPDATE ... RETURNING row - the same shape as GET /v1/settings (alertsTelegramBotToken "" + alertsTelegramBotTokenSet - v3.9.8 item 7). |
| `timezone` | string | IANA zone of the account: the daily window of the 'round_robin' dispatch and the dashboard clock. Default 'America/New_York'. |
| `applePayEnabled` | boolean | ACCOUNT-WIDE Apple Pay switch (account_settings.apple_pay_enabled, migration 130, default true). false = GET /v1/checkouts/:shopId/routing answers applePay false for every store of the account (applePayGlobal carries this value), POST /wallet/sessions refuses every Apple session on one of the account's wallet providers with { eligible: false, reason: 'apple_pay_disabled' }, POST /wallet/sessions/:id/charge answers 403 for an Apple session already open and the hosted /s/:id page renders a fallback instead of the sheet. Nothing on the shops' routing rows or on the providers' apple_pay_enabled flags is touched; Google Pay is not affected. Flipped from /wallet-providers. |

**Errors**

- `400` `{"error":"Invalid request","details":{...}}` when a field has the wrong type or is out of bounds, or the body has no known field (`Nothing to update`); `{"error":"Unknown timezone: <value>"}` when timezone is not an IANA zone.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Only the fields present are written; null is not accepted for any field. Unknown fields are ignored (the schema is not strict), so a misspelled field alone answers 400 `Nothing to update` and next to a valid one is silently dropped.
- Changes reach the charge path within the 30-second settings cache of each server process.
- alertsTelegramBotToken is answered "" with alertsTelegramBotTokenSet, like GET.

##### `GET /v1/settings/credentials`

**Scope** `settings.write` - **Reveal the stored Telegram bot token**

Returns the account's stored Telegram bot token in clear for the dashboard's alerts form. It never answers 200 to an API key: the token can be written with PATCH /v1/settings but not read back through the API.

*No parameters.*

**Response**

```json
{
  "alertsTelegramBotToken": "000000000:EXAMPLE-not-a-real-token"
}
```

| response field | type | description |
|---|---|---|
| `alertsTelegramBotToken` | string | The stored token, "" when unset. |

**Errors**

- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"settings.write"}: the key lacks settings.write, refused by the gate before anything is read or decrypted. {"error":"Stored secrets are only returned to a role that may edit this configuration"}: a member whose role may read but not edit it.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- Not usable with an API key (always 403). Use alertsTelegramBotTokenSet from GET /v1/settings to know whether a token is stored, and PATCH /v1/settings to replace it.

#### Agreements

The account's CRM agreements: generate, read, download and sign.

##### `GET /v1/me/agreements`

**Scope** `billing.read` - **List account CRM agreements**

Lists the account's CRM agreements (drafts and signed), newest first, with the current template metadata: provider identity, the pricing a new draft would carry (the account's assigned platform plan when it has one) and the template version. No statement or billing action exists here.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `25` | no | Rows per page, 1 to 100; newest first. |
| `offset` | integer; default `0` | no | Rows to skip, an integer >= 0. Any other query parameter is a 400 (strict). |

**Response**

```json
{
  "rows": [
    {
      "id": "11111111-1111-4111-8111-111111111111",
      "kind": "main",
      "client": {
        "firstName": "Jane",
        "lastName": "Example",
        "company": "Example Commerce LLC",
        "address": "10 Example Road, Dubai, UAE",
        "email": "legal@example.com",
        "title": "Director"
      },
      "version": "2026-11-02.1",
      "created_at": "2026-11-20T10:00:00.000Z",
      "signed_at": null,
      "created_by": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
      "signed_by": null,
      "content_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    }
  ],
  "hasMore": false,
  "version": "2026-11-02.1",
  "pricing": {
    "currency": "USD",
    "monthlyFeeCents": 79900,
    "successfulVolumeBasisPoints": 0
  },
  "provider": {
    "name": "NOCOMP FZCO",
    "brand": "Kontrol",
    "address": "<provider address>",
    "email": "legal@example.com"
  },
  "canManage": true,
  "canSign": true
}
```

| response field | type | description |
|---|---|---|
| `rows` | array | Page of agreements: id, kind, client {firstName, lastName, company, address, email, title}, version, created_at, signed_at, created_by, signed_by, content_hash. created_by and signed_by name the caller: the login e-mail, or apikey:<keyId> (<key name>) when an API key made the call. |
| `hasMore` | boolean | Whether another page exists. |
| `pricing` | object | Current template currency USD, monthlyFeeCents 79900, successfulVolumeBasisPoints 30 (0.3% of successful captured/settled payment volume). Historical records retain their own pricing. |
| `provider` | object | Provider legal identity and notice details. |
| `version` | string | Template version a new draft is labelled with in this list: 2026-11-17.1 when the account has an assigned platform plan, else 2026-11-02.1. (The snapshot of a new draft carries its own version field.) |
| `canManage / canSign` | boolean | Caller capabilities: true for the account owner, an account administrator and an API key of the account (canSign equals canManage). |
| `pricing.intervalMonths` | integer? | Assigned offer cadence. Absent on legacy templates, meaning monthly. |
| `pricing.planName` | string? | Assigned offer name, when present. |

**Errors**

- `400` {"error":"Invalid pagination"} when limit or offset is out of range or an unknown query parameter is sent.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"An active account is required."} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All responses are private/no-store. No endpoint charges a card, creates a subscription, creates a login/sub-account, or changes routing.
- kind=main and kind=sub_account only group history in the UI; the legal text is identical and makes no reference to a parent company.
- Signed records and their snapshotted terms cannot be edited. Generate a new draft for changes. IDs are globally unique; repeat creation with the same ID and identical body returns the same document.
- Signature acceptance retains the typed name, authenticated operator, server UTC timestamp, request IP/user-agent, exact content SHA-256, and an acceptance-record SHA-256. This is not a qualified electronic-signature service or independent identity certificate.
- Template 2026-10-21.1 includes snapshot.providerSignature (the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21). This is a provider mark only: signed_at remains null until the client explicitly accepts. Older snapshots without this field never receive a retrospective provider signature. PDF styling does not alter stored legal terms.
- Template 2026-11-02.1 uses a flat USD 799 monthly fee with no sales percentage. Existing signed snapshots and acceptance evidence are never rewritten.
- No new charge or billing mandate is created. Unassigned legacy accounts retain their prior template. monthlyFeeCents is a compatibility field holding the amount per intervalMonths; intervalMonths defaults to 1 for old snapshots.

##### `POST /v1/me/agreements`

**Scope** `billing.write` - **Generate a CRM agreement draft**

Validate party fields and snapshot the complete English agreement. New drafts include the authorised pre-applied provider signature and await separate client acceptance. New drafts use the assigned subscription offer snapshot, including exact price, interval, limits and revision. Existing drafts and signed contracts retain their saved commercial terms.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Fresh client-generated UUID. Retrying identical creation with the same UUID returns the same agreement; changed payload with that UUID returns 409. |
| `kind` | enum: main\|sub_account | **yes** | History grouping only; both generate the same independent contract without a parent-company clause. |
| `client` | object | **yes** | Required client identity; only the fields listed below are accepted. |
| `client.firstName` | string | **yes** | Trimmed, maximum 100 characters. Required and nonempty. |
| `client.lastName` | string | **yes** | Trimmed, maximum 100 characters. Required and nonempty. |
| `client.company` | string | **yes** | Trimmed, maximum 250 characters. Required and nonempty. |
| `client.address` | string | **yes** | Trimmed, maximum 1500 characters. Required and nonempty. |
| `client.email` | string | **yes** | Valid email address; Trimmed, maximum 254 characters. Required and nonempty. |
| `client.title` | string | no | Trimmed, maximum 150 characters. Optional, defaults to an empty string. |

**Request body**

```json
{
  "id": "11111111-1111-4111-8111-111111111111",
  "kind": "main",
  "client": {
    "firstName": "Jane",
    "lastName": "Example",
    "company": "Example Commerce LLC",
    "address": "10 Example Road, Dubai, UAE",
    "email": "legal@example.com",
    "title": "Director"
  }
}
```

**Response** `200`

```json
{
  "agreement": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "main",
    "request_hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    "snapshot": {
      "title": "CRM Service Agreement",
      "version": "2026-11-02.1",
      "client": {
        "firstName": "Jane",
        "lastName": "Example",
        "company": "Example Commerce LLC",
        "address": "10 Example Road, Dubai, UAE",
        "email": "legal@example.com",
        "title": "Director"
      },
      "provider": {
        "name": "NOCOMP FZCO",
        "brand": "Kontrol",
        "address": "<provider address>",
        "email": "legal@example.com"
      },
      "pricing": {
        "currency": "USD",
        "monthlyFeeCents": 79900,
        "successfulVolumeBasisPoints": 0
      },
      "sections": [
        {
          "title": "1. Parties, scope and formation",
          "paragraphs": [
            "The response contains the complete contract text."
          ]
        }
      ],
      "providerSignature": {
        "name": "Alex Example",
        "title": "Authorised representative",
        "method": "pre-applied electronic signature",
        "authorisedOn": "2026-10-21"
      }
    },
    "content_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "created_by": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
    "created_at": "2026-11-20T10:00:00.000Z",
    "signed_at": null,
    "signed_by": null,
    "signature": null,
    "evidence": null
  }
}
```

| response field | type | description |
|---|---|---|
| `agreement` | object | The stored record: id, owner_email, kind, request_hash, snapshot (title, version, provider, pricing, optional plan, client, complete sections, providerSignature), content_hash, created_by, created_at, signed_at, signed_by, signature, evidence. Null signature fields mean an unsigned draft. created_by and signed_by name the caller: the login e-mail, or apikey:<keyId> (<key name>) when an API key made the call. |
| `agreement.snapshot.providerSignature` | object \| absent | New snapshots: the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21. Missing in older snapshots; do not add it retrospectively. |
| `agreement.signed_at` | ISO timestamp \| null | Client acceptance time only. The pre-applied provider mark does not set this field. |
| `agreement.snapshot.plan` | object? | Immutable assigned offer ID/revision, price, interval, modules, quotas and quota FX rates. A new template does not modify any signed record. |

**Errors**

- `400` {"error":"Complete all required agreement fields.","details":<zod flatten()>} for a missing or invalid field, control characters, or an unknown field (strict at every level).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"An active account is required."} when the caller resolves to no account.
- `409` {"error":"This request ID has already been used. Create a new draft."} when the id exists with a different body (or in another account).
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} on an unexpected failure.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All responses are private/no-store. No endpoint charges a card, creates a subscription, creates a login/sub-account, or changes routing.
- kind=main and kind=sub_account only group history in the UI; the legal text is identical and makes no reference to a parent company.
- Signed records and their snapshotted terms cannot be edited. Generate a new draft for changes. IDs are globally unique; repeat creation with the same ID and identical body returns the same document.
- Signature acceptance retains the typed name, authenticated operator, server UTC timestamp, request IP/user-agent, exact content SHA-256, and an acceptance-record SHA-256. This is not a qualified electronic-signature service or independent identity certificate.
- Use a fresh UUID for a new document. POSTing again is not a new monthly charge. To revise details create another draft; signing is separate.
- Template 2026-10-21.1 includes snapshot.providerSignature (the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21). This is a provider mark only: signed_at remains null until the client explicitly accepts. Older snapshots without this field never receive a retrospective provider signature. PDF styling does not alter stored legal terms.
- Template 2026-11-02.1 uses a flat USD 799 monthly fee with no sales percentage. Existing signed snapshots and acceptance evidence are never rewritten.
- No new charge or billing mandate is created. Unassigned legacy accounts retain their prior template. monthlyFeeCents is a compatibility field holding the amount per intervalMonths; intervalMonths defaults to 1 for old snapshots.

##### `GET /v1/me/agreements/:id`

**Scope** `billing.read` - **Read a CRM agreement**

Retrieve the exact saved text and electronic acceptance evidence for review; never substitutes the latest template.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Agreement UUID returned by creation, belonging to this account. |

**Response**

```json
{
  "agreement": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "main",
    "request_hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    "snapshot": {
      "title": "CRM Service Agreement",
      "version": "2026-11-02.1",
      "client": {
        "firstName": "Jane",
        "lastName": "Example",
        "company": "Example Commerce LLC",
        "address": "10 Example Road, Dubai, UAE",
        "email": "legal@example.com",
        "title": "Director"
      },
      "provider": {
        "name": "NOCOMP FZCO",
        "brand": "Kontrol",
        "address": "<provider address>",
        "email": "legal@example.com"
      },
      "pricing": {
        "currency": "USD",
        "monthlyFeeCents": 79900,
        "successfulVolumeBasisPoints": 0
      },
      "sections": [
        {
          "title": "1. Parties, scope and formation",
          "paragraphs": [
            "The response contains the complete contract text."
          ]
        }
      ],
      "providerSignature": {
        "name": "Alex Example",
        "title": "Authorised representative",
        "method": "pre-applied electronic signature",
        "authorisedOn": "2026-10-21"
      }
    },
    "content_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "created_by": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
    "created_at": "2026-11-20T10:00:00.000Z",
    "signed_at": null,
    "signed_by": null,
    "signature": null,
    "evidence": null
  }
}
```

| response field | type | description |
|---|---|---|
| `agreement` | object | The stored record: id, owner_email, kind, request_hash, snapshot (title, version, provider, pricing, optional plan, client, complete sections, providerSignature), content_hash, created_by, created_at, signed_at, signed_by, signature, evidence. Null signature fields mean an unsigned draft. created_by and signed_by name the caller: the login e-mail, or apikey:<keyId> (<key name>) when an API key made the call. evidence (when signed): {accepted, actor, signedAt, contentHash, recordHash, ip, userAgent}. |
| `agreement.snapshot.providerSignature` | object \| absent | New snapshots: the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21. Missing in older snapshots; do not add it retrospectively. |
| `agreement.signed_at` | ISO timestamp \| null | Client acceptance time only. The pre-applied provider mark does not set this field. |

**Errors**

- `400` {"error":"Invalid agreement ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"An active account is required."} when the caller resolves to no account.
- `404` {"error":"Agreement not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All responses are private/no-store. No endpoint charges a card, creates a subscription, creates a login/sub-account, or changes routing.
- kind=main and kind=sub_account only group history in the UI; the legal text is identical and makes no reference to a parent company.
- Signed records and their snapshotted terms cannot be edited. Generate a new draft for changes. IDs are globally unique; repeat creation with the same ID and identical body returns the same document.
- Signature acceptance retains the typed name, authenticated operator, server UTC timestamp, request IP/user-agent, exact content SHA-256, and an acceptance-record SHA-256. This is not a qualified electronic-signature service or independent identity certificate.
- Template 2026-10-21.1 includes snapshot.providerSignature (the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21). This is a provider mark only: signed_at remains null until the client explicitly accepts. Older snapshots without this field never receive a retrospective provider signature. PDF styling does not alter stored legal terms.
- Template 2026-11-02.1 uses a flat USD 799 monthly fee with no sales percentage. Existing signed snapshots and acceptance evidence are never rewritten.

##### `GET /v1/me/agreements/:id/pdf`

**Scope** `billing.read` - **Download CRM agreement PDF**

Render the stored full contract into a branded, paginated PDF with local Inter fonts, handwritten-style signature typography, cost table, clickable contents and evidence page. Drafts are marked as awaiting client acceptance.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Agreement UUID returned by creation, belonging to this account. |

**Response** `200` (application/pdf)

```json
{
  "contentType": "application/pdf",
  "filename": "Kontrol-CRM-Agreement-11111111-1111-4111-8111-111111111111.pdf"
}
```

| response field | type | description |
|---|---|---|
| `binary body` | application/pdf | Actual PDF bytes, not JSON or an HTML print page. Content-Disposition attachment. Fonts are embedded; no remote resource requests. |

**Errors**

- `400` {"error":"Invalid agreement ID"} when id is not a uuid.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"An active account is required."} when the caller resolves to no account.
- `404` {"error":"Agreement not found"}.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} when rendering fails.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Downloads the complete stored contract as a binary PDF, not JSON. Local Inter and handwriting-style signature fonts; no decorative icons; a subtle orange-to-white page-top strip and a clickable kontrolcheckout.com footer. Styling never changes the saved agreement text or acceptance evidence.
- All responses are private/no-store. No endpoint charges a card, creates a subscription, creates a login/sub-account, or changes routing.
- kind=main and kind=sub_account only group history in the UI; the legal text is identical and makes no reference to a parent company.
- Signed records and their snapshotted terms cannot be edited. Generate a new draft for changes. IDs are globally unique; repeat creation with the same ID and identical body returns the same document.
- Signature acceptance retains the typed name, authenticated operator, server UTC timestamp, request IP/user-agent, exact content SHA-256, and an acceptance-record SHA-256. This is not a qualified electronic-signature service or independent identity certificate.
- Template 2026-10-21.1 includes snapshot.providerSignature (the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21). This is a provider mark only: signed_at remains null until the client explicitly accepts. Older snapshots without this field never receive a retrospective provider signature. PDF styling does not alter stored legal terms.
- Template 2026-11-02.1 uses a flat USD 799 monthly fee with no sales percentage. Existing signed snapshots and acceptance evidence are never rewritten.

##### `POST /v1/me/agreements/:id/sign`

**Scope** `billing.write` - **Sign a CRM agreement**

Records the client's acceptance of a saved agreement: the typed full name of the signatory, explicit acceptance and the exact content hash that was reviewed. The server stores the signer (login e-mail or API key label), the UTC time, the request IP and User-Agent, the content SHA-256 and an acceptance-record SHA-256. An API key of the account can sign: the record then names the key, never a person.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Agreement UUID returned by creation. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `contentHash` | string | **yes** | Exact current content_hash from the agreement detail: 64 lowercase hexadecimal characters. |
| `signature` | string | **yes** | Typed full name of the client signatory, matching the saved first and last names; trimmed, 1-201 characters. |
| `acceptAgreement` | boolean | **yes** | Must be literal true after the client reviews and accepts the contract. |

**Request body**

```json
{
  "contentHash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "signature": "Jane Example",
  "acceptAgreement": true
}
```

**Response**

```json
{
  "agreement": {
    "id": "11111111-1111-4111-8111-111111111111",
    "owner_email": "owner@example.com",
    "kind": "main",
    "request_hash": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    "snapshot": {
      "title": "CRM Service Agreement",
      "version": "2026-11-02.1",
      "client": {
        "firstName": "Jane",
        "lastName": "Example",
        "company": "Example Commerce LLC",
        "address": "10 Example Road, Dubai, UAE",
        "email": "legal@example.com",
        "title": "Director"
      },
      "provider": {
        "name": "NOCOMP FZCO",
        "brand": "Kontrol",
        "address": "<provider address>",
        "email": "legal@example.com"
      },
      "pricing": {
        "currency": "USD",
        "monthlyFeeCents": 79900,
        "successfulVolumeBasisPoints": 0
      },
      "sections": [
        {
          "title": "1. Parties, scope and formation",
          "paragraphs": [
            "The response contains the complete contract text."
          ]
        }
      ],
      "providerSignature": {
        "name": "Alex Example",
        "title": "Authorised representative",
        "method": "pre-applied electronic signature",
        "authorisedOn": "2026-10-21"
      }
    },
    "content_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "created_by": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
    "created_at": "2026-11-20T10:00:00.000Z",
    "signed_at": "2026-11-20T10:05:00.000Z",
    "signed_by": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
    "signature": "Jane Example",
    "evidence": {
      "accepted": true,
      "actor": "apikey:4b1d9c2e-7a3f-4e6b-9c8d-2f1a0e5b7c36 (Agent key)",
      "signedAt": "2026-11-20T10:05:00.000Z",
      "contentHash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "recordHash": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
      "ip": "203.0.113.10",
      "userAgent": "agent/1.0"
    }
  }
}
```

| response field | type | description |
|---|---|---|
| `agreement` | object | The signed record (same shape as GET /v1/me/agreements/:id) with signed_at, signed_by, signature and evidence {accepted, actor, signedAt, contentHash, recordHash, ip, userAgent} set. |

**Errors**

- `400` {"error":"A valid agreement, signature and explicit acceptance are required."} for an invalid id or body (strict); {"error":"Enter the full name of the signatory shown in the agreement."} when signature does not match.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"An active account is required."} when the caller resolves to no account.
- `404` {"error":"Agreement not found"}.
- `409` {"error":"The agreement does not match the version reviewed. Reload it before signing."}; {"error":"This agreement has already been signed and cannot be changed."}; {"error":"This agreement has already been signed. Reload it."}
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All responses are private/no-store. No endpoint charges a card, creates a subscription, creates a login/sub-account, or changes routing.
- kind=main and kind=sub_account only group history in the UI; the legal text is identical and makes no reference to a parent company.
- Signed records and their snapshotted terms cannot be edited. Generate a new draft for changes. IDs are globally unique; repeat creation with the same ID and identical body returns the same document.
- Signature acceptance retains the typed name, authenticated operator, server UTC timestamp, request IP/user-agent, exact content SHA-256, and an acceptance-record SHA-256. This is not a qualified electronic-signature service or independent identity certificate.
- contentHash is the exact 64-character lowercase SHA-256 returned by GET. signature is 1-201 trimmed characters and must match the stated first and last name (Unicode-normalised, case-insensitive). acceptAgreement must be literal true. No backdated or client-supplied audit metadata.
- Template 2026-10-21.1 includes snapshot.providerSignature (the provider's authorised representative (title Authorised representative), pre-applied electronic signature, authorisedOn 2026-10-21). This is a provider mark only: signed_at remains null until the client explicitly accepts. Older snapshots without this field never receive a retrospective provider signature. PDF styling does not alter stored legal terms.
- Template 2026-11-02.1 uses a flat USD 799 monthly fee with no sales percentage. Existing signed snapshots and acceptance evidence are never rewritten.
- contentHash must be the exact 64-character lowercase content_hash returned by GET /v1/me/agreements/:id; signature must equal the saved "firstName lastName" (Unicode-normalised, case-insensitive); acceptAgreement must be true.
- Idempotent for the same signer: repeating the identical signature returns the existing acceptance. Another signer, a different signature or changed content answers 409.
- An agent should sign only on the explicit instruction of the account holder: the acceptance is a legal record bound to the key that made it. created_by and signed_by name the caller: the login e-mail, or apikey:<keyId> (<key name>) when an API key made the call.

#### Logs

The logs of the account: charge requests, actions (audit), server errors, filter blocks, checkout events and wallet payments.

- Page totals of the charge and charge-batch logs are summed in the browser; every log export is built in the browser from the list endpoint.

##### `GET /v1/audit-logs`

**Scope** `operations.read` - **List audit logs**

Read the account's action log (the dashboard Action logs view), newest first, with offset pagination. A row is written for every successful mutating account request (POST, PUT, PATCH or DELETE answered below 400) made by a member of the account or with one of its API keys. Read only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer (1..10000); default `100` | no | Rows to return. Coerced from the query string; outside 1..10000, a decimal or a non-number answers 400 (never clamped). |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. Coerced; negative or non-numeric answers 400. |

**Response**

```json
{
  "logs": [
    {
      "id": "3f2a8c14-9b6e-4d31-a0f7-7c5e1b9d4482",
      "user_email": "owner@example.com",
      "action": "update",
      "object_type": "trip",
      "object_id": "a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
      "object_name": "US Retail ATRI",
      "page": "ATRI",
      "method": "PATCH",
      "path": "/v1/trips/a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
      "status": 200,
      "created_at": "2026-11-20T14:03:11.482Z",
      "total": 2
    },
    {
      "id": "9c71e5b0-2d48-4f6a-b3c2-118ad6e7f905",
      "user_email": "owner@example.com",
      "action": "create",
      "object_type": "key",
      "object_id": null,
      "object_name": "agent key",
      "page": "API Keys",
      "method": "POST",
      "path": "/v1/keys",
      "status": 200,
      "created_at": "2026-11-20T13:47:02.117Z",
      "total": 2
    }
  ],
  "total": 2
}
```

| response field | type | description |
|---|---|---|
| `logs` | object[] | Audit rows ordered by created_at descending. Empty when nothing matches or offset is past the end. |
| `logs[].id` | string (uuid) | Row id. Random, not sequential: never use it to order or as a cursor. |
| `logs[].user_email` | string \| null | Who acted: the member's e-mail, or the account owner's e-mail for a request made with an API key. |
| `logs[].action` | string | create (POST), update (PUT or PATCH), delete (DELETE), set_default (path ends /default), update_membership (path ends /accounts), or ban / unban (member ban path). |
| `logs[].object_type` | string | Resource kind derived from the path: account, trip, key, subscription, integration, checkout, customer, discount_code, trip_membership, user, editor_font and so on; an unmapped resource keeps its raw path segment (for example wallet-providers). |
| `logs[].object_id` | string \| null | The id segment of the path when it looks like a uuid or hex id (8+ characters of 0-9a-f and hyphens); otherwise null. |
| `logs[].object_name` | string \| null | The body field name when it was a string; for member operations (create member, role change, password, ATRI grants) the validated target e-mail; for a ban the banned e-mail; otherwise null. |
| `logs[].page` | string \| null | Dashboard section label (ATRI, NMI Accounts, API Keys, Subscriptions, Checkouts, Clients, ...) or the raw resource segment. |
| `logs[].method` | string | HTTP method of the recorded request. |
| `logs[].path` | string | Path of the recorded request without its query string, as routed internally (account routes are recorded under their internal prefix even when called under /v1). |
| `logs[].status` | integer | Response status of the recorded request, always below 400. |
| `logs[].created_at` | string (ISO 8601) | When the row was written. |
| `logs[].total` | integer | The window count repeated in every row; read the top-level total instead. |
| `total` | integer | Rows matching the account filter, ignoring limit and offset. On an empty page with offset > 0 it is recounted, so it stays correct past the end. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten>}: limit or offset out of range or not an integer.
- `401` Missing bearer token; or Invalid API key.
- `402` A paid platform subscription is required (code subscription_required).
- `403` API key scope denied (code insufficient_scope; requiredScope names the missing scope); or Banned (the account owner is banned).
- `503` Authentication scope is temporarily unavailable.

**Gotchas**

- No filter beyond limit and offset: no date range, action, object or user filter. Page with offset.
- Only successful mutations are recorded. Failed or refused requests and reads leave no row.
- Rows are written best effort after the response: a row can be missing after a database hiccup and may appear a moment after the mutation returns.
- Ordering is created_at descending with no tie breaker; rows written in the same millisecond can move between pages.
- Actions of a platform operator acting as the account (mutations and reads) are recorded under the operator's e-mail, which is not an account member, so they do not appear in this account's log.
- Every row also carries a redundant total field; a strict client schema must allow it.

##### `GET /v1/charge-logs`

**Scope** `operations.read` - **List /v1/charge requests (every call, refused ones included)**

Lists every POST /v1/charge request of the account, refused ones included; the external rebill tool's batches are GET /v1/subscription-charge-logs and the subscription engine's charges GET /v1/subscription/transactions. Read-only, paginated feed of the account's POST /v1/charge requests (charge_request_logs), newest first, including requests refused for validation, a banned owner or routing overrides, which never became transactions.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `outcome` | enum: accepted \| auth_failed \| invalid_body \| error | no | Exact filter on the log classification. accepted = processed (processor declines included); auth_failed = key refused (for an account this is the banned-owner 403, since an unknown key has no account); invalid_body = request refused before charging (400 or 422); error = auth lookup failure (503) or processing exception (500). Any other value is a 400. |
| `limit` | integer, 1..10000; default `100` | no | Page size. Out of range is a 400, not clamped. |
| `offset` | integer >= 0; default `0` | no | Rows to skip after ordering by created_at descending. |

**Response**

```json
{
  "logs": [
    {
      "id": "9f3c1e2a-7b64-4f0d-9c31-2ad8e5b7f104",
      "created_at": "2026-11-24T14:32:07.481Z",
      "remote_ip": "203.0.113.44",
      "api_key_id": "b1d4c8f2-3e57-4a19-8c62-9f0e1a7d3b85",
      "key_prefix": "ck_live_9f2",
      "method": "POST",
      "outcome": "accepted",
      "status_code": 200,
      "order_count": 3,
      "error": "1/3 order(s) not approved",
      "detail": null
    },
    {
      "id": "1c07b5d9-4e82-4b3a-a6f1-77c9e2401db3",
      "created_at": "2026-11-24T14:31:52.007Z",
      "remote_ip": "198.51.100.12",
      "api_key_id": "b1d4c8f2-3e57-4a19-8c62-9f0e1a7d3b85",
      "key_prefix": "ck_live_9f2",
      "method": "POST",
      "outcome": "invalid_body",
      "status_code": 422,
      "order_count": null,
      "error": "Gateway targets cannot override checkout routing",
      "detail": null
    },
    {
      "id": "5ab3f710-9d2c-42e8-b0c4-8e15d6a9f223",
      "created_at": "2026-11-24T14:29:18.664Z",
      "remote_ip": "203.0.113.44",
      "api_key_id": "b1d4c8f2-3e57-4a19-8c62-9f0e1a7d3b85",
      "key_prefix": "ck_live_9f2",
      "method": "POST",
      "outcome": "invalid_body",
      "status_code": 400,
      "order_count": null,
      "error": "Invalid order",
      "detail": {
        "formErrors": [],
        "fieldErrors": {
          "amount": [
            "Expected number, received string"
          ],
          "email": [
            "Invalid email"
          ]
        }
      }
    }
  ],
  "total": 1284
}
```

| response field | type | description |
|---|---|---|
| `logs` | object[] | The page of log rows, newest first (`order by created_at desc`). At most `limit` entries. |
| `logs[].id` | string (uuid) | Primary key of the log row (`gen_random_uuid()`). Not a transaction id and not correlatable to one - there is no transaction_id column on this table. |
| `logs[].created_at` | string (ISO 8601 timestamptz) | When the charge request was logged (effectively when it finished). This is the only time column and the sole sort key. |
| `logs[].remote_ip` | string \| null | Caller IP as seen by the API. Null when it could not be determined. |
| `logs[].api_key_id` | string (uuid) \| null | The api_keys row that authenticated the request (always one of the account's keys in this feed). FK is on delete set null: a deleted key's history leaves the account feed. |
| `logs[].key_prefix` | string \| null | First 11 characters of the key the caller presented, for example "ck_live_9f2". |
| `logs[].method` | string | HTTP method of the logged request. Always "POST" in practice - /v1/charge is registered only as app.post, so this column has exactly one value and is useless as a filter. |
| `logs[].outcome` | enum: accepted\|auth_failed\|invalid_body\|error | accepted \| auth_failed \| invalid_body \| error. accepted means processed, NOT approved. |
| `logs[].status_code` | integer | HTTP status returned: 200 (accepted, declines included), 400 or 422 (invalid_body), 403 (auth_failed, banned owner), 500 or 503 (error). |
| `logs[].order_count` | integer \| null | Orders in the request when known (accepted rows, the 422 subscription opt-in refusals, some errors); null when the body never parsed. |
| `logs[].error` | string \| null | Human-readable error or summary. On `accepted` rows this is null when everything approved, or "N/M order(s) not approved" / "N/M rebill(s) not approved" when the processor declined some - so a non-null `error` on a 200 row is how you detect declines. |
| `logs[].detail` | object \| null | Structured detail (jsonb): the zod flatten shape for an invalid order or batch, the offending orders for a subscription opt-in refusal; null otherwise. Treat as opaque. |
| `total` | integer | Count of rows matching the account scope and the outcome filter. An empty page past the end still reports the real total (a separate count is run). |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: limit outside 1..10000, negative or non-integer offset, or an outcome outside the four values.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- outcome=accepted does NOT mean the payment succeeded: declines are logged accepted / 200 with `error` = "N/M order(s) not approved" (or "rebill(s)"). Parse `error` on 200 rows.
- outcome is the only filter: no date range, key or status filter. Page with offset and read created_at.
- Pagination is a live append feed ordered by created_at only; deep offsets can skip or repeat rows while new requests arrive.
- Unknown query parameters are ignored (a misspelled filter returns the unfiltered page).
- Log writes are best effort and not awaited: a missing row does not prove a request never happened.
- duration_ms is stored but not returned here; GET /v1/perf reports the latency percentiles.
- Requests with a missing or unknown key are not attributed to any account and never appear in an account's feed.

##### `GET /v1/checkouts/event-types`

**Scope** `tracking.read` - **List the checkout event types in use**

The event types the caller's stores actually emitted over the last 30 days, each with its volume and journey stage, sorted by count: the vocabulary for the type filter of GET /v1/checkouts/events.

*No parameters.*

**Response**

```json
{
  "rows": [
    {
      "type": "product_view",
      "stage": "browse",
      "count": 8562
    },
    {
      "type": "field_focus",
      "stage": "checkout",
      "count": 2700
    },
    {
      "type": "abandon",
      "stage": "trouble",
      "count": 1872
    }
  ],
  "shops": [
    {
      "id": "...",
      "name": "HOOMA",
      "domain": "shop.example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | { type, stage, count }, highest count first. |
| `shops[]` | object[] | { id, name, domain } of the visible stores. |

**Errors**

- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- Counted over at most the 50 000 newest events of the last 30 days.
- A type the stage map does not know falls into stage other rather than being hidden.

##### `GET /v1/checkouts/events`

**Scope** `tracking.read` - **List checkout events (flat, filterable)**

The flat checkout event stream of the caller's stores, newest first, filterable by store, journey stage, exact type, device, country, journey id and time window. Each row carries a stage (browse, checkout, pay, outcome, recovery, trouble, other) so a reader sees the shape of a session without knowing every event name.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `shop` | uuid | no | One store. A store that is not among the caller's stores yields no rows (not a 404). Omitted = every visible store. |
| `type` | string or string[] | no | Exact event type; repeat the parameter for several (?type=pay_click&type=payment_success). No comma splitting. Wins over stage. List the types in use with GET /v1/checkouts/event-types. |
| `stage` | string | no | One of browse, checkout, pay, outcome, recovery, trouble, other. Narrows to the event types of that stage; other does not narrow (every type). |
| `device` | string | no | Exact ua_device_kind (for example mobile, desktop, tablet). Max 40 characters. |
| `country` | string | no | ISO 3166 alpha-2 country, upper-cased before matching. Max 2 characters. |
| `q` | string | no | A journey id matched exactly against cart_token, visitor_id and session_id. Max 200 characters. |
| `from` | string | no | Lower bound on occurred_at (inclusive): an ISO instant with offset or YYYY-MM-DD. |
| `to` | string | no | Upper bound on occurred_at (inclusive): an ISO instant with offset or YYYY-MM-DD. |
| `limit` | integer; default `500` | no | Rows to return, 1 to 5000 (coerced from the query string). |

**Response**

```json
{
  "rows": [
    {
      "id": "...",
      "shop_id": "...",
      "event_type": "payment_success",
      "stage": "outcome",
      "occurred_at": "2026-09-25T08:34:37.000Z",
      "cart_token": "owny145i055c",
      "visitor_id": null,
      "session_id": null,
      "country_iso2": "US",
      "ua_device_kind": "mobile",
      "browser": "Safari",
      "os": "iOS",
      "referrer_host": "facebook.com",
      "webview_kind": null,
      "load_time_ms": 1420,
      "nav_to_lcp_ms": 980,
      "metadata": {}
    }
  ],
  "shops": [
    {
      "id": "...",
      "name": "HOOMA",
      "domain": "shop.example.com"
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows[]` | object[] | id, shop_id, event_type, stage, occurred_at, cart_token, visitor_id, session_id, country_iso2, ua_device_kind, browser, os, referrer_host, webview_kind, load_time_ms, nav_to_lcp_ms, metadata. Newest first. |
| `shops[]` | object[] | { id, name, domain } of the visible stores. |

**Errors**

- `400` {"error":"Invalid","details":...}: a parameter failed validation (bad uuid, unknown stage, device or country too long, malformed from/to, limit outside 1 to 5000).
- `401` Missing bearer token, or invalid API key.
- `402` A paid platform subscription is required (code subscription_required): the account has no active platform subscription.
- `403` API key scope denied (code insufficient_scope, requiredScope names the missing scope); Your subscription does not include this tool. (code subscription_module_required, module stores): the plan lacks the stores module.
- `500` Internal Server Error with a requestId, including every checkout-database failure (a malformed UUID in a filter, a constraint violation).

**Gotchas**

- A row with no cart_token, visitor_id or session_id has no journey to open; the dashboard renders it as a plain row rather than a dead link.

##### `GET /v1/errors`

**Scope** `operations.read` - **List server errors**

Returns the durable server-error log of the caller's account, newest first, with the total number of matching rows. A row is written for every 5xx answered on an account route while a member of the account (or one of its API keys) was the caller, so a failure cannot vanish into ephemeral platform logs. Read-only.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer; default `50` | no | Rows per page, 1 to 10000. Coerced from the query string ("50" works). Out of range or not an integer (0, 10001, 1.5, "abc") answers 400; it is never clamped. |
| `offset` | integer; default `0` | no | Rows to skip, an integer >= 0. A negative or non-integer value answers 400. An offset past the end returns an empty page with the real total. |

**Response**

```json
{
  "errors": [
    {
      "id": "9f1c2d84-7b60-4a1e-95f3-0c6ad4e2b118",
      "created_at": "2026-11-20T14:02:51.734Z",
      "request_id": "req-7hk29fa1",
      "method": "POST",
      "path": "/v1/checkouts/2b8f6c1e-55aa-4c1e-9d3e-0f2a7b6c9d10/publish",
      "status": 500,
      "message": "A required data table is unavailable.",
      "user_email": "owner@example.com",
      "ip": "203.0.113.44"
    },
    {
      "id": "1a7b0e33-4c22-4d90-8f11-6ee9c0b7d502",
      "created_at": "2026-11-20T13:47:09.201Z",
      "request_id": "req-2pd81xz0",
      "method": "GET",
      "path": "/v1/transactions",
      "status": 500,
      "message": "Operation control deadline exceeded; reconnect to check its status",
      "user_email": "teammate@example.com",
      "ip": "198.51.100.7"
    }
  ],
  "total": 2
}
```

| response field | type | description |
|---|---|---|
| `errors` | object[] | One page of error rows, ordered by created_at descending. Length <= limit. |
| `errors[].id` | string (uuid) | Row id. |
| `errors[].created_at` | string (ISO 8601) | When the error was recorded; the only sort key. |
| `errors[].request_id` | string \| null | Request id of the failing call (the requestId a 500 answer carries). Quote it to support. |
| `errors[].method` | string \| null | HTTP method of the failing request. |
| `errors[].path` | string \| null | Path of the failing request, without the query string. A call made to a /v1 account address is recorded under its internal route prefix, so the stored path may differ from the address you called. |
| `errors[].status` | integer \| null | HTTP status that was answered (5xx). |
| `errors[].message` | string \| null | Server-side error message. Free text, not a stable code. |
| `errors[].user_email` | string \| null | The member who made the call (the account e-mail for an API key call); null only for anonymous rows, which only the platform owner sees. |
| `errors[].ip` | string \| null | Client IP of the failing request. |
| `total` | integer | Number of rows matching the account filter (not the page length). 0 on an empty first page. |

**Errors**

- `400` {"error":"Invalid","details":<zod flatten() with fieldErrors>} when limit or offset is out of range or not an integer.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"No account"} when the caller resolves to no account.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Internal Server Error","requestId":"<id>"} when the database read fails.
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- Only 5xx answers are recorded, and only those raised on account routes are attributed to the account: an error on a public route (POST /v1/charge, the storefront runtime, inbound webhooks) has no user and does not appear here.
- Any 503 (an unreachable database, a busy server), a request the client abandoned (499), every 4xx and a 5xx that a route answers itself without throwing are never written to this log.
- The stack trace is stored but never returned.
- There is no filter (date, status, path, request id): limit and offset are the only parameters. To find one request id, page through and match request_id.
- Offset paging over a table that grows continuously: a new error between two page reads shifts rows by one. Deduplicate on id.
- The insert is best-effort: if writing the row fails, the error is missing. An empty page does not prove that no error occurred.

##### `GET /v1/filters/hits`

**Scope** `routing.read` - **Read the filter block log**

The orders each filter has blocked on this account, newest first and paged, plus per-filter block counts (last 24 hours and total). Use it to tune false positives. GET /v1/rejections is the complete refusal log across every family.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer (1-10000); default `100` | no | Page size. |
| `offset` | integer (>= 0); default `0` | no | Rows to skip. |
| `key` | enum: email_provider \| max_order_per_ip \| device_mobile_only \| acquisition_required \| commercial_card_block \| velocity_guard \| credential_cutoff | no | Restrict rows and total to one filter (single value, not a list). |

**Response**

```json
{
  "rows": [
    {
      "id": "00000000-0000-4000-8000-000000000011",
      "created_at": "2026-11-24T09:58:11.402Z",
      "filter_key": "velocity_guard",
      "reason": "Blocked by velocity guard: 7 declined or refused attempts from this IP in the last hour (limit 6)",
      "order_id": "ORDER-1001",
      "transaction_id": null,
      "email_domain": "example.com",
      "ip": "203.0.113.7",
      "device_type": "mobile",
      "traffic_type": "meta",
      "bin": "411111",
      "total": 1
    }
  ],
  "total": 1,
  "stats": [
    {
      "filter_key": "velocity_guard",
      "hits_24h": 1,
      "hits_total": 12
    }
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | The page of rejections, ordered `created_at desc` (newest first). Length <= `limit`. |
| `rows[].id` | string (uuid) | Primary key of the `filter_hits` row. |
| `rows[].created_at` | string (ISO-8601 datetime) | When the block happened. The only time column, and the sort column. |
| `rows[].filter_key` | string | Which filter blocked: one of the six slugs. Plain text, not constrained by the DB. |
| `rows[].reason` | string | The internal reason string. For `device_mobile_only`, `acquisition_required` and `velocity_guard` this is the diagnostic text ('Blocked by filter: device type "desktop" not accepted'), which the customer NEVER saw — they got a generic decline. For `email_provider` and `commercial_card_block` it IS the customer-facing sentence. |
| `rows[].order_id` | string \| null | The merchant's order id (text, not a uuid). |
| `rows[].transaction_id` | string (uuid) \| null | Always null since v3.9 §1: a filter block is a rejection (charge_rejections), never a transaction row. Older hits kept the id of a row that has since been purged. |
| `rows[].email_domain` | string \| null | Domain part of the order email, lowercased. Null when the order carried no parseable email. The full email is deliberately NOT stored. |
| `rows[].ip` | string \| null | Order IP as supplied. |
| `rows[].device_type` | string \| null | `desktop` \| `mobile` \| `tablet` \| `other`, derived from the user-agent. Null when the order had no user-agent at all. |
| `rows[].traffic_type` | string \| null | `meta` \| `tiktok` \| `google` (v3.9.18) \| `other` \| `organic`, derived from trafficSource/fbclid/ttclid (and, for google, the label `google`). Never null in practice — a blank source classifies as `organic`. |
| `rows[].bin` | string \| null | First 6 digits of the PAN. The only card data recorded — no last4, no masked PAN, no CVV. |
| `total` | integer | Count of ALL rows matching the `key` filter, before limit/offset. Computed as a window function read off the FIRST returned row. |
| `stats` | object[] | Per-filter block counts across the WHOLE `filter_hits` table, ordered `hits_total desc`. Independent of `key`, `limit` and `offset`. |
| `stats[].filter_key` | string | Filter slug. Only filters with at least one recorded hit appear — a filter that has never blocked is absent, not zero. |
| `stats[].hits_24h` | integer | Blocks in the trailing 24 hours (`created_at >= now() - interval '24 hours'`). |
| `stats[].hits_total` | integer | All-time blocks for that filter. |

**Errors**

- `400` `{"error":"Invalid","details":{...}}` when limit is outside 1-10000, offset is negative or not an integer, or key is not one of the seven keys.
- `401` `{"error":"Missing bearer token"}` when no `Authorization: Bearer` header is sent; `{"error":"Invalid API key"}` when the key is unknown or revoked.
- `402` `{"error":"A paid platform subscription is required","code":"subscription_required"}`: the account has no paid or granted platform subscription.
- `403` `{"error":"API key scope denied","code":"insufficient_scope","requiredScope":"..."}` when the key's scopes do not include the scope this route needs; `{"error":"Banned","message":"..."}` when the account owner is banned; `{"error":"An active account owner is required for admin API access"}` when the key has no active owner account.
- `403` `{"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"payments"}` when the account's plan does not include the payments module.
- `503` `{"error":"Authentication scope is temporarily unavailable"}`: the account scope could not be loaded; retry later.

**Gotchas**

- total is read from the first row: an offset past the end returns rows [] and total 0.
- stats ignores key and omits filters with no hits.
- Each row also repeats the window total as a `total` field.
- reason is an English sentence with live numbers: match on filter_key, never parse reason. Only the first matching filter of an order is logged, writes are best effort, and rebills never appear.

##### `GET /v1/wallet-logs`

**Scope** `operations.read` - **Wallet Logs**

Paginated append-only trace of wallet (Apple/Google Pay) interactions: kind='session_pick' (the checkout asking which wallet MID to use, and which won) and kind='charge' (the charge sent to the provider, with the request/response payloads). Scoped to the caller's own wallet providers. Powers the Wallet Logs page.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `limit` | integer, 1..10000; default `50` | no | Page size. Out of range is a 400. |
| `offset` | integer >= 0; default `0` | no | Rows to skip. |
| `kind` | enum: session_pick \| charge | no | Event type. Strict: any other value (an empty string included) is a 400. Omit for both. |

**Response**

```json
{
  "rows": [
    {
      "id": "b81d4c33-2e0f-4a17-9f2c-7d5a1b6e0c22",
      "created_at": "2026-08-26T10:03:55.201Z",
      "kind": "charge",
      "outcome": "approved",
      "session_id": "6a0f8e21-9c44-4b3d-8f10-2ab7c9d5e134",
      "provider_id": "c9f2a7b0-1d33-4e58-b6aa-4f0c8e19d2b5",
      "provider_name": "Wallet MID EU-1",
      "shop_id": "1f7c4e90-55aa-4c21-9b8e-0d3f6a2c7e11",
      "wallet_kind": "apple",
      "amount_cents": 4999,
      "currency": "USD",
      "order_id": "ORD-10482",
      "transaction_id": "7e91c0da-3b58-4f6c-a2d9-8c14b7e05f63",
      "external_payment_id": "pay_9Xk2Lq",
      "redirect_url": null,
      "request_payload": { "amount": 4999, "token": { "paymentData": "(wallet payload, can be large)" } },
      "response_payload": { "status": "approved", "id": "pay_9Xk2Lq" },
      "remote_ip": "198.51.100.24",
      "error": null,
      "duration_ms": 1183,
      "total": 8642
    }
  ],
  "total": 8642
}
```

| response field | type | description |
|---|---|---|
| `rows` | array<object> | One object per wallet trace event, ordered by created_at desc. Length <= limit. |
| `rows[].id` | string (uuid) | Primary key of the wallet_logs row. |
| `rows[].created_at` | string (ISO-8601 timestamptz) | When the event was recorded. |
| `rows[].kind` | string | enum: session_pick\|charge. session_pick = the checkout's 'which wallet MID do I use' call; charge = the charge sent to the provider. |
| `rows[].outcome` | string | picked \| no_eligible_mid \| apple_pay_disabled (session_pick) or approved \| declined \| error (charge). Not filterable. |
| `rows[].session_id` | string (uuid) \| null | The wallet_sessions row this event belongs to; ties a session_pick to its later charge. |
| `rows[].provider_id` | string (uuid) \| null | The wallet provider (MID). Always one of the account's providers in this feed. |
| `rows[].provider_name` | string \| null | Denormalised provider label captured at write time; may be stale relative to wallet_providers. |
| `rows[].shop_id` | string (uuid) \| null | Storefront the wallet request came from. |
| `rows[].wallet_kind` | string \| null | enum in practice: apple\|google. |
| `rows[].amount_cents` | integer \| null | Amount in INTEGER CENTS (e.g. 4999 = 49.99). Never a decimal. Null on events with no amount. |
| `rows[].currency` | string \| null | ISO-4217 code, e.g. 'USD'. |
| `rows[].order_id` | string \| null | Merchant order id as supplied by the checkout (free text, not a uuid). |
| `rows[].transaction_id` | string (uuid) \| null | Our transactions.id, once the charge produced a transaction. |
| `rows[].external_payment_id` | string \| null | The provider's own payment identifier. |
| `rows[].redirect_url` | string \| null | Redirect issued to the shopper for the wallet flow, when applicable. |
| `rows[].request_payload` | object \| array \| null (parsed jsonb) | For kind='charge': the body POSTed to the provider (the full Apple/Google Pay payload). Returned as parsed JSON, not a string. Can be very large. |
| `rows[].response_payload` | object \| array \| null (parsed jsonb) | For kind='charge': the provider's raw response, parsed. Shape is provider-specific and unvalidated. |
| `rows[].remote_ip` | string \| null | IP of the checkout/shopper request. |
| `rows[].error` | string \| null | Error text when outcome is 'error' (and sometimes 'declined'); null otherwise. |
| `rows[].duration_ms` | integer \| null | Time spent on the provider call, in milliseconds. |
| `rows[].total` | integer | Window-function duplicate of the top-level `total`, repeated on every row. Ignore it. |
| `total` | integer | Rows matching the scope and kind filter. An empty page past the end still reports the real total (a separate count is run). |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: limit or offset out of range or not an integer, or kind other than session_pick / charge.
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner is banned; `Forbidden for your role` when the caller's member role cannot reach this route.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- An account without wallet providers gets an empty feed: events with no provider (for example a session pick that matched no eligible MID) are never shown to an account.
- `kind` is strict (a typo is a 400), unlike `outcome` on GET /v1/subscription-charge-logs.
- `outcome` is not a query parameter: filter declines and errors client-side.
- amount_cents is integer cents.
- request_payload / response_payload are parsed JSON objects holding the full wallet payloads: a large page can be several megabytes and the columns cannot be excluded.
- Every row repeats the page total in `total`; read the top-level `total`.
- No date, session, order or transaction filter and no sort control: newest first, page with offset.
- provider_name is a snapshot taken when the event was written.

#### Preferences

The personal dashboard preferences of the key owner's login: layouts, columns, favourites.

##### `GET /v1/me/prefs`

**Scope** `settings.read` - **Get my dashboard preferences**

Returns the caller's stored preference object (the keys the dashboard writes: dashboardLayout, favorites, tableColumns.<tableId>, dateDisplay, releaseAnnouncement:<releaseId>, described on PUT /v1/me/prefs): a free-form JSON object keyed by the login e-mail, {} when nothing was ever saved.

*No parameters.*

**Response**

```json
{
  "prefs": {
    "dashboardLayout": {
      "v": 1,
      "blocks": [
        { "id": "cards", "visible": true, "size": "full" },
        { "id": "chart", "visible": true, "size": "full" },
        { "id": "finance", "visible": false, "size": "full" }
      ],
      "hiddenCards": ["fees"]
    },
    "favorites": {
      "gateway": ["7d1c2b3a-4e5f-4a60-8b71-9c0d1e2f3a45", "wallet:5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e"],
      "atri": [],
      "subscription": [],
      "product": ["blue-widget"]
    },
    "tableColumns.gateways": { "visible": ["name", "status", "volume"], "order": ["name", "status", "volume", "cap"], "version": 2 },
    "dateDisplay": "relative",
    "releaseAnnouncement:v5.4": { "action": "dismissed", "at": "2026-11-20T09:15:00.000Z" }
  }
}
```

| response field | type | description |
|---|---|---|
| `prefs` | object | The whole stored object (opaque to the API). {} at first. |

**Errors**

- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token. `Unauthorized` when the caller resolves to no e-mail.
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner or the login is banned.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- Readable without a paid platform subscription (no 402).
- Personal, not per account: two members of one account each have their own preferences.
- A key reads the preferences row of its account owner's e-mail, the same row as the owner's own dashboard.
- Opaque to the API: whatever the dashboard stored comes back as-is.

##### `PUT /v1/me/prefs`

**Scope** `settings.write` - **Merge my dashboard preferences**

Shallow-merges the given object into the calling USER's stored preferences atomically (one upsert): every top-level key of `prefs` replaces the stored value of that key, keys not mentioned are kept, and a top-level null DELETES the key (back to default). Returns the merged object.

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `prefs` | object | **yes** | Map of top-level keys (1..64 characters) to any JSON value; a top-level null deletes that key. The serialised object must stay at or under 65536 bytes. The API stores any key; the keys the dashboard reads are listed below. |
| `prefs.dashboardLayout` | object | no | The Dashboard page layout: {v: 1, blocks: [{id, visible, size}], hiddenCards: [card id]}. blocks lists the dashboard blocks in display order (ids such as lastOrders, cards, chart, recentOrders, finance, atri, flow, store, traffic, brand, source, wallet, wire, products, gateways, declines, outcomes, alerts, threeDs); size is full, half or third (tables are always full). hiddenCards lists the data cards switched off (gross, net, success, declines, approvalRate, refunds, chargebacks, fees, ...). Unknown ids are dropped when read. |
| `prefs.favorites` | object | no | Starred items: {gateway: string[], atri: string[], subscription: string[], product: string[]}, at most 300 ids per kind (the dashboard refuses more). gateway holds card gateway ids and wallet providers as "wallet:<id>"; atri holds ATRI ids; subscription holds subscription product ids; product holds sold product slugs (handles). Starred rows sort first in every table and picker. The whole object is replaced on each write. |
| `prefs.tableColumns.<tableId>` | object \| null | no | One key per table, named "tableColumns." plus the table id (for example tableColumns.gateways, tableColumns.atri, tableColumns.bank-accounts, tableColumns.kontrolpay-payouts): {visible: string[], order: string[], version?: integer}, the column keys shown and their order. null restores the table's default columns. |
| `prefs.dateDisplay` | string | no | "relative" shows dates as "5 min ago" in the tables, anything else (or absent) shows absolute dates. |
| `prefs.releaseAnnouncement:<releaseId>` | object \| null | no | The acknowledgement of one release announcement: {action: "read" \| "dismissed", at: ISO date-time}. Once set, the release bar of that release is not shown again. |

**Request body**

```json
{
  "prefs": {
    "dashboardLayout": {
      "v": 1,
      "blocks": [
        { "id": "cards", "visible": true, "size": "full" },
        { "id": "chart", "visible": true, "size": "full" },
        { "id": "finance", "visible": false, "size": "full" }
      ],
      "hiddenCards": ["fees"]
    },
    "favorites": {
      "gateway": ["7d1c2b3a-4e5f-4a60-8b71-9c0d1e2f3a45", "wallet:5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e"],
      "atri": [],
      "subscription": [],
      "product": ["blue-widget"]
    },
    "tableColumns.gateways": { "visible": ["name", "status", "volume"], "order": ["name", "status", "volume", "cap"], "version": 2 },
    "dateDisplay": "relative",
    "releaseAnnouncement:v5.5": null
  }
}
```

**Response**

```json
{
  "prefs": {
    "dashboardLayout": {
      "v": 1,
      "blocks": [
        { "id": "cards", "visible": true, "size": "full" },
        { "id": "chart", "visible": true, "size": "full" },
        { "id": "finance", "visible": false, "size": "full" }
      ],
      "hiddenCards": ["fees"]
    },
    "favorites": {
      "gateway": ["7d1c2b3a-4e5f-4a60-8b71-9c0d1e2f3a45", "wallet:5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e"],
      "atri": [],
      "subscription": [],
      "product": ["blue-widget"]
    },
    "tableColumns.gateways": { "visible": ["name", "status", "volume"], "order": ["name", "status", "volume", "cap"], "version": 2 },
    "dateDisplay": "relative",
    "releaseAnnouncement:v5.4": { "action": "dismissed", "at": "2026-11-20T09:15:00.000Z" }
  }
}
```

| response field | type | description |
|---|---|---|
| `prefs` | object | The full stored object after the merge (nulls removed). |

**Errors**

- `400` `{"error":"Invalid","details":<zod flatten>}`: prefs missing or not an object, an empty or longer than 64-character key, or the object over 64 KB (`prefs must stay under 65536 bytes`).
- `401` `Missing bearer token`, `Invalid API key`, or an expired or invalid login token. `Unauthorized` when the caller resolves to no e-mail.
- `402` `A paid platform subscription is required` (code `subscription_required`).
- `403` `API key scope denied` (code `insufficient_scope`, `requiredScope` names the missing scope); `Banned` when the account owner or the login is banned.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `503` `Authentication scope is temporarily unavailable`, or the database is momentarily unreachable (Retry-After: 1).

**Gotchas**

- SHALLOW merge: sending {"dashboardLayout": {"hidden": []}} replaces the WHOLE dashboardLayout object. Read, modify and write nested objects client-side.
- null deletes only at the top level; a nested null is stored as null.
- The 64 KB limit applies to the object you send, not to the stored total.
- Same row as GET /v1/me/prefs: keyed by the login e-mail; a key writes its account owner's preferences.
- Unlike GET, PUT needs a paid platform subscription for every caller, logins included.
- Recorded in the account's action log (action update, object type me).
- With an API key these are the preferences of the account owner's own login: a write changes the owner's dashboard (layout, favourites, columns).

### Inbound webhooks

Addresses that providers call (or send the buyer's browser to), never with an API key. Documented so you can configure them on the provider side; none takes a scope.

#### Payment providers and 3-D Secure

Stripe webhooks, the 3-D Secure callbacks of the issuer's page and the return from a hosted payment page.

##### `GET /v1/3ds/callback/:id/method`

**Inbound** no API key, no scope - **3DS Method completion callback (browser redirect, GET)**

Inbound browser callback of 3-D Secure, never called with an API key. Nothing to configure: Kontrol hands this address (with the session id) to the 3DS provider for each authentication. The issuer's ACS sends the cardholder's browser here when the device fingerprint (3DS Method) is done. Browser-facing endpoint the ACS notifies when the 3DS Method iframe (device fingerprinting) has completed - the threeDSMethodNotificationURL Kontrol hands to the provider. Records the posted fields on the session (callback stage 'method') and answers a tiny HTML page that postMessages {type:'coco3ds', sessionId, event:'method', status} to the parent / top / opener window so the checkout can continue to authentication. Registered for GET and POST (some ACS implementations redirect). Not meant to be called by your server.

**Who calls it and how it is authenticated**: None. The ACS / the provider's hosted page sends the cardholder's browser here; the unguessable session UUID in the path is the only capability. An unknown id is NOT rejected - the page is still returned with status 'unknown' (no enumeration signal).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id embedded in the callback URL Kontrol generated. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | no | POST only: application/x-www-form-urlencoded or JSON - typically threeDSMethodData (base64url). Every value is stored as a string on the session. |

**Response**

```json
<!doctype html><html><head><meta charset="utf-8"><title>3-D Secure</title>
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#111}</style></head>
<body><p id="m">Authentication step complete. You can return to the checkout.</p>
<script nonce="bm9uY2UtZXhhbXBsZS0wMQ==">(function(){var m={"type":"coco3ds","sessionId":"a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91","event":"method","status":"completed"};try{if(window.parent&&window.parent!==window){window.parent.postMessage(m,'*');}
if(window.top&&window.top!==window){window.top.postMessage(m,'*');}if(window.opener){window.opener.postMessage(m,'*');}}catch(e){}})();</script></body></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | 200 text/html for any well-formed session id. The embedded message: {type:'coco3ds', sessionId, event:'method', status:'completed'\|'unknown'}. |
| `message.status` | enum: completed\|unknown | 'completed' when the session exists and the callback was recorded; 'unknown' for an unknown session id. |
| `Content-Security-Policy` | header | default-src 'none'; script-src 'nonce-<random>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'. A fresh 16-byte nonce per response matches the page's only script tag. No frame-ancestors: the ACS and the checkout both frame this page. |

**Errors**

- `400` {"error":"A value has an invalid format."} (JSON, not the HTML page) when the path id is not a UUID.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).

**Gotchas**

- Fires inside a hidden iframe on the checkout page: the visible text is a fallback, the postMessage is the signal.
- Stage 'method' never decides the authentication by itself - the checkout still calls POST /v1/3ds/sessions/:id/complete after the challenge (or the frictionless result).
- Idempotent: a second notification for the same session overwrites the stored fields and answers the same page.
- The page loads nothing external and carries its own nonce-based Content-Security-Policy. In the embedded JSON every '<' is written as \u003c, so a hostile status or id cannot close the script block; the message the parent receives is unchanged.
- A path id that is not a UUID is answered 400 JSON {"error":"A value has an invalid format."} by the global handler, not the HTML page. A well-formed unknown id still gets the 200 page with status unknown.

##### `POST /v1/3ds/callback/:id/method`

**Inbound** no API key, no scope - **3DS Method completion callback (form post, POST)**

Inbound browser callback of 3-D Secure, never called with an API key. Nothing to configure: Kontrol hands this address (with the session id) to the 3DS provider for each authentication. The issuer's ACS sends the cardholder's browser here when the device fingerprint (3DS Method) is done. Browser-facing endpoint the ACS notifies when the 3DS Method iframe (device fingerprinting) has completed - the threeDSMethodNotificationURL Kontrol hands to the provider. Records the posted fields on the session (callback stage 'method') and answers a tiny HTML page that postMessages {type:'coco3ds', sessionId, event:'method', status} to the parent / top / opener window so the checkout can continue to authentication. Registered for GET and POST (some ACS implementations redirect). Not meant to be called by your server.

**Who calls it and how it is authenticated**: None. The ACS / the provider's hosted page sends the cardholder's browser here; the unguessable session UUID in the path is the only capability. An unknown id is NOT rejected - the page is still returned with status 'unknown' (no enumeration signal).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id embedded in the callback URL Kontrol generated. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | no | POST only: application/x-www-form-urlencoded or JSON - typically threeDSMethodData (base64url). Every value is stored as a string on the session. |

**Request body**

```json
threeDSMethodData=eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6ImE3ZTJmMWMwLTViM2QtNGU4YS05YzIxLTdkNmYwYjRlMmE5MSJ9
```

**Response**

```json
<!doctype html><html><head><meta charset="utf-8"><title>3-D Secure</title>
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#111}</style></head>
<body><p id="m">Authentication step complete. You can return to the checkout.</p>
<script nonce="bm9uY2UtZXhhbXBsZS0wMQ==">(function(){var m={"type":"coco3ds","sessionId":"a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91","event":"method","status":"completed"};try{if(window.parent&&window.parent!==window){window.parent.postMessage(m,'*');}
if(window.top&&window.top!==window){window.top.postMessage(m,'*');}if(window.opener){window.opener.postMessage(m,'*');}}catch(e){}})();</script></body></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | 200 text/html for any well-formed session id. The embedded message: {type:'coco3ds', sessionId, event:'method', status:'completed'\|'unknown'}. |
| `message.status` | enum: completed\|unknown | 'completed' when the session exists and the callback was recorded; 'unknown' for an unknown session id. |
| `Content-Security-Policy` | header | default-src 'none'; script-src 'nonce-<random>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'. A fresh 16-byte nonce per response matches the page's only script tag. No frame-ancestors: the ACS and the checkout both frame this page. |

**Errors**

- `400` {"error":"A value has an invalid format."} (JSON, not the HTML page) when the path id is not a UUID.
- `415` Unsupported content type (only JSON and application/x-www-form-urlencoded are parsed).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).

**Gotchas**

- Fires inside a hidden iframe on the checkout page: the visible text is a fallback, the postMessage is the signal.
- Stage 'method' never decides the authentication by itself - the checkout still calls POST /v1/3ds/sessions/:id/complete after the challenge (or the frictionless result).
- Idempotent: a second notification for the same session overwrites the stored fields and answers the same page.
- The page loads nothing external and carries its own nonce-based Content-Security-Policy. In the embedded JSON every '<' is written as \u003c, so a hostile status or id cannot close the script block; the message the parent receives is unchanged.
- A path id that is not a UUID is answered 400 JSON {"error":"A value has an invalid format."} by the global handler, not the HTML page. A well-formed unknown id still gets the 200 page with status unknown.

##### `POST /v1/3ds/callback/:id/notify`

**Inbound** no API key, no scope - **ACS challenge result callback (CRes)**

Inbound browser callback of 3-D Secure, never called with an API key. Nothing to configure: Kontrol hands this address (with the session id) to the 3DS provider for each challenge. The issuer's ACS posts the challenge result (CRes) here from the cardholder's browser. Browser-facing endpoint the issuer's ACS posts the challenge result (CRes) to after a 3DS challenge - it is the notificationURL Kontrol hands to the provider (3dsecure.io flow). Records the posted form fields on the session (callback_payload + challengeReturned:'true') and answers a tiny HTML page that postMessages {type:'coco3ds', sessionId, event:'challenge', status} to the parent / top / opener window so the checkout knows to call POST /v1/3ds/sessions/:id/complete. Not meant to be called by your server.

**Who calls it and how it is authenticated**: None. The ACS / hosted page posts here from the cardholder's browser; the unguessable session UUID in the path is the only capability. An unknown id is NOT rejected - the page is still returned with status 'unknown' (no enumeration signal).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id embedded in the callback URL Kontrol generated. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | no | application/x-www-form-urlencoded (parsed on this plugin) or JSON: the ACS fields, typically cres (base64url CRes) and threeDSSessionData. Every value is stored as a string on the session. |

**Request body**

```json
cres=eyJtZXNzYWdlVHlwZSI6IkNSZXMiLCJ0cmFuc1N0YXR1cyI6IlkiLCJ0aHJlZURTU2VydmVyVHJhbnNJRCI6Ii4uLiJ9&threeDSSessionData=YTdlMmYxYzAtNWIzZC00ZThhLTljMjEtN2Q2ZjBiNGUyYTkx
```

**Response**

```json
<!doctype html><html><head><meta charset="utf-8"><title>3-D Secure</title>
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#111}</style></head>
<body><p id="m">Authentication  complete. You can return to the checkout.</p>
<script nonce="bm9uY2UtZXhhbXBsZS0wMQ==">(function(){var m={"type":"coco3ds","sessionId":"a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91","event":"challenge","status":"returned"};try{if(window.parent&&window.parent!==window){window.parent.postMessage(m,'*');}
if(window.top&&window.top!==window){window.top.postMessage(m,'*');}if(window.opener){window.opener.postMessage(m,'*');}}catch(e){}})();</script></body></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | 200 text/html for any well-formed session id. The embedded message: {type:'coco3ds', sessionId, event:'challenge', status:'returned'\|'unknown'}. |
| `message.status` | enum: returned\|unknown | 'returned' when the session exists and the payload was recorded; 'unknown' when the id matches no session (nothing stored). |
| `Content-Security-Policy` | header | default-src 'none'; script-src 'nonce-<random>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'. A fresh 16-byte nonce per response matches the page's only script tag. No frame-ancestors: the ACS and the checkout both frame this page. |

**Errors**

- `400` {"error":"A value has an invalid format."} (JSON, not the HTML page) when the path id is not a UUID.
- `415` Unsupported content type (only JSON and application/x-www-form-urlencoded are parsed).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).
- `500` `Internal Server Error` on an unexpected server error while recording the callback (an unreachable database answers 503).

**Gotchas**

- Never 404s: a well-formed unknown session id still gets the 200 HTML page, with status 'unknown' in the message and nothing stored.
- This does NOT advance the session: it only stores the payload. The checkout must follow with POST /v1/3ds/sessions/:id/complete {stage:"challenge"} (or GET the session), which resumes the provider with the stored cres.
- The postMessage targets '*' - the checkout should verify the message shape ({type:'coco3ds'}) and the sessionId it expects.
- Two sibling callbacks exist for the other browser steps, registered with app.route for GET and POST: /v1/3ds/callback/:id/method (3DS Method notification, event "method", flag methodCompleted:"true") and /v1/3ds/callback/:id/return (hosted-page return for Evervault / VGS, event "return", merges the query string, status from ?status= when present). They behave like this route and have their own entries.
- The callback URLs are built from API_PUBLIC_URL at session start; they must be reachable from the cardholder browser / ACS (public HTTPS).
- No rate-limit override on the callbacks (global default applies); no CSRF token - the session id is the capability and unknown ids leak nothing.
- The page loads nothing external and carries its own nonce-based Content-Security-Policy. In the embedded JSON every '<' is written as \u003c, so a hostile status or id cannot close the script block; the message the parent receives is unchanged.
- A path id that is not a UUID is answered 400 JSON {"error":"A value has an invalid format."} by the global handler, not the HTML page. A well-formed unknown id still gets the 200 page with status unknown.

##### `GET /v1/3ds/callback/:id/return`

**Inbound** no API key, no scope - **Hosted challenge return callback (browser redirect, GET)**

Inbound browser callback of 3-D Secure, never called with an API key. Nothing to configure: Kontrol hands this address (with the session id) to the 3DS provider's hosted challenge page. The cardholder's browser comes back here when the challenge is over. Browser-facing endpoint a provider's hosted challenge page (Evervault, VGS redirect_url) sends the cardholder back to once the challenge is over. Records the form fields and the query string on the session (callback stage 'challenge') and answers a tiny HTML page that postMessages {type:'coco3ds', sessionId, event:'return', status} to the parent / top / opener window so the checkout calls POST /v1/3ds/sessions/:id/complete. Registered for GET (redirect) and POST (form post).

**Who calls it and how it is authenticated**: None. The ACS / the provider's hosted page sends the cardholder's browser here; the unguessable session UUID in the path is the only capability. An unknown id is NOT rejected - the page is still returned with status 'unknown' (no enumeration signal).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id embedded in the callback URL Kontrol generated. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `status` | string | no | Provider-supplied outcome hint (e.g. success \| failure \| error); echoed as the message status when present, otherwise 'returned'. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | no | POST only: the hosted page's form fields (provider specific). Merged with the query string and stored as strings on the session. |

**Response**

```json
<!doctype html><html><head><meta charset="utf-8"><title>3-D Secure</title>
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#111}</style></head>
<body><p id="m">Authentication  complete. You can return to the checkout.</p>
<script nonce="bm9uY2UtZXhhbXBsZS0wMQ==">(function(){var m={"type":"coco3ds","sessionId":"a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91","event":"return","status":"success"};try{if(window.parent&&window.parent!==window){window.parent.postMessage(m,'*');}
if(window.top&&window.top!==window){window.top.postMessage(m,'*');}if(window.opener){window.opener.postMessage(m,'*');}}catch(e){}})();</script></body></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | 200 text/html for any well-formed session id. The embedded message: {type:'coco3ds', sessionId, event:'return', status:<?status>\|'returned'\|'unknown'}. |
| `Content-Security-Policy` | header | default-src 'none'; script-src 'nonce-<random>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'. A fresh 16-byte nonce per response matches the page's only script tag. No frame-ancestors: the ACS and the checkout both frame this page. |

**Errors**

- `400` {"error":"A value has an invalid format."} (JSON, not the HTML page) when the path id is not a UUID.
- `429` Per-IP rate limit exceeded (default 300 requests per minute).

**Gotchas**

- The status is a hint from the provider's redirect, never the authentication verdict: the verdict comes from POST /v1/3ds/sessions/:id/complete, which asks the provider.
- An unknown session id still answers 200 with status unknown - treat it as a page for humans, not an API response.
- The page loads nothing external and carries its own nonce-based Content-Security-Policy. In the embedded JSON every '<' is written as \u003c, so a hostile status or id cannot close the script block; the message the parent receives is unchanged.
- A path id that is not a UUID is answered 400 JSON {"error":"A value has an invalid format."} by the global handler, not the HTML page. A well-formed unknown id still gets the 200 page with status unknown.

##### `POST /v1/3ds/callback/:id/return`

**Inbound** no API key, no scope - **Hosted challenge return callback (form post, POST)**

Inbound browser callback of 3-D Secure, never called with an API key. Nothing to configure: Kontrol hands this address (with the session id) to the 3DS provider's hosted challenge page. The cardholder's browser comes back here when the challenge is over. Browser-facing endpoint a provider's hosted challenge page (Evervault, VGS redirect_url) sends the cardholder back to once the challenge is over. Records the form fields and the query string on the session (callback stage 'challenge') and answers a tiny HTML page that postMessages {type:'coco3ds', sessionId, event:'return', status} to the parent / top / opener window so the checkout calls POST /v1/3ds/sessions/:id/complete. Registered for GET (redirect) and POST (form post).

**Who calls it and how it is authenticated**: None. The ACS / the provider's hosted page sends the cardholder's browser here; the unguessable session UUID in the path is the only capability. An unknown id is NOT rejected - the page is still returned with status 'unknown' (no enumeration signal).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `id` | uuid | **yes** | Session id embedded in the callback URL Kontrol generated. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `status` | string | no | Provider-supplied outcome hint (e.g. success \| failure \| error); echoed as the message status when present, otherwise 'returned'. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | no | POST only: the hosted page's form fields (provider specific). Merged with the query string and stored as strings on the session. |

**Response**

```json
<!doctype html><html><head><meta charset="utf-8"><title>3-D Secure</title>
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#111}</style></head>
<body><p id="m">Authentication  complete. You can return to the checkout.</p>
<script nonce="bm9uY2UtZXhhbXBsZS0wMQ==">(function(){var m={"type":"coco3ds","sessionId":"a7e2f1c0-5b3d-4e8a-9c21-7d6f0b4e2a91","event":"return","status":"success"};try{if(window.parent&&window.parent!==window){window.parent.postMessage(m,'*');}
if(window.top&&window.top!==window){window.top.postMessage(m,'*');}if(window.opener){window.opener.postMessage(m,'*');}}catch(e){}})();</script></body></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | 200 text/html for any well-formed session id. The embedded message: {type:'coco3ds', sessionId, event:'return', status:<?status>\|'returned'\|'unknown'}. |
| `Content-Security-Policy` | header | default-src 'none'; script-src 'nonce-<random>'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'. A fresh 16-byte nonce per response matches the page's only script tag. No frame-ancestors: the ACS and the checkout both frame this page. |

**Errors**

- `400` {"error":"A value has an invalid format."} (JSON, not the HTML page) when the path id is not a UUID.
- `415` Unsupported content type (only JSON and application/x-www-form-urlencoded are parsed).
- `429` Per-IP rate limit exceeded (default 300 requests per minute).

**Gotchas**

- The status is a hint from the provider's redirect, never the authentication verdict: the verdict comes from POST /v1/3ds/sessions/:id/complete, which asks the provider.
- An unknown session id still answers 200 with status unknown - treat it as a page for humans, not an API response.
- The page loads nothing external and carries its own nonce-based Content-Security-Policy. In the embedded JSON every '<' is written as \u003c, so a hostile status or id cannot close the script block; the message the parent receives is unchanged.
- A path id that is not a UUID is answered 400 JSON {"error":"A value has an invalid format."} by the global handler, not the HTML page. A well-formed unknown id still gets the 200 page with status unknown.

##### `GET /v1/payments/return`

**Inbound** no API key, no scope - **Resume a checkout after a provider return (browser redirect, GET)**

Payment return address, opened by the buyer's browser when a payment provider (hosted page, wallet sheet, redirect) sends it back, never called with an API key. Nothing to configure: Kontrol builds this address with a signed token for each payment that needs a return URL. Read-only browser navigation relay. Verifies a signed reference and its persisted owner/provider binding, record age and destination. Redirects to the saved checkout/flow, or a neutral CRM page when no allowed destination exists. Does not submit or approve a payment.

**Who calls it and how it is authenticated**: No credential: the signed token is the only input with authority. The API mints these tokens itself when it builds a provider return URL; this endpoint cannot mint one, choose a destination or grant checkout access.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string | **yes** | The unchanged signed reference from the provider return URL: v1.<base64url payload>.<43-character MAC>, at most 1024 characters. Its payload is a reference of kind flow, wallet (phase checkout or sheet), transaction, legacy or neutral. Never construct or edit it. |

**Response** `303`

```json
HTTP/1.1 303 See Other
Location: https://shop.example.com/checkout/<saved-checkout-token>
Cache-Control: no-store
Referrer-Policy: no-referrer
```

| response field | type | description |
|---|---|---|
| `Location` | HTTP header | Validated saved checkout/flow destination, or the canonical /v1/payments/return/complete neutral page. |

**Errors**

- `400` {"error":"Invalid or expired payment return"}: the token is missing, not a string, longer than 1024 characters, badly formed or its MAC does not verify.
- `403` {"error":"Forbidden"} from the global crawler guard when the User-Agent looks like a bot, crawler or scanner (runs before the handler).
- `429` Per-IP rate limit (the global default per minute per IP, in memory per API instance).
- `503` {"error":"Payment return temporarily unavailable"} with Retry-After: 1 when the destination lookup fails (database unavailable). Reloading only retries navigation, never a payment.

**Gotchas**

- A valid token always answers 303. The Location is the saved destination when every binding still holds, otherwise the neutral page /v1/payments/return/complete.
- Flow references go back to https://<serving domain>/flow/<checkoutId> of the original session; transaction references go to the saved checkout return URL (or the session path /flow/<id> or /c/<slug>); wallet references go to the hosted sheet https://<registered wallet domain>/s/<session id> (phase sheet, or when no return URL was saved) or to the saved checkout URL with ?session=<wallet session id> appended (phase checkout).
- Every binding is re-checked against the database at each visit: the MAC binds the account, owner or wallet provider; the store must still be active, verified, not archived and owned by the same account; the destination must be on that store or session host with the same cart. A changed owner or provider, an archived store or a mismatched destination falls back to the neutral page.
- References expire 24 hours after the source record (session, wallet session or transaction) was created. Legacy references always land on the neutral page.
- Read-only: a visit never settles, retries or changes a payment, and repeating it is harmless. Provider status, success or next query fields and any POST body are ignored.
- Responses carry Cache-Control no-store and Referrer-Policy no-referrer.

##### `POST /v1/payments/return`

**Inbound** no API key, no scope - **Resume a checkout after a provider return (form post, POST)**

Payment return address, posted by the buyer's browser when a payment provider sends it back with a form post, never called with an API key. Nothing to configure: Kontrol builds this address with a signed token for each payment that needs a return URL. Read-only browser navigation relay. Verifies a signed reference and its persisted owner/provider binding, record age and destination. Redirects to the saved checkout/flow, or a neutral CRM page when no allowed destination exists. Does not submit or approve a payment.

**Who calls it and how it is authenticated**: No credential: the signed token is the only input with authority. The API mints these tokens itself when it builds a provider return URL; this endpoint cannot mint one, choose a destination or grant checkout access.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string | **yes** | The unchanged signed reference from the provider return URL: v1.<base64url payload>.<43-character MAC>, at most 1024 characters. Its payload is a reference of kind flow, wallet (phase checkout or sheet), transaction, legacy or neutral. Never construct or edit it. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | any | no | Some providers POST a form back. A form (application/x-www-form-urlencoded) or JSON body is accepted and discarded: it has no financial or redirect authority. Limit 16 KB. |

**Response** `303`

```json
HTTP/1.1 303 See Other
Location: https://shop.example.com/checkout/<saved-checkout-token>
Cache-Control: no-store
Referrer-Policy: no-referrer
```

| response field | type | description |
|---|---|---|
| `Location` | HTTP header | Validated saved checkout/flow destination, or the canonical /v1/payments/return/complete neutral page. |

**Errors**

- `400` {"error":"Invalid or expired payment return"}: the token is missing, not a string, longer than 1024 characters, badly formed or its MAC does not verify.
- `403` {"error":"Forbidden"} from the global crawler guard when the User-Agent looks like a bot, crawler or scanner (runs before the handler).
- `413` Body larger than 16 KB.
- `415` Unsupported Content-Type (only form-urlencoded, JSON and text/plain bodies are parsed).
- `429` Per-IP rate limit (the global default per minute per IP, in memory per API instance).
- `503` {"error":"Payment return temporarily unavailable"} with Retry-After: 1 when the destination lookup fails (database unavailable). Reloading only retries navigation, never a payment.

**Gotchas**

- A valid token always answers 303. The Location is the saved destination when every binding still holds, otherwise the neutral page /v1/payments/return/complete.
- Flow references go back to https://<serving domain>/flow/<checkoutId> of the original session; transaction references go to the saved checkout return URL (or the session path /flow/<id> or /c/<slug>); wallet references go to the hosted sheet https://<registered wallet domain>/s/<session id> (phase sheet, or when no return URL was saved) or to the saved checkout URL with ?session=<wallet session id> appended (phase checkout).
- Every binding is re-checked against the database at each visit: the MAC binds the account, owner or wallet provider; the store must still be active, verified, not archived and owned by the same account; the destination must be on that store or session host with the same cart. A changed owner or provider, an archived store or a mismatched destination falls back to the neutral page.
- References expire 24 hours after the source record (session, wallet session or transaction) was created. Legacy references always land on the neutral page.
- Read-only: a visit never settles, retries or changes a payment, and repeating it is harmless. Provider status, success or next query fields and any POST body are ignored.
- Responses carry Cache-Control no-store and Referrer-Policy no-referrer.

##### `GET /v1/payments/return/complete`

**Inbound** no API key, no scope - **Display a neutral payment return page**

Neutral page the buyer's browser lands on after a payment return with no checkout to go back to; nothing to configure and never called with an API key. Neutral browser page that GET or POST /v1/payments/return redirects to when a return reference is valid but no allowed destination exists (headless, expired, unbound or neutral reference). It explicitly does not confirm a payment.

**Who calls it and how it is authenticated**: No credential: a public browser page. It discloses no transaction, payment state or customer data.

*No parameters.*

**Response** `200`

```json
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Payment return</title><h1>You can return to your checkout</h1><p>This page does not confirm a payment. Your checkout will show its current status.</p></html>
```

| response field | type | description |
|---|---|---|
| `(root)` | text/html | Neutral page without payment actions or a success assertion. |

**Errors**

- `403` {"error":"Forbidden"} from the global crawler guard when the User-Agent looks like a bot, crawler or scanner (runs before the handler).
- `429` Per-IP rate limit (the global default per minute per IP, in memory per API instance).

**Gotchas**

- Payment status is only available through the checkout and status APIs, never from this page.
- Headers: Content-Type text/html, Cache-Control no-store, Referrer-Policy no-referrer, and a Content-Security-Policy that forbids every resource, framing, base URI and form action.

##### `POST /v1/stripe/webhooks/:accountId`

**Inbound** no API key, no scope - **Receive a Stripe webhook (provider)**

Inbound webhook called by Stripe, never with an API key. To configure: in the Stripe dashboard (Developers > Webhooks) add the endpoint https://api.kontrolcheckout.com/v1/stripe/webhooks/<gateway id>, where <gateway id> is the id of the Stripe gateway in Kontrol (GET /v1/accounts; the gateway form shows this path as Webhook path), then save that endpoint's signing secret (whsec_...) as the gateway's Webhook signing secret (body password of POST /v1/accounts or PATCH /v1/accounts/:id). It verifies the Stripe-Signature header against that secret and only wakes the settlement check of the payment named in data.object.metadata.kontrol_transaction; Kontrol then reads the payment from Stripe itself. It answers {"received": true}, also for an unknown transaction id; an event is a wake-up, never a proof of payment.

**Who calls it and how it is authenticated**: Inbound Stripe webhook: Stripe-Signature HMAC (t=..., v1=...) over the raw body with the webhook signing secret stored on the Stripe gateway; timestamp tolerance 300 seconds. No Kontrol credential.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `accountId` | uuid | **yes** | The Stripe gateway (MID) id configured in the webhook URL. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `data.object.metadata.kontrol_transaction` | uuid | no | Kontrol transaction id carried in the Stripe object metadata; its unsettled payment check is moved to now. Any other content is ignored. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `Stripe-Signature` | string | **yes** | Stripe signature header. |

**Request body**

```json
{
  "id": "evt_example",
  "type": "payment_intent.succeeded",
  "data": {
    "object": {
      "metadata": {
        "kontrol_transaction": "11111111-1111-4111-8111-111111111111"
      }
    }
  }
}
```

**Response**

```json
{
  "received": true
}
```

**Errors**

- `400` Invalid webhook (accountId not a uuid); Invalid signature (no Stripe gateway with that id, no secret, stale or wrong signature); or Invalid event (body not JSON).
- `413` Body larger than 256 KB.

**Gotchas**

- Sign the exact raw bytes. Unknown transaction ids are acknowledged without change. An event is a wake-up, never proof of payment.

#### Dispute alerts

Chargeback and dispute alerts from the alert providers.

##### `POST /v1/alerts/:provider/:account`

**Inbound** no API key, no scope - **Receive a chargeback / dispute alert (webhook)**

Inbound webhook called by a dispute-alert provider (XCaliber XProtect: provider xcaliber; RCVR: provider rcvr), never with an API key. To configure: give the provider the address https://api.kontrolcheckout.com/v1/alerts/<provider>/<account e-mail, URL-encoded>, exactly as GET /v1/integrations returns it in catalog[].webhookUrl, and the integration's webhookSecret (saved with PUT /v1/integrations/:key, secrets.webhookSecret), which the provider sends as X-Webhook-Secret, a Bearer token or ?token=. It checks that secret, records the alert, matches it to one of the account's approved charges and, when the integration's autoRefund is on, refunds that charge in full. Inbound webhook for the Alerts integrations (XCaliber XProtect, RCVR): each account has its own URL per provider, shown as catalog[].webhookUrl in GET /v1/integrations. The JSON body is read leniently (flattened up to 3 levels; well-known keys picked), the alert is ALWAYS recorded in integration_alerts with the raw payload, then matched to one of the account's approved charges (gateway transaction id -> order id -> last4 + amount). When a match exists, is not yet refunded, and the integration's `autoRefund` toggle is on, the transaction is refunded in full through the shared refund engine (which also blacklists the customer's email + card and ends the order's subscriptions). Answers 200 with what happened.

**Who calls it and how it is authenticated**: Shared-secret webhook: the value the account saved as the `webhookSecret` secret of its xcaliber / rcvr integration must arrive as header X-Webhook-Secret, OR Authorization: Bearer <secret>, OR query ?token=<secret> (read in that order; constant-time compare). Failure precedence: unknown :provider -> 404; integration disabled or never saved for :account -> 404 'Integration not enabled for this account'; integration on but no webhookSecret saved -> 403; wrong secret -> 401 'Invalid webhook secret'. No IP allow-list, no body HMAC. Rate limit RATE_LIMIT_DEFAULT (300/min per IP).

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `provider` | enum: xcaliber\|rcvr | **yes** | The alert provider. Anything else answers 404 {"error":"Unknown alert provider"}. |
| `account` | string | **yes** | The account e-mail, URL-encoded (owner%40example.com); lower-cased. The provider integration must be enabled for it. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string | no | Third way to pass the secret (lands in access logs). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `alertType` | string; default `unknown` | no | Alert type; aliases alert_type, type, source, network. Lower-cased, 32 characters kept. |
| `alertId` | string | no | Provider alert id; aliases alert_id, id, caseId, case_id, disputeId. |
| `amount` | string\|number | no | Amount in major units; aliases transactionAmount, transaction_amount, disputeAmount, dispute_amount. Every character but digits and . is stripped; a missing or zero amount disables the last4 + amount match. |
| `currency` | string | no | Aliases currencyCode, currency_code; upper-cased, 3 characters kept. |
| `last4` | string | no | Card last 4; aliases cardLast4, card_last4, lastFour, last_four. |
| `arn` | string | no | Acquirer reference number; aliases acquirerReferenceNumber, acquirer_reference_number. Stored, not used to match. |
| `transactionId` | string | no | Gateway transaction id (first match key); aliases transaction_id, gatewayTransactionId, gateway_transaction_id, authId, transactionid. |
| `orderId` | string | no | Order id (second match key); aliases order_id, merchantOrderId, merchant_order_id, invoice. |
| `descriptor` | string | no | Aliases merchantDescriptor, merchant_descriptor, billingDescriptor. Stored, not used to match. |
| `(other keys)` | any | no | Any other field is kept in the stored payload. Nested objects are flattened up to 3 levels (data.transaction.id is also read as id). |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `X-Webhook-Secret` | string | no | The account's saved webhookSecret. One of X-Webhook-Secret, Authorization: Bearer <secret> or ?token= is required (read in that order). |

**Request body**

```json
{
  "alertType": "ethoca",
  "alertId": "ALR-88213",
  "transactionId": "9876543210",
  "orderId": "ord_01J8QZ6M3K5W9X2R7T4V1B0N8C",
  "amount": "49.99",
  "currency": "USD",
  "last4": "1111",
  "arn": "74123456789012345678901",
  "descriptor": "ACME*STORE 8005551234",
  "reasonCode": "10.4"
}
```

**Response**

```json
{
  "received": true,
  "alertId": "5e1c9b2a-0d4f-4a7e-b8c3-2f6a1d9e7b50",
  "matched": true,
  "transactionId": "3f2a91c4-7b0e-4d1a-9f55-8c2d6b1e40aa",
  "action": "refunded"
}
```

| response field | type | description |
|---|---|---|
| `received` | boolean | Always true on 200 - the alert was stored. |
| `alertId` | uuid | integration_alerts.id (visible in GET /v1/integrations/alerts). |
| `matched` | boolean | A transaction of the account was identified. |
| `transactionId` | uuid\|null | The matched transaction. |
| `action` | enum: recorded\|refunded\|refund_failed\|already_refunded | recorded = stored only (no match, or autoRefund off); refunded = full refund executed; refund_failed = refund attempted and failed (detail stored on the alert); already_refunded = the matched transaction was refunded before. |

**Errors**

- `400` Empty or malformed JSON body (Fastify body-parsing error, {"error":"<parser message>"}).
- `401` {"error":"Invalid webhook secret"} - secret present but wrong (or missing entirely: `provided` null also fails the compare -> 401).
- `403` {"error":"No webhook secret configured for this integration"} - the account enabled the provider but never saved webhookSecret.
- `404` {"error":"Unknown alert provider"} - :provider not xcaliber / rcvr.
- `404` {"error":"Integration not enabled for this account"} - no row or switched off for :account (also for a non-existent account: no enumeration difference).
- `415` Unsupported Media Type - body sent as form-urlencoded / text instead of JSON.
- `429` Per-IP rate limit (RATE_LIMIT_DEFAULT, default 300 requests per minute).
- `500` Internal Server Error with a requestId (the alert may or may not have been stored).

**Gotchas**

- Always 200 once authenticated, even when nothing matched (matched:false, action "recorded", action_detail "no matching transaction") - do not retry on a 200.
- Matching order and rules: (1) gateway transaction id = transactions.order_id_supplier of an APPROVED charge; (2) order id = transactions.order_id; (3) last4 + exact amount_cents within 180 days, only when exactly ONE candidate exists (ambiguous -> unmatched). ARN and descriptor are stored but never used for matching.
- Tenancy: the candidate charges are the ACCOUNT's under the full tenant rule (its keys, wallet providers, its MIDs, its members' imports) - an acquirer alert naming one of your MIDs matches even if another account's key sent the order.
- Auto-refund = FULL remaining amount via the refund engine, idempotency key 'alert:<provider>:<alertId>', requestedBy '<provider> alert'. Side effects of that engine: the customer's email + card are auto-blacklisted for the account and the order's subscriptions are ended ('refund'). The transaction is NOT flagged as chargeback/dispute by this route - do that manually (POST /v1/refund/chargeback with the refundId, or POST /v1/refunds/:id/dispute) if needed.
- Duplicates are not deduplicated: the same alert posted twice creates two alert rows; the second refund attempt is refused by the engine (already refunded) -> action already_refunded.
- amount parsing strips every non [0-9.] character ("$49.99" -> 49.99 -> 4999 cents); a missing / zero amount disables the last4+amount fallback.
- The secret compare is constant-time but there is no signature over the body and no IP allow-list - anyone with the URL and the secret can inject alerts (and trigger refunds when autoRefund is on). Rotate the secret from the Integrations page if it leaks.
- Only JSON bodies are parsed on this route (the form parser of the 3DS plugin is encapsulated and does not apply here).
- Payload PII is stored verbatim in integration_alerts.payload.

#### Messaging delivery reports

Delivery reports of the e-mail and SMS providers.

##### `POST /v1/recovery/email-callback/:providerId`

**Inbound** no API key, no scope - **E-mail delivery receipt (Resend webhook)**

Inbound webhook called by Resend (the e-mail sender of cart recovery), never with an API key. To configure: in Resend, add the webhook https://api.kontrolcheckout.com/v1/recovery/email-callback/<sender id>, where <sender id> is the id of the e-mail provider in Kontrol (GET /v1/messaging/email-providers; its form shows the full address), and save Resend's signing secret on that provider (its Receipts tab). It verifies the Svix signature with that secret and records the delivery status of the recovery e-mail. Delivery status of a recovery e-mail, posted by Resend to the webhook URL configured on the sender. Writes recovery_sends.delivery_status and, for a delivery, delivered_at. Not for merchants to call: it is authenticated by the sender's Svix signing secret, not by an API key.

**Who calls it and how it is authenticated**: Provider webhook, not for accounts: authenticated by the sender's Svix signing secret.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `providerId` | uuid | **yes** | The e-mail sender this endpoint belongs to; selects its signing secret. Shown on the sender's Receipts tab. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `(body)` | object | **yes** | The Resend event (type, created_at, data.email_id, data.to, data.subject, ...), verified on its raw bytes; up to 256 KiB. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `svix-id` | string | **yes** | Svix message id. |
| `svix-timestamp` | string | **yes** | Unix seconds; refused outside five minutes. |
| `svix-signature` | string | **yes** | One or more space-separated v1,<base64> signatures over id.timestamp.rawBody. |

**Request body**

```json
{"type":"email.delivered","created_at":"2026-11-04T12:14:29.000Z","data":{"email_id":"01a1a67b-6ca0-77bd-979d-5cf26db82e0c","to":["buyer@example.com"],"subject":"Your basket","created_at":"2026-11-04T12:14:26.000Z"}}
```

**Response**

```json
{"ok":true,"updated":1,"matchedBy":"provider_message_id"}
```

**Errors**

- `400` {"ok":false,"error":"Invalid webhook"} (providerId not a uuid) or {"ok":false,"error":"Invalid event"} (body not JSON).
- `401` {"ok":false}: signature missing or wrong, unknown sender or no secret, or timestamp outside five minutes (the reason is only logged).
- `413` Body larger than 256 KiB.
- `429` 3000 requests per minute per IP.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.

**Gotchas**

- Signed with Svix: `svix-id`, `svix-timestamp` and `svix-signature` over `${id}.${timestamp}.${rawBody}`. Several space-separated signatures are accepted so a secret rotation drops no event.
- A timestamp outside five minutes is refused. A captured receipt must not stay replayable.
- `updated: 0` with HTTP 200 is the honest answer for an e-mail this platform did not send: the signature was valid, so the provider must not retry it.
- The join has three steps, reported in `matchedBy`: the provider event id, then the queue id the SMTP server answered with, then recipient + subject + a ten-minute window. A send made over SMTP has no API id, which is why the third exists.
- `email.opened` and `email.clicked` are engagement, not delivery, and change nothing. A status only ever moves forward, so a late `delivery_delayed` cannot undo a `delivered`.
- The sender must carry a webhook signing secret (its Receipts tab); without one every call is refused with 401.

##### `POST /v1/recovery/sms-callback`

**Inbound** no API key, no scope - **MessageWhiz delivery report**

Inbound callback called by the SMS provider (MessageWhiz) for the recovery SMS Kontrol sends, never with an API key. Nothing to configure: Kontrol attaches this address, with the platform callback secret as ?token=, to every SMS it sends. It checks the token and records the delivery status of the send (an opt-out adds the phone to the account's SMS suppression list). Delivery status of an SMS the tool sent, posted by MessageWhiz to the callback URL the tool attached to the send (`RECOVERY_PUBLIC_URL/v1/recovery/sms-callback?token=...`). Updates the send row matched by `message_id`. Not for merchants to call.

**Who calls it and how it is authenticated**: Provider callback, not for accounts: the token query parameter must equal the platform SMS callback secret (constant-time compare).

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string | **yes** | The shared callback secret. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `message_id` | string | **yes** | The provider message id returned at send time. |
| `status` | string | no | Provider delivery status (delivered, failed, ...). |
| `error_code` | string \| null | no | Provider error code; stored as `status:error_code`. |

**Request body**

```json
{
  "message_id": "mw_example_0001",
  "status": "delivered"
}
```

**Response**

```json
{
  "ok": true,
  "updated": 1,
  "suppressed": 0
}
```

| response field | type | description |
|---|---|---|
| `updated` | number | Rows updated (0 when the message id is unknown - still 200). |
| `suppressed` | number | Phone numbers added to the SMS suppression list because the report says the recipient opted out (STOP). |

**Errors**

- `400` {"ok":false}: body without message_id (or invalid field types).
- `401` {"ok":false}: wrong token.
- `429` 3000 requests per minute per IP.
- `500` {"error":"Internal Server Error","requestId":"<id>"}: unexpected failure.
- `503` {"ok":false,"error":"sms callback not configured"}.

**Gotchas**

- Other body fields are accepted and ignored (`passthrough`); if MessageWhiz names the fields differently, the extra fields are ignored.
- Rate limit 3 000 / minute per IP.
- A report whose status says the recipient opted out adds the phone to the account's SMS suppression list.

#### Store platforms

The Shopify connection callback.

##### `GET /v1/shopify/oauth/callback`

**Inbound** no API key, no scope - **Shopify OAuth callback (browser)**

Browser redirect from Shopify, not an API call. To configure: in the Shopify app of the store, list https://api.kontrolcheckout.com/v1/shopify/oauth/callback as an Allowed redirection URL (the exact string GET /v1/checkouts/:shopId/onboarding returns as callbackUrl), then start the connection with POST /v1/checkouts/:shopId/shopify-oauth/start. It verifies Shopify's hmac, Kontrol's own signed state and the shop host, exchanges the code for the store's Admin API token and stores it. Where Shopify sends the operator's browser after the app is approved: verifies, exchanges code for an Admin API token, stores it on the store and shows an HTML page linking back to the setup wizard. Start the flow with POST /v1/checkouts/:shopId/shopify-oauth/start.

**Who calls it and how it is authenticated**: Browser redirect from Shopify, not an API call: Shopify's hmac over the query (with the app secret held for the store), Kontrol's own signed state (10 minutes, names the store) and a matching shop host must all agree.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `code` | string | **yes** | Shopify's one-time authorisation code. |
| `shop` | string | **yes** | The <shop>.myshopify.com host that authorised; must equal the store admin URL. |
| `state` | string | **yes** | Signed state minted by the start call. |
| `hmac` | string | **yes** | Shopify's signature over every other query parameter (timestamp, host and so on are part of it). |
| `error` | string | no | Set by Shopify when the operator declined; error_description is shown. |
| `error_description` | string | no | Shopify explanation of error. |

**Response**

```json
<!doctype html> ... <h1>Store connected</h1><p>example-store.myshopify.com is connected. The access token is stored; you can close this tab and continue the setup.</p>
```

| response field | type | description |
|---|---|---|
| `(html)` | string | An HTML page: 200 Store connected, or 400 Connection failed with the reason. |

**Errors**

- `400` HTML page "Connection failed" with the reason, for EVERY failure: Shopify refused the connection: ...; Shopify did not return code, shop and state; expired or altered link; unexpected shop; store host mismatch; Checkout not found; no app credentials on file; signature mismatch; Shopify refused the token exchange (HTTP N); or Shopify returned no access token.

**Gotchas**

- Every failure is a 400 HTML page, including a token exchange refused by Shopify.
- Re-running the flow replaces the stored token.

#### Uptime monitoring

The uptime monitor's state changes.

##### `POST /v1/uptime/callback`

**Inbound** no API key, no scope - **UptimeRobot alert sink**

Inbound webhook called by the platform's uptime monitor (UptimeRobot), never with an API key. Nothing to configure for a merchant: one platform-wide address and secret serve every account, and the monitors derive from the account's store domains. It checks the shared secret, resolves the monitor to the account that owns the domain and alerts that account's own contacts. Where UptimeRobot reports that a monitored store domain changed state. One webhook serves every account: the monitor id is resolved to the account that owns the domain, the event is recorded (deduplicated) and the alert is sent to that account's own Telegram, e-mail and SMS contacts.

**Who calls it and how it is authenticated**: Not a merchant endpoint: the inbound UptimeRobot webhook. It is authenticated by the shared secret UPTIME_CALLBACK_SECRET sent as the X-Uptime-Token header or the token query parameter, compared in constant time. When the secret is not configured every request is refused.

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `token` | string | no | The shared webhook secret, when not sent as the X-Uptime-Token header. |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `monitorId` | string | **yes** | UptimeRobot monitor id (monitorID is also accepted). Trimmed. The only identity read from the body, and only as a key into the monitors table. |
| `alertType` | string | no | Vendor alert code: 1 = down, 2 = up, 3 = SSL or domain expiry. Read first. |
| `alertTypeName` | string | no | Vendor alert word, used when alertType is not 1/2/3: contains ssl or expir = ssl; starts with down or contains not reachable = down; starts with up or contains back = up; anything else = unknown. |
| `alertDetails` | string | no | Free text detail, trimmed and cut to 1000 characters. |
| `alertDateTime` | string | no | Unix seconds (or a date string) of the alert; part of the deduplication key with the monitor id and the alert type. |
| `alertDuration` | string | no | Seconds the monitor was in the previous state; ignored when not a non-negative number. |
| `monitorName / monitorUrl / other fields` | string | no | Not used for routing or identity; the whole body is stored with the event as its raw payload. |

**Header parameters**

| field | type | required | description |
|---|---|---|---|
| `X-Uptime-Token` | string | no | The shared webhook secret. Takes precedence over the token query parameter when present. |

**Request body**

```json
{
 "monitorId": "800000001",
 "monitorName": "Store - shop.example.com",
 "monitorUrl": "https://shop.example.com/",
 "alertType": "1",
 "alertTypeName": "Down",
 "alertDetails": "Connection Timeout",
 "alertDateTime": "1793000000",
 "alertDuration": "0"
}
```

**Response**

```json
{
 "ok": true,
 "recorded": true,
 "notified": 2,
 "attempted": 3
}
```

**Errors**

- `400` {"ok":false,"error":"monitorId_required"}: no monitorId / monitorID in the body.
- `401` {"ok":false,"error":"unauthorized"}: missing or wrong secret, or no secret configured.
- `403` {"error":"Forbidden"} from the global crawler guard when the User-Agent looks like a bot, crawler or scanner (runs before the handler).
- `429` Per-IP rate limit (the global default per minute per IP, in memory per API instance).
- `500` Internal Server Error with a requestId (unexpected server or database failure).

**Gotchas**

- The body is not an identity: owner, host and destinations all come from the stored monitor row. A body naming another account's host changes nothing.
- Unknown monitor: 200 {"ok":true,"skipped":"unknown_monitor"} so the vendor stops retrying.
- Retry of the same alert (same monitor, type and alertDateTime): 200 {"ok":true,"skipped":"duplicate"}, nobody is notified twice.
- Unrecognised alert type: recorded, monitor state unchanged, 200 {"ok":true,"recorded":true,"notified":0}.
- down and ssl set the monitor state to down, up sets it to up, before the notifications are sent.

### Outbound webhooks and services

What Kontrol sends: the checkout webhooks you configure, and the external services the platform calls.

#### Checkout webhooks

Configure the signed webhooks a checkout sends (order, payment, subscription events), read deliveries, resend, rotate secrets and send test events.

##### `GET /v1/checkouts/:checkoutId/webhooks`

**Scope** `checkouts.read` - **List checkout webhooks**

Lists the webhook endpoints of a checkout together with the account-wide ones (or, with linkId, the endpoints of one saved link), oldest first, with the list of event types.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "rows": [
    {
      "id": "6f1d2c3b-4a5e-4f60-8b71-9c0d1e2f3a45",
      "checkout_id": "2b8f6c1e-55aa-4c1e-9d3e-0f2a7b6c9d10",
      "url": "https://tracker.example.com/events",
      "description": "Conversion tracker",
      "format": "json",
      "events": [
        "order.paid",
        "order.refunded"
      ],
      "status": "active",
      "include_customer": true,
      "rate_per_second": 20,
      "failure_since": null,
      "last_success_at": "2026-11-20T13:59:00.000Z",
      "disabled_at": null,
      "notification_state": null,
      "created_at": "2026-11-01T10:00:00.000Z",
      "updated_at": "2026-11-01T10:00:00.000Z"
    }
  ],
  "events": [
    "checkout.lead_captured",
    "order.paid",
    "order.payment_failed",
    "upsell.accepted",
    "upsell.declined",
    "upsell.payment_failed",
    "flow.completed",
    "order.refunded",
    "order.chargeback",
    "offer_viewed",
    "offer_variant_changed",
    "offer_accepted",
    "offer_declined",
    "offer_timer_expired",
    "offer_charge_failed"
  ]
}
```

| response field | type | description |
|---|---|---|
| `rows` | object[] | Endpoints (never their secret), ordered by created_at. |
| `rows[].checkout_id` | string (uuid) \| null | null for an account-wide endpoint (scope account). |
| `rows[].status` | enum: active \| paused \| disabled | disabled = switched off by the delivery worker after persistent failures (failure_since, disabled_at); PUT with status active re-enables it. |
| `rows[].format` | enum: json \| url_template | json = signed POST of the JSON payload; url_template = GET of the URL with its macros filled. |
| `rows[].include_customer` | boolean | Whether payloads carry the customer object. |
| `rows[].rate_per_second` | integer | Delivery rate limit of the endpoint. |
| `rows[].failure_since / last_success_at / disabled_at / notification_state` | string \| null | Delivery health of the endpoint. |
| `events` | string[] | Every event type an endpoint may subscribe to. |

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's. {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `POST /v1/checkouts/:checkoutId/webhooks`

**Scope** `checkouts.write` - **Add checkout webhook**

Creates a webhook endpoint for the checkout (scope checkout) or for every checkout of the account (scope account): a public HTTPS destination, 1 to 9 subscribed events and a delivery policy. Answers 201 {id, secret}: the signing secret is returned only here. Also enrols the checkout in the event pipeline.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `url` | string | **yes** | Public HTTPS port 443 URL; no credentials, redirects or private addresses. |
| `description` | string | no | Display label, at most 300 characters. |
| `scope` | string | no | checkout or account. Default checkout; account applies to every account checkout. |
| `format` | string | no | json (POST, default) or url_template (GET). No customer-data URL macros. |
| `events` | string[] (enum) | **yes** | 1 to 9 event types (duplicates are removed) from the 15 webhook events: checkout.lead_captured, order.paid, order.payment_failed, upsell.accepted, upsell.declined, upsell.payment_failed, flow.completed, order.refunded, order.chargeback, offer_viewed, offer_variant_changed, offer_accepted, offer_declined, offer_timer_expired, offer_charge_failed. Any other value is a 400. |
| `status` | string | no | active (default) or paused. Explicitly re-enabling resets a disabled failure interval. |
| `includeCustomer` | boolean | no | Defaults true for merchant checkout/account endpoints. With linkId, explicitly send false; private customer data is forbidden for link-scoped endpoints. |
| `ratePerSecond` | integer | no | Durable endpoint limit 1-100, default 20. |

**Request body**

```json
{
  "url": "https://tracker.example.com/events",
  "description": "Conversion tracker",
  "scope": "checkout",
  "format": "json",
  "events": [
    "order.paid",
    "order.refunded"
  ],
  "status": "active",
  "includeCustomer": true,
  "ratePerSecond": 20
}
```

**Response**

```json
{
  "id": "00000000-0000-4000-8000-000000000003",
  "secret": "whsec_EXAMPLE_ONLY"
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId. {"error":"Invalid webhook configuration"} for an invalid body (strict: unknown fields refused); {"error":"Use a public HTTPS destination on port 443 with supported macros"} for a URL that is not public HTTPS on port 443 or carries an unsupported macro; {"error":"Link webhooks cannot include private customer data or other links"} with linkId when scope is not checkout, includeCustomer is not false, or the URL uses the {email} macro.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's. {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.
- Store the secret at once: it is never returned again (rotate it with POST /v1/checkouts/:checkoutId/webhooks/:endpointId/rotate-secret).

##### `PUT /v1/checkouts/:checkoutId/webhooks/:endpointId`

**Scope** `checkouts.write` - **Edit checkout webhook**

Replaces the whole configuration of an endpoint (same body as creation; omitted fields take their defaults). Sending status active on a disabled endpoint re-enables it and clears its failure interval. The secret is unchanged.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `url` | string | **yes** | Public HTTPS port 443 URL; no credentials, redirects or private addresses. |
| `description` | string | no | Display label, at most 300 characters. |
| `scope` | string | no | checkout or account. Default checkout; account applies to every account checkout. |
| `format` | string | no | json (POST, default) or url_template (GET). No customer-data URL macros. |
| `events` | string[] (enum) | **yes** | 1 to 9 event types (duplicates are removed) from the 15 webhook events: checkout.lead_captured, order.paid, order.payment_failed, upsell.accepted, upsell.declined, upsell.payment_failed, flow.completed, order.refunded, order.chargeback, offer_viewed, offer_variant_changed, offer_accepted, offer_declined, offer_timer_expired, offer_charge_failed. Any other value is a 400. |
| `status` | string | no | active (default) or paused. Explicitly re-enabling resets a disabled failure interval. |
| `includeCustomer` | boolean | no | Defaults true for merchant checkout/account endpoints. With linkId, explicitly send false; private customer data is forbidden for link-scoped endpoints. |
| `ratePerSecond` | integer | no | Durable endpoint limit 1-100, default 20. |

**Request body**

```json
{
  "url": "https://tracker.example.com/events",
  "description": "Conversion tracker",
  "scope": "checkout",
  "format": "json",
  "events": [
    "order.paid",
    "order.refunded"
  ],
  "status": "active",
  "includeCustomer": true,
  "ratePerSecond": 20
}
```

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId. {"error":"Invalid webhook configuration"} for an invalid body (strict: unknown fields refused); {"error":"Use a public HTTPS destination on port 443 with supported macros"} for a URL that is not public HTTPS on port 443 or carries an unsupported macro; {"error":"Link webhooks cannot include private customer data or other links"} with linkId when scope is not checkout, includeCustomer is not false, or the URL uses the {email} macro.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.
- PUT is a full replacement: an omitted description becomes "", an omitted includeCustomer becomes true, an omitted ratePerSecond becomes 20.

##### `DELETE /v1/checkouts/:checkoutId/webhooks/:endpointId`

**Scope** `checkouts.write` - **Delete checkout webhook**

Deletes an endpoint (soft delete: it is paused and hidden; its past deliveries stay). Answers {ok: true}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "ok": true
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `GET /v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries`

**Scope** `checkouts.read` - **List webhook deliveries**

Read delivery status, attempts, HTTP result and latency with server pagination and optional UTC period/state filters. Supply linkId to manage endpoints for one saved standalone link.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | ISO 8601 | no | Inclusive UTC created-at boundary. ISO 8601 datetime with Z (an offset is refused). |
| `to` | ISO 8601 | no | Exclusive UTC created-at boundary. ISO 8601 datetime with Z (an offset is refused). |
| `state` | string | no | pending, processing, succeeded, failed or cancelled. |
| `limit` | integer | no | 1-500; default 50. |
| `offset` | integer | no | 0-100000; default 0. |
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "rows": [],
  "total": 0
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId. {"error":"Invalid delivery filters"} for an invalid or unknown query parameter.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.
- Strict query: from, to, state, limit, offset and linkId only.

##### `GET /v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries/:deliveryId`

**Scope** `checkouts.read` - **View webhook payload and attempts**

Rebuild the request from immutable source records using the current customer-data policy, and return retained response diagnostics. Supply linkId to manage endpoints for one saved standalone link.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |
| `deliveryId` | uuid | **yes** | Account-owned delivery identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "payload": {
    "id": "evt_00000000-0000-4000-8000-000000000004",
    "type": "order.paid",
    "api_version": "2026-10-29",
    "created_at": "2026-10-29T00:00:00Z",
    "account_id": "acc_0000000000000000",
    "test": false,
    "data": {}
  },
  "logs": []
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope); {"error":"Delivery not found"}. {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `POST /v1/checkouts/:checkoutId/webhooks/:endpointId/deliveries/:deliveryId/resend`

**Scope** `checkouts.write` - **Resend one webhook delivery**

Queues a new delivery (next generation) of the same event to the endpoint and answers {id} of the new delivery. The original delivery is unchanged. No body is read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |
| `deliveryId` | uuid | **yes** | Account-owned delivery identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "id": "00000000-0000-4000-8000-000000000005"
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope); {"error":"Delivery not found"}. {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `POST /v1/checkouts/:checkoutId/webhooks/:endpointId/resend-failed`

**Scope** `checkouts.write` - **Resend failed webhook period**

Queues one new delivery for every distinct event whose delivery to this endpoint failed in [from, to) and answers {queued: <count>}.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `from` | ISO 8601 | **yes** | Start of the period, inclusive. ISO 8601 datetime with Z, matched on the delivery creation time. |
| `to` | ISO 8601 | **yes** | End of the period, exclusive; must be after from. ISO 8601 datetime with Z, matched on the delivery creation time. |

**Request body**

```json
{
  "from": "2026-10-01T00:00:00Z",
  "to": "2026-11-01T00:00:00Z"
}
```

**Response**

```json
{
  "queued": 15
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId. {"error":"Invalid period"} when from / to are missing, not ISO datetimes with Z, carry an unknown field, or to is not after from.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `POST /v1/checkouts/:checkoutId/webhooks/:endpointId/rotate-secret`

**Scope** `checkouts.write` - **Rotate webhook secret**

Issues a new signing secret; the previous one keeps signing (dual signature) for exactly 24 hours (previousValidUntil). The new secret is returned only here. No body is read.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Response**

```json
{
  "secret": "whsec_EXAMPLE_ONLY",
  "previousValidUntil": "2026-10-30T00:00:00.000Z"
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId.
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `409` {"error":"Wait until the current rotation window ends"} while a previous rotation is still inside its 24-hour grace window.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

##### `POST /v1/checkouts/:checkoutId/webhooks/:endpointId/test`

**Scope** `checkouts.write` - **Send a synthetic webhook event**

Queues a delivery of a synthetic test event of the chosen type to the endpoint and answers {id (the delivery id), eventId ("evt_<uuid>")}. The test event is flagged test on the delivery list.

**Path parameters**

| field | type | required | description |
|---|---|---|---|
| `checkoutId` | uuid | **yes** | Account-owned checkout identifier. |
| `endpointId` | uuid | **yes** | Account-owned endpoint identifier. |

**Query parameters**

| field | type | required | description |
|---|---|---|---|
| `linkId` | uuid | no | Optional saved standalone link id (uuid) of this checkout. Omit it to manage the checkout and account endpoints; send it on every request to manage the endpoints of that one link (a malformed value answers 400 "A valid link is required"; a link that is not a live, unarchived link of this checkout answers 404 "Link not found"). |

**Body parameters**

| field | type | required | description |
|---|---|---|---|
| `event` | enum | **yes** | One of the 15 event types: checkout.lead_captured, order.paid, order.payment_failed, upsell.accepted, upsell.declined, upsell.payment_failed, flow.completed, order.refunded, order.chargeback, offer_viewed, offer_variant_changed, offer_accepted, offer_declined, offer_timer_expired, offer_charge_failed. |

**Request body**

```json
{
  "event": "order.paid"
}
```

**Response**

```json
{
  "id": "00000000-0000-4000-8000-000000000005",
  "eventId": "evt_00000000-0000-4000-8000-000000000004"
}
```

**Errors**

- `400` {"error":"Invalid identifier"} when a path id is not a uuid; {"error":"A valid link is required"} for a malformed linkId. {"error":"Invalid event"} when event is missing or not one of the 15 event types (strict body).
- `401` {"error":"Missing bearer token"} when no Authorization: Bearer header is sent; {"error":"Invalid API key"} for an unknown or deactivated key.
- `402` {"error":"A paid platform subscription is required","code":"subscription_required","subscriptionStatus":"unpaid","billingPath":"/subscription"} when the account has no paid or granted platform subscription.
- `403` {"error":"API key scope denied","code":"insufficient_scope","requiredScope":"<the scope of this endpoint>"} when the key's scopes do not include the endpoint's required scope; {"error":"Banned","message":"<reason>"} when the account owner is banned; {"error":"An active account owner is required for admin API access"} when the key's owner no longer has an active role; {"error":"Your subscription does not include this tool.","code":"subscription_module_required","module":"checkouts"} when the account's plan lacks the checkouts module; {"error":"Forbidden"} when the User-Agent looks like a crawler or scanner. {"error":"Forbidden"} when the request also carries an affiliate session cookie.
- `404` {"error":"Checkout not found"} when the checkout is not one of the account's; {"error":"Webhook not found"} when the endpoint is not one of the account's (or of the link scope). {"error":"Link not found"} for a linkId that is not a live link of this checkout.
- `429` Per-IP rate limit exceeded (default 300 requests per minute, counted per server instance).
- `500` {"error":"Webhook operation failed"} on any unexpected failure (this route family masks server errors with that sentence).
- `503` {"error":"Server busy, retry"} with Retry-After: 1 when the instance is saturated; {"error":"The database is temporarily unavailable - please retry in a moment."} when the database cannot be reached. Both are safe to retry.

**Gotchas**

- All endpoints are account-scoped; this checkout and all-checkout endpoints appear together. No request-supplied account identity is trusted.
- No payment is initiated by these management APIs.
- Secrets are encrypted and shown only once at creation/rotation, never in list or delivery responses.
- With linkId, every lookup and delivery is scoped to that exact saved standalone link. Endpoint IDs cannot cross links, checkouts or accounts. Revoked creator access stops new delivery.
- Link configuration requires scope=checkout and includeCustomer=false. Customer objects, gateway identifiers, card last4 and affiliate cuts are removed; only payment.card_brand may remain. The email URL macro is refused.
- The link comes from persisted purchase/session attribution. A buyer URL cannot choose a webhook recipient. Management never charges a customer.
- A source-link webhook follows the persisted acquisition-link attribution even when a flow selects a different checkout; merchant checkout-scoped webhooks follow the actual final checkout, and account-wide endpoints retain their account scope.

#### Services Kontrol calls

The external services the platform calls on the account's behalf: what for, and on which host.

Kontrol calls these services on the account's behalf, with the credentials the account saved for them (stored encrypted). Hosts are for allowlists and audits.

| service | what for | host |
|---|---|---|
| Checkout webhooks | Account-scoped signed checkout event POST JSON or GET template delivery with retries. | Merchant-configured public HTTPS hosts, port 443; DNS pinned per dispatch. |
| Stripe | PaymentIntents (S2S), Embedded and Hosted Checkout Sessions, verified settlement reads and refunds. | api.stripe.com/v1 · js.stripe.com · checkout.stripe.com |
| NMI | Card sales, subscription charges, refunds, voids, transaction queries (the main gateway). | secure.nmi.com/api/transact.php · secure.nmi.com/api/query.php |
| ConvesioPay S2S | Direct gateway charges and Apple Pay / Google Pay wallet payments. | s2s.convesiopay.com/v1 |
| PAAY (3DS) | 3-D Secure authentication (frictionless / challenge). | api.3dsintegrator.com/v2.2 (sandbox: api-sandbox.3dsintegrator.com) |
| Evervault (3DS) | 3-D Secure authentication. | 3ds.evervault.com · api.evervault.com |
| VGS (3DS) | 3-D Secure authentication. | vgsapi.com (sandbox: sandbox.vgsapi.com) · auth.verygoodsecurity.com (OAuth token) |
| 3dsecure.io (3DS) | 3-D Secure authentication. | service.3dsecure.io (sandbox: service.sandbox.3dsecure.io) |
| Exify | External subscription export (the accounts handled outside the in-house engine). | Configurable per account (Exify integration). |
| PlatformPay | Order push to PlatformPay. | Configurable (PlatformPay integration). |
| TheSupportCare (TSC) | Order creation in the support / tracking tool after an approved sale. | tracking.getsupportcare.com/api/createOrder |
| Meta Conversions API | Server-side Purchase for eligible merchant/store and immutable saved-link pixels. | graph.facebook.com |
| TikTok Events API | Server-side Purchase events. | business-api.tiktok.com/open_api/v1.3/event/track/ |
| Snapchat Conversions API | Server-side Purchase events. | tr.snapchat.com/v3/ |
| Whop | Order events. | api.whop.com/api/v1/events |
| MessageWhiz (SMS) | Abandoned-cart SMS and alerts. | sms.messagewhiz.com/sms |
| SMTP (e-mail) | Abandoned-cart e-mails and alerts through the account's SMTP providers. | Per provider host / port (nodemailer). |
| OpenAI | AI provider (storefront generation, verification of the integration). | api.openai.com/v1 |
| Anthropic | AI provider (storefront copy generation). | api.anthropic.com/v1/messages |
| Fal.ai | AI media generation. | api.fal.ai/v1 · queue.fal.run |
| Higgsfield | AI media generation. | platform.higgsfield.ai |
| Namecheap | Domain list and DNS for the stores. | api.namecheap.com/xml.response (sandbox: api.sandbox.namecheap.com) |
| Pilot | TikTok ad spend per day (the Live Report: users/me, live-report/status, live-report/range, live-report/day, auth/tiktok/status, live-report/run-now) for the Pilot Spend / ROAS cards. | pilot.ad/api (configurable per account) |
| Google Ads API | v3.9.18: server-side purchase conversions (customers/{id}:uploadClickConversions, partialFailure, validateOnly for test orders, ≤ 2000 per request) and the « Test connection » reads (customers:listAccessibleCustomers, googleAds:search on conversion_action); the OAuth 2.0 refresh-token exchange before them. | googleads.googleapis.com/v25 · oauth2.googleapis.com/token |

