# securepayAPI — agent integration handbook (checkout layer)

This is the contract for an AI coding agent that builds, reviews or operates an
integration with the securepayAPI **checkout layer**: the Payment Intents API,
subscriptions, the JavaScript SDK / embedded widget, hosted checkout pages,
webhooks and the transaction lookup. It is written to be read by a model: each
rule is stated once, in imperative form, with exact names.

It was checked against the running code on **2026-11-12**. Do not invent a
route, a field, a default, a status or a retry rule that is absent here or in
its chapters. When something you need is missing, stop and ask.

Pages with the same facts, for people: https://doc.securepayapi.com/

> Scope boundary. This layer never shows you a card number: the card is typed
> into an iframe served by securepayAPI. If the merchant must send card data to
> the processing API itself (PCI DSS scope), that is the **direct core
> integration**, documented separately in the private section
> (https://doc.securepayapi.com/private). Do not mix the two: the checkout
> layer's base URL is `https://checkout.securepayapi.com`; core's is
> `https://securepayapi.com`.

## How this handbook is organised

This file holds the rules that decide money, the credentials, the route map,
the fulfilment decision and the checklist. **Each area has a chapter with the
full contract** — every request field with its type and limits, an example
request, every response body by HTTP status, the errors actually returned, and
every message or event payload. Read the chapter before you write a call.

| Chapter | Covers |
| --- | --- |
| [`/agents/intents-subscriptions.md`](/agents/intents-subscriptions.md) | Payment Intents: create, read, set `externalid`, `notify_url`, statuses, errors. Recurring subscriptions: plans, the `subscription` block, activation, agreements, fixed and variable billing, retries, every subscription event with its payload, dead ends |
| [`/agents/widget-sdk.md`](/agents/widget-sdk.md) | The JavaScript SDK (options, the handle, callbacks, events), the embedded-widget `postMessage` protocol in both directions, 3-D Secure and wallets in the widget, sandbox and testing |
| [`/agents/webhooks-transactions.md`](/agents/webhooks-transactions.md) | The webhook request and signature, the full payload with examples, the status enum, what triggers what, what is never sent, a correct handler; the transactions API; disputes |
| [`/agents/hosted-products.md`](/agents/hosted-products.md) | Hosted product checkout pages, products and coupons, hosted invoices with bank and USDC pay-ins |

Everything in one file: [`/agents-full.md`](/agents-full.md) (this entry
followed by the four chapters). Where this entry and a chapter differ, the
chapter is right — it carries the detail.

---

## 1. Invariants (read first)

- **The server decides the money.** Amount, currency, live/sandbox and any
  subscription terms are fixed when the merchant's backend creates the
  Payment Intent with its secret key. Nothing the browser sends can change
  them. Never put `amount`, `currency` or `mode` under the control of page
  code or a URL.
- **The browser's "success" is not evidence.** Before fulfilling, the backend
  reads the intent back with `GET /api/v1/payment-intents/{id}` and checks
  `status`, `amount`, `currency` and `mode` against the order it created.
- **`status: "pending"` means "do not ask for money again".** The payment was
  accepted and its outcome is not settled yet. Show "being confirmed", then let
  the server poll the intent. Treating pending as failure is how a shopper pays
  twice.
- **An intent that reads `processing` means the charge was sent.** Money may
  have moved: never treat it as unpaid, never as paid. While the customer is
  still typing a card, approving a wallet sheet or passing 3-D Secure the
  intent reads `requires_payment`.
- **Known defect — Google Pay with a bank redirect.** When the bank requires a
  redirect 3-D Secure during a Google Pay payment in the widget, the platform
  may capture the payment while the intent keeps reading `requires_payment`,
  and the page may receive neither `success` nor `error`. For an intent that
  stays `requires_payment` after the shopper approved a wallet payment, look
  the payment up (`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`
  or the dashboard) **before** asking for another payment.
- **One intent per order attempt; store the intent `id` with the order.**
  Confirm the id *you* created — never one the browser hands you. Any
  succeeded intent passes a status check, including one the same shopper paid
  earlier for the same amount.
- **A subscription is `pending_activation` after payment, never `active`.**
  The widget's success message says the first charge was captured. The
  agreement is activated by the payment platform afterwards, on its side, and
  no webhook announces it: read the agreement.
- **Keys:** `sp_secret_…` lives only on the server (Bearer header). `sp_client_…`
  is publishable and goes to the browser. The `client_secret` is the capability
  to pay one intent — hand it only to that customer's session, never log it.
- **Never tear the widget down while a payment is active.** From
  `payment_started` until `payment_ended`, `success` or `error` (SDK:
  `onActive(true)` … `onActive(false)`) a wallet sheet or a 3-D Secure challenge
  is open *inside the iframe*. Removing or re-creating the iframe, swapping the
  `clientSecret` or navigating kills it. A checkout that creates a new intent
  per cart edit must queue that change until the active window closes.
- **A `transaction_reference` that has done nothing is not a stuck payment.**
  After a wallet decline the widget prepares a new attempt, so the intent
  points at a fresh reference; the decline is in `last_attempt`. One intent can
  therefore have several transactions.
- **Webhooks describe the transaction, not the intent.** Verify the signature
  on the raw body with the webhook signing secret (not the API secret), expect
  merged, repeated and out-of-order deliveries, keep processing after `PAID`
  (refunds and disputes follow), and treat the transaction read as the source
  of truth.

---

## 2. Credentials and identifiers

| Credential | Looks like | Where | Used for |
| --- | --- | --- | --- |
| Secret key | `sp_secret_…` (42 characters: the prefix and 32 letters and digits) | server only, `Authorization: Bearer` | every `/api/v1/*` call, and the transactions API |
| Publishable key | `sp_client_…` (same shape) | browser | identifies the account to the widget (`SecurePay('sp_client_…')`, `/embed?pk=`) |
| Client secret | `pi_<intentId>_secret_<random>` | the paying customer's browser session | completes one intent; valid **7 days**; the payment can succeed **once** |
| Webhook signing secret | shown **once** per endpoint when issued in Developer → Webhooks. Saving the same URL keeps its secret. Changing the URL or choosing **New secret** rotates it. | server only | verifies `X-Signature` on webhooks |

Identifiers:

| Value | Shape | Notes |
| --- | --- | --- |
| Intent `id` | 24 lowercase alphanumerics | yours to store against the order |
| `transaction_reference` | newly issued: `LU` + 14 uppercase alphanumerics; store as a string up to 128 characters | the payment platform's reference for the current attempt; the `id` in webhooks and on the transaction |
| `externalid` on the transaction / in webhooks | your `externalid` from the intent, else the intent `id`; on a hosted product page, the product id | correlation key. Send at most **128** characters: the create route accepts more, but a longer value makes every payment attempt fail |

Both keys are managed in the dashboard: https://app.securepayapi.com/developer.
Regenerating a key invalidates the old one immediately. While the account is
not active the keys are refused: `401 invalid_api_key` on
`checkout.securepayapi.com`, `403` on the transactions API.

---

## 3. Endpoints

| Method | URL | From | Purpose |
| --- | --- | --- | --- |
| `POST` | `https://checkout.securepayapi.com/api/v1/payment-intents` | server | create an intent → `client_secret` |
| `GET` | `https://checkout.securepayapi.com/api/v1/payment-intents/{id}` | server | read an intent back to **confirm** |
| `POST` | `https://checkout.securepayapi.com/api/v1/payment-intents/{id}` | server | set `externalid` on an unpaid intent |
| `POST` `GET` | `https://checkout.securepayapi.com/api/v1/subscription-plans` | server | create / list subscription plans |
| `POST` | `…/api/v1/subscription-plans/versions`, `…/archive`, `…/reactivate` | server | evolve a plan |
| `GET` | `…/api/v1/subscriptions/{externalReference}`, `…/api/v1/subscriptions` | server | read an agreement (activation, status, cycles) |
| `POST` | `…/api/v1/subscriptions/cycles`, `…/cancel`, `…/pause`, `…/resume`, `…/contact` | server | bill a variable period; manage an agreement |
| `GET` | `https://checkout.securepayapi.com/sdk/v1/securepay.js` | browser | the SDK |
| `GET` | `https://checkout.securepayapi.com/embed?pk=sp_client_…` | browser (iframe) | the widget (what the SDK loads for you) |
| `GET` | `https://checkout.securepayapi.com/<productId>` | browser | a hosted checkout page for a dashboard product |
| `GET` | `https://app.securepayapi.com/api/v1/transactions/{id}` | server | read the transaction record |

Every `/api/v1/*` endpoint on `checkout.securepayapi.com` sends **no CORS
headers**: a browser call is refused by the browser. Use the exact paths, no
trailing slash. Bodies are JSON with `Content-Type: application/json`.

The widget's own internal endpoints (`/api/card-payment/*`) are not part of the
contract. Never call them.

`/embed` is fail-closed: an unknown `pk`, or a merchant with no registered
domain, answers **404**, and the frame posts nothing — no callback fires. The
page must be on a registered domain; the host is compared **including the
port**, so `localhost:3000` must itself be registered for local development.

Details of every call: [Payment Intents and subscriptions](/agents/intents-subscriptions.md),
[SDK and widget](/agents/widget-sdk.md),
[transactions API](/agents/webhooks-transactions.md),
[hosted pages](/agents/hosted-products.md).

---

## 4. Confirm a payment — the fulfilment decision

Read the intent with the secret key: `GET /api/v1/payment-intents/{id}`. The
full response and its fields are in the
[Payment Intents chapter](/agents/intents-subscriptions.md).

```text
status succeeded AND amount/currency equal the order AND mode is live AND the id is the one you stored  → fulfil
status processing                                                                                   → money may have moved: do not fulfil, do not charge again; read again
status processing that does not clear                                                               → settle it from the transactions API or the dashboard
status requires_payment after the shopper approved a Google Pay payment                              → look the transaction up before asking for another payment (known defect)
status requires_payment or failed, before expires_at                                                 → unpaid; the customer may retry
expires_at passed, not succeeded                                                                     → reconcile any pending/uncertain capture before a new payment
mode sandbox                                                                                         → a test; no money moved
```

There is no `expired` status: only `expires_at` tells you the intent can no
longer be paid. `last_attempt` is the browser's account of the previous attempt
— enough to explain, never enough to settle.

To learn about a capture even when the shopper never returns to your page, set
`notify_url` when you create the intent: the platform then POSTs
`{ id, status, externalid }` to it after the capture. That call is **unsigned
and is a hint only** — read the intent back before acting on it.

---

## 5. Rules per call — retry and idempotency

| Call | Retry? | Notes |
| --- | --- | --- |
| `POST /payment-intents` | not blindly — no idempotency key | every call creates a new intent; on a timeout, check your own store before creating another |
| `GET /payment-intents/{id}` | yes, freely | read-only |
| `POST /payment-intents/{id}` (external id) | yes | setting the same value again is harmless; `409 intent_not_updatable` once the intent is paid or its capture is uncertain |
| widget `submit()` | never call twice while pending | one promise per attempt; it settles exactly once |
| after `status: "pending"` | poll `GET` | never start a new payment for the same order |
| webhook handling | idempotent per transaction `id` and `status`; subscription events per `id` + `paymentId` + `occurredAt` | merged, repeated and out-of-order deliveries happen |
| `GET` transactions API | yes, freely | source of truth after the payment |
| new intent on a cart change | only while **no** payment is active | queue it from `payment_started` until `payment_ended`/`success`/`error`, then create the intent and remount |
| `POST /subscription-plans` | only with unchanged facts | no idempotency key; a replay with the same `externalReference` and identical facts is safe; a replay with changed facts answers `502 upstream_error` — do not retry it, use `/versions` |
| `GET /subscriptions…`, `GET /subscription-plans…` | yes, freely | read-only |
| `POST /subscriptions/cycles` | yes, **with the same `idempotencyKey`** | a new key for the same period is `409`; never bill a period twice; the answer is a schedule, not a payment |
| `POST /subscriptions/cancel`, `pause`, `resume`, `contact` | yes, with the same key **and the same facts** | reusing a key with different facts answers `502`; `409` while a charge is in flight → wait and retry; read `status` in the answer |

---

## 6. Pre-launch checklist

- Secret key only on the server; publishable key only in the browser; no key
  in a repository.
- Intent created server-side with the order's exact `amount`/`currency`; `id`
  stored on the order before the `client_secret` reaches the browser.
- `mode` set explicitly per environment, and the same `mode` for a plan and the
  intents and agreements that use it; sandbox tests never promoted to live by a
  page flag.
- Fulfilment happens only after `GET /payment-intents/{id}` shows `succeeded`
  with matching `amount`, `currency`, `mode` and the stored `id`.
- `status: "pending"` shows "being confirmed" and triggers server polling, not
  a retry. `processing` is "money may have moved".
- A Google Pay payment whose intent stays `requires_payment` is looked up in
  the transactions API before the shopper is asked to pay again.
- Webhook endpoint verifies `X-Signature` on the raw body with the signing
  secret, answers 2xx within 10 s, is idempotent, never moves an order
  backwards, keeps handling refunds and disputes after `PAID`, and is backed by
  a reconciliation job that reads the transaction.
- `externalid` is at most 128 characters; nothing depends on `descriptor`,
  `description` or `metadata` reaching the transaction or a webhook.
- For subscriptions: `termsHash` computed from the exact `termsText`;
  `shopperExternalReference` is a customer id, not an email; `billingAnchor`
  carries an offset and is at least an hour out; access granted only after the
  agreement reads `active`; the dead ends in the
  [subscriptions chapter](/agents/intents-subscriptions.md) are handled.
- The checkout page runs on a registered domain (port included) over HTTPS;
  `loc` is the real page URL when wiring the iframe yourself.
- The page never removes or re-creates the widget, swaps the `clientSecret` or
  navigates while `onActive` is `true`; cart-driven intent changes are queued.
- Support tooling reads `last_attempt` before calling a payment "stuck".
- Logs contain intent ids and transaction references — never `client_secret`,
  keys, card data or consent text.

## Hosted invoice bank and USDC options

Bank (ACH, wire) and USDC pay-ins are options of the **hosted invoice** page,
not Payment Intents or SDK capabilities — do not generate them as such. The
customer pays exactly the amount in the instructions the page shows; nothing is
paid until the platform confirms the funds, and no webhook is guaranteed for a
bank pay-in: check the invoice. See
[hosted pages and pay-ins](/agents/hosted-products.md).


---

## Payment Intents API

Base URL: `https://checkout.securepayapi.com`. Call every endpoint below from
the merchant's **server** only. The endpoints send no CORS headers; a browser
call fails, and the secret key must never reach a browser.

### Keys and authentication

- The account has one key pair, created in the dashboard (**Developer** →
  **Generate API keys**): publishable `sp_client_…` (labelled **Client key**)
  and secret `sp_secret_…`. Each is the prefix plus 32 base62 characters
  (42 characters in total). The same pair serves live and sandbox; the
  environment is the `mode` of each request.
- Send `Authorization: Bearer sp_secret_…` on every call in this chapter. The
  word `Bearer` is case-insensitive; surrounding whitespace is ignored.
- Regenerating a key in the dashboard invalidates the old one immediately.
  The secret key stays readable in the dashboard.
- Never put the secret key in page code, a mobile app, a repository or a log.

| Status | Body | Cause | Do |
| --- | --- | --- | --- |
| `401` | `{"error":{"type":"authentication","code":"missing_api_key","message":"Missing 'Authorization: Bearer <secret key>' header."}}` | No `Authorization: Bearer …` header | Send the header. |
| `401` | `{"error":{"type":"authentication","code":"invalid_api_key","message":"The provided API key is invalid."}}` | Not an `sp_secret_` key, unknown or rotated key, or the account is not active | Fix the key; if it is correct, contact support. |

The same secret key authenticates the transactions API at
`https://app.securepayapi.com/api/v1/transactions/{id}`; there an inactive
account answers `403 {"error":"Account is not active"}`.

### Error envelope

Every error from `/api/v1/*` is JSON with `Cache-Control: no-store`:

```json
{ "error": { "type": "invalid_request", "code": "amount_invalid", "message": "'amount' must be an integer in minor units (e.g. 2000 = $20.00)." } }
```

`type` is one of `invalid_request`, `authentication`, `forbidden`,
`not_found`, `conflict`, `server`. Branch on `code`; show or log `message`;
never parse `message`. A `5xx` without this body can occur when the service
is briefly unable to reach its database: treat it as a retryable `500`.

### `POST /api/v1/payment-intents` — create

Create one intent per order attempt. Store the returned `id` with the order
before you hand anything to the browser.

#### Request fields

| Field | Type | Required | Rule | On failure (`400`, `invalid_request`) |
| --- | --- | --- | --- | --- |
| `amount` | JSON integer | yes | Minor units (cents). 1 – 99,999,999. A float or a string is refused. | `amount_invalid` (not an integer), `amount_out_of_range` |
| `currency` | string | yes | Trimmed and upper-cased; must be `USD`. | `currency_unsupported` |
| `reference` | string | no | ≤ 200 chars, stored as sent. Returned by `GET`. Never sent to the payment platform. | `reference_invalid` |
| `metadata` | object | no | Not an array; every value a string (one level); `JSON.stringify(metadata)` ≤ 4096 bytes UTF-8. Returned by `GET`. Not on the transaction, not in webhooks. | `metadata_invalid`, `metadata_too_large` |
| `externalid` | string | no | Accepted up to 200 chars (counted before trimming), stored trimmed, blank = absent. **Send at most 128**: the payment platform refuses a longer value at every payment attempt, so the customer can never pay the intent. Becomes the transaction's external reference (in webhooks and on the transaction). Absent → the transaction carries the intent `id`. | `externalid_invalid` |
| `descriptor` | string | no | Trimmed; blank = absent; else 5 – 100 chars. Stored only: it does **not** reach the statement. | `descriptor_invalid` |
| `description` | string | no | Same rule. Stored only. | `description_invalid` |
| `theme` | string | no | `light` (default) or `dark`: the widget's colour scheme. | `theme_invalid` |
| `mode` | string | no | `live` (default) or `sandbox`. Fixed for the intent's life; the browser cannot change it. | `mode_invalid` |
| `subscription` | object | no | Makes the payment a recurring-agreement setup or a card replacement. See "The subscription block" below. | `subscription_…` codes |
| `notify_url` | string | no | `null` or `""` = absent. Otherwise, after trimming: ≤ 2048 chars, absolute `https:` URL, port 443 or none, no user name/password, no `#fragment`, host name with a dot, not an IP literal, not ending in `.local`, `.internal` or `.localhost`. See the `notify_url` section below. | `notify_url_invalid` |

A body that is not valid JSON → `400 invalid_json` ("Body is not valid
JSON."). Fields are checked in the table's order (`amount`, `currency`,
`reference`, `metadata`, `externalid`, `descriptor`, `description`, `theme`,
`mode`, `subscription`, `notify_url`); only the first failure is reported.
Unknown fields are ignored.

#### Example request

```bash
curl https://checkout.securepayapi.com/api/v1/payment-intents \
  -H "Authorization: Bearer sp_secret_…" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 2000,
    "currency": "USD",
    "reference": "order_123",
    "externalid": "shop-order-123",
    "metadata": { "order_id": "123" },
    "notify_url": "https://shop.example.com/securepay/notify",
    "mode": "live"
  }'
```

#### Responses

`200`:

```json
{
  "id": "k3m9q2x7v1b8n4c6d0f5g7h2",
  "client_secret": "pi_k3m9q2x7v1b8n4c6d0f5g7h2_secret_Zx8…",
  "amount": 2000,
  "currency": "USD",
  "status": "requires_payment",
  "mode": "live"
}
```

- `id`: 24 characters `[a-z0-9]`.
- `client_secret`: `pi_<id>_secret_<random>`. Returned **only here**; it cannot
  be read back. It lets a browser pay this one intent and nothing else. Give
  it only to that customer's session; never log it.
- When `subscription` was sent, the body also has `subscription`: the stored
  block without `termsText`, with `operation` (`"setup"` or
  `"recoverPaymentMethod"`), `recurringSurchargeConsent: false`, and for a
  setup the canonical `billingTimezone` (`"UTC"` when none was sent).
- The intent expires **7 days** after creation.

| Status | `code` | Do |
| --- | --- | --- |
| `400` | field codes above | Fix the request. |
| `401` | `missing_api_key`, `invalid_api_key` | Fix the key. |
| `500` | `internal_error` ("Could not create the payment intent.") | Nothing was created. Retry. |

#### Idempotency

There is no idempotency key. Every successful `POST` creates a new intent. If
a create call times out, create another and keep only the `id` you stored;
an orphaned intent is harmless (it expires unpaid).

### `GET /api/v1/payment-intents/{id}` — read and confirm

Use it to confirm every payment before fulfilment. The browser's `success`
and the `notify_url` call are hints only.

```bash
curl https://checkout.securepayapi.com/api/v1/payment-intents/k3m9q2x7v1b8n4c6d0f5g7h2 \
  -H "Authorization: Bearer sp_secret_…"
```

`200`:

```json
{
  "id": "k3m9q2x7v1b8n4c6d0f5g7h2",
  "status": "succeeded",
  "amount": 2000,
  "currency": "USD",
  "mode": "live",
  "reference": "order_123",
  "externalid": "shop-order-123",
  "metadata": { "order_id": "123" },
  "transaction_reference": "LU494ZZ07K7814E3",
  "last_attempt": null,
  "created_at": "2026-11-12T19:02:11.000Z",
  "expires_at": "2026-11-19T19:02:11.000Z",
  "paid_at": "2026-11-12T19:04:58.000Z"
}
```

| Field | Meaning |
| --- | --- |
| `status` | See "Statuses" below. |
| `amount`, `currency`, `mode` | As created. |
| `reference`, `metadata` | As created. |
| `externalid` | The stored value, `null` if never set (the transaction then carries the intent `id`). |
| `transaction_reference` | The payment platform's reference of the current attempt; `null` before any. Bound when an attempt opens — for Apple Pay / Google Pay that is when the widget loads, before the customer acts. After `succeeded`, the reference of the captured payment. Equals the `id` in transaction webhooks and on `GET https://app.securepayapi.com/api/v1/transactions/{id}`. Store it. |
| `last_attempt` | `null`, or `{ reference, outcome, message, at }`: how the previous attempt ended, as the browser reported it when the widget prepared a new one. `outcome` ∈ `declined`, `cancelled`, `failed`, `pending`; `message` ≤ 200 chars or `null`. Use it to explain; never to settle. |
| `created_at`, `expires_at` | ISO-8601 UTC. |
| `paid_at` | ISO-8601 only when `status` is `succeeded`, else `null`. |

| Status | `code` | When |
| --- | --- | --- |
| `401` | `missing_api_key`, `invalid_api_key` | Bad key. |
| `404` | `intent_not_found` | Unknown id, an id not of the form 24 × `[a-z0-9]`, or another account's id (indistinguishable). |

#### Confirmation rule (apply all, in this order)

1. The `id` is the one **you stored** for this order. Never confirm an id the
   browser sent you: any succeeded intent passes the other checks, including
   one the same customer paid earlier for the same amount.
2. `status` is `succeeded` (and `paid_at` is set).
3. `amount` and `currency` equal the order.
4. `mode` is the environment you run in — `live` for real orders. A `sandbox`
   intent moved no money.
5. Store `transaction_reference` with the order.

### Statuses

| `status` | Meaning | Do |
| --- | --- | --- |
| `requires_payment` | Nothing charged. Also while the customer types a card, has a wallet sheet open or is in 3-D Secure, and after an attempt that never reached the charge (abandoned or failed authentication, closed sheet). `transaction_reference` may already be set. | Wait. Do not fulfil. See the Google Pay exception below. |
| `processing` | The capture was sent; the outcome is not final. | Never treat as paid, never as unpaid. Hold the order; read again later. |
| `succeeded` | Captured. Final. | Fulfil (after the confirmation rule). |
| `failed` | The last capture was declined; nothing taken. The intent stays payable until `expires_at`, and keeps reading `failed` while the customer tries another card, until that new capture is sent. | Let the customer retry; do not cancel the order before `expires_at` unless you choose to. |

- There is no `expired` status. After `expires_at` the intent cannot be paid,
  whatever `status` reads; compare `expires_at` with now.
- `processing` stays when (a) the capture outcome was uncertain — the widget
  reported `status: "pending"`; the intent is then closed to any further
  attempt so the customer cannot be charged twice — or (b) the answer to the
  capture never arrived; the intent stays payable. The API does not tell the
  two apart, and the intent can still turn `succeeded` later. Resolve it from
  `succeeded`, or from the transaction (`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`)
  or the dashboard. Never ask for the money again meanwhile.
- **Known defect — Google Pay with a redirect 3-D Secure.** When Google Pay
  in the widget hits a bank that redirects for 3-D Secure, the payment can be
  captured on the payment platform's own return page and the intent can stay
  `requires_payment` although the money was taken. For an intent that stays
  `requires_payment` after the customer approved a wallet payment, read the
  transaction by `transaction_reference` (or check the dashboard) **before**
  asking for another payment.

### `POST /api/v1/payment-intents/{id}` — set `externalid` later

Use it when the order number exists only after the intent (for example a
store that creates its order when the customer clicks "Place order").

| Field | Type | Required | Rule |
| --- | --- | --- | --- |
| `externalid` | string or `null` | yes | Trimmed, then ≤ 128 chars. `null`, `""` or blank clears it (the intent `id` is used again). |

```bash
curl https://checkout.securepayapi.com/api/v1/payment-intents/k3m9q2x7v1b8n4c6d0f5g7h2 \
  -H "Authorization: Bearer sp_secret_…" \
  -H "Content-Type: application/json" \
  -d '{ "externalid": "order-10452" }'
```

`200`: `{ "id": "k3m9q2x7v1b8n4c6d0f5g7h2", "externalid": "order-10452" }`

| Status | `type` / `code` | When |
| --- | --- | --- |
| `400` | `invalid_request` / `invalid_json` ("Body must be JSON.") | Body not JSON. |
| `400` | `invalid_request` / `externalid_invalid` | Field missing, not a string or `null`, or longer than 128 after trimming. |
| `401` | `authentication` / `missing_api_key`, `invalid_api_key` | Bad key. |
| `404` | `not_found` / `intent_not_found` | Unknown or another account's id. |
| `409` | **`invalid_request`** / `intent_not_updatable` ("The payment intent was already paid.") | The intent `succeeded`, or was closed after an uncertain capture. |

- The body is checked before the id (a bad body on an unknown id is `400`).
  An expired, never-paid intent can still be updated.
- The new value reaches the platform with the **next** attempt. An attempt
  already opened keeps the reference it was opened with — Apple Pay and
  Google Pay attempts open when the widget loads, so set `externalid` before
  mounting the widget when you need it on a wallet payment. The call never
  rewrites an existing transaction and never changes `reference`.

### `notify_url` — server-to-server payment notification

When the intent was created with `notify_url`, the service posts to it after
a capture, so the order does not depend on the customer's browser returning.

```http
POST /securepay/notify HTTP/1.1
Host: shop.example.com
Content-Type: application/json
User-Agent: securepayAPI-Notify/1.0

{"id":"k3m9q2x7v1b8n4c6d0f5g7h2","status":"succeeded","externalid":"order-10452"}
```

| Body field | Value |
| --- | --- |
| `id` | The intent id. |
| `status` | `succeeded`, or `processing` (capture sent, outcome uncertain). |
| `externalid` | The value stored on the intent, or `null`. |

Sent when: the capture succeeded (`succeeded`, once); the capture outcome is
uncertain (`processing`); the payment platform later reports the capture
(`succeeded`) — so a `processing` call can be followed by a `succeeded` one.
Never sent for a decline.

Delivery:

- First try 10 seconds after the capture; on failure, again at 1 minute and
  5 minutes after the capture; then stop. At most three tries. The call can
  still arrive at the same moment as the browser's own success (a slow
  browser, a retry): handle the two concurrently.
- Success = any `2xx`. Failure = other status (a `3xx` included — redirects
  are not followed), timeout (15 seconds), connection or DNS error.
- A host that resolves to a private, loopback, link-local or multicast
  address is never called and not retried.
- Best effort: a restart of the service within those five minutes loses the
  pending tries.

Receiver rules:

1. The call is **unsigned**. Never settle from its body.
2. Look up the order by the `id` you stored (ignore an `id` you do not know),
   then `GET /api/v1/payment-intents/{id}` and apply the confirmation rule.
3. Be idempotent and safe under concurrency: this call and the browser's own
   success can reach your server at the same moment. Settle an order under a
   lock (or a unique constraint), so it is completed once; an already settled
   order needs nothing.
4. Answer `2xx` quickly (within 15 seconds), even when nothing changed.
5. On `processing`, put the order on hold; never ask for payment again.
6. Keep your own check for orders still open (read the intent): the call can
   be lost.

### Outcome table — what to do with an intent

| Observation | Decision |
| --- | --- |
| `GET` → `succeeded`, amount/currency/mode match, id is yours | Fulfil. |
| `GET` → `succeeded` but amount, currency or mode differ | Do not fulfil; investigate. |
| `GET` → `processing` | Hold. Never re-charge. Re-read; reconcile via the transaction or dashboard. |
| `GET` → `failed`, before `expires_at` | Unpaid; the customer may retry with the same intent. |
| `GET` → `requires_payment` after the customer approved Google Pay | Check the transaction by `transaction_reference` before asking for money (known defect). |
| `GET` → `requires_payment` or `failed`, after `expires_at` | Unpaid and unpayable. Create a new intent if the customer comes back. |
| Widget `success` with `status: "pending"` | Show "being confirmed"; never ask again; settle from `GET`. |
| `notify_url` call received | Treat as a cue to `GET`; nothing else. |
| `GET` → `404` | Wrong id or wrong account key. Never fall back to an id from the browser. |

## Recurring subscriptions

The payment platform stores the card, runs the schedule, retries and the
lifecycle. The merchant's server creates plans, sells them with a Payment
Intent carrying a `subscription` block, reads agreements, bills variable
periods, and manages the lifecycle — all with `Authorization: Bearer sp_secret_…`
on `https://checkout.securepayapi.com`.

### Common rules for the subscription endpoints

- `mode`: `"live"` (default) or `"sandbox"`; body field on `POST`, query
  parameter on `GET`; `""` = live. Plans and agreements exist per mode. Use
  the **same** `mode` for a plan, the intents that sell it and every call on
  its agreements. Bad value → `400 mode_invalid`.
- Money is an exact decimal **string** (`"19.99"`). Only the Payment Intent
  uses integer cents (`1999`).
- Bodies: a JSON object of at most 16,384 bytes → otherwise `400 body_too_large`,
  or `400 invalid_json` ("Body is not valid JSON." / "Body must be a JSON object.").
- `externalReference` in a body or in the path: string of 1 – 255 chars with
  no surrounding whitespace → otherwise `400 externalReference_invalid`.
- `idempotencyKey` on mutations: a UUID (`8-4-4-4-12` hex), lower-cased by the
  service. Absent → a new one is generated (except on `/cycles`, where it is
  required). Malformed → `400 idempotencyKey_invalid`. The key used is echoed
  in every successful mutation answer as `idempotencyKey`. **Always send your
  own and store it**: a `502` can hide a call that was applied, and only the
  same key makes the retry safe.
- Successful bodies are the platform's own answer (its status code too), with
  the internal `processorConfigId` removed and `idempotencyKey` added.
- `environment` in answers is `"production"` or `"sandbox"`.

#### How refusals reach you

| Situation | Status | `type` / `code` | `message` |
| --- | --- | --- | --- |
| Your field fails a check above | `400` | `invalid_request` / the field code | ours |
| Platform refuses the request | `400` | `invalid_request` / `rejected` | the platform's |
| Feature not enabled on the account | `403` | `forbidden` / `not_enabled` | the platform's |
| No such plan or agreement in this mode | `404` | `not_found` / `not_found` | the platform's |
| State does not allow it | `409` | `conflict` / `conflict` | the platform's |
| Platform error (`5xx`), credentials refused, or a binding problem on our side | `502` | `server` / `upstream_error` | the platform's, or "The payment platform could not be reached. Try again later." |
| Platform unreachable, no answer within 20 s, or non-JSON answer | `502` | `server` / `upstream_unavailable` | "The subscription service is currently unavailable. Please try again or contact support." |
| Our deployment lacks the processor binding / platform credentials | `502` | `server` / `processor_unconfigured`, `credentials_unavailable` | same as above |
| Unexpected error on our side | `500` | `server` / `internal_error` | "An unexpected error occurred." |
| Subscriptions switched off on this platform | `503` | `server` / `subscriptions_disabled` | "Subscriptions are not enabled on this platform yet." |

Merchant mistakes that currently arrive as `502 upstream_error` (do not retry
these blindly): a plan re-created under the same `externalReference` with any
changed fact (`name` included) — message `subscription plan creation failed`;
a plan amount that is not a positive decimal, or `amount` on a variable plan /
`maximumAmount` on a fixed plan; a cancel key reused with a different
`atPeriodEnd` (`subscription cancel failed`); a contact key reused with a
different address (`subscription customer contact update failed`).

`400 rejected` messages that mean "account not set up — contact support":
`processor configuration is unavailable for this merchant` (that mode is not
set up), `the selected processor is unavailable for subscriptions` / `… for
subscription plans` / `… for subscription billing` (recurring billing not
enabled), `the selected processor does not support external-vault
subscriptions`.

### `POST /api/v1/subscription-plans` — create a plan

| Field | Type | Required | Rule |
| --- | --- | --- | --- |
| `externalReference` | string | yes | 1 – 255, no surrounding whitespace. Your plan id. |
| `name` | string | yes | 1 – 255. Shown to the customer. Cannot be changed later. |
| `amountMode` | string | yes | `"fixed"` or `"variable"`. |
| `amount` | string | fixed only | Positive decimal, ≤ 20 integer digits, ≤ 18 decimals. Forbidden on variable. |
| `maximumAmount` | string | variable only | Same format. The cap for every charge. Forbidden on fixed. |
| `currency` | string | yes | Send `"USD"` (the only currency an intent can carry). |
| `intervalUnit` | string | yes | `day`, `week`, `month`, `year`. |
| `intervalCount` | JSON integer | yes | 1 – 365. |
| `termsVersion` | string | yes | 1 – 64. Your label for the consent text. |
| `termsHash` | string | yes | 64 lowercase hex: SHA-256 (UTF-8) of the exact consent text. |
| `requiresCommerceOrder` | boolean | no | Default `false`. Physical-shipment plans; variable only; needs a feature not available through this API's intents — do not set it. |
| `idempotencyKey` | string | no | Echoed; has no effect here. |
| `mode` | string | no | See common rules. |

```bash
curl https://checkout.securepayapi.com/api/v1/subscription-plans \
  -H "Authorization: Bearer sp_secret_…" \
  -H "Content-Type: application/json" \
  -d '{ "externalReference": "gold-monthly", "name": "Gold membership",
        "amountMode": "fixed", "amount": "19.99", "currency": "USD",
        "intervalUnit": "month", "intervalCount": 1,
        "termsVersion": "2026-11-01",
        "termsHash": "5d48345db32747eed3f5666e43c946652760795f35d09d81c4e0f6f29c353ed3" }'
```

`200`:

```json
{
  "externalReference": "gold-monthly",
  "name": "Gold membership",
  "status": "active",
  "version": 1,
  "amountMode": "fixed",
  "amount": "19.99",
  "maximumAmount": null,
  "requiresCommerceOrder": false,
  "currency": "USD",
  "intervalUnit": "month",
  "intervalCount": 1,
  "termsVersion": "2026-11-01",
  "termsHash": "5d48345db32747eed3f5666e43c946652760795f35d09d81c4e0f6f29c353ed3",
  "created": true,
  "idempotencyKey": "6f1c2a0e-5b1d-4c0a-9d8e-3b2a1c0d9e8f"
}
```

- Idempotent on `externalReference`: the same facts again → `200`,
  `created: false`, the existing plan. Any changed fact → `502 upstream_error`.
  To change a plan, append a version.
- Amounts come back as the stored decimal; trailing zeros may differ.
- Errors: `400 rejected` with messages such as `amountMode is invalid`,
  `intervalCount is invalid`, `intervalUnit is invalid`, `currency is invalid`,
  `amount is invalid`, `maximumAmount is invalid`, `name is invalid`,
  `termsVersion is invalid`, `termsHash is invalid`,
  `requiresCommerceOrder must be a boolean`, `commerce-order subscription plans
  must use variable pricing`; the account messages above; `502` cases above.
- No webhook for plan creation.

Compute the hash from the exact text the customer will see:

```js
const { createHash } = require("node:crypto");
const termsHash = createHash("sha256").update(termsText, "utf8").digest("hex");
```

### `GET /api/v1/subscription-plans` — read plans

| Query | Rule |
| --- | --- |
| `externalReference` | ≤ 255. When present: one plan with `versions` (newest first, ≤ 100); other parameters ignored; unknown → `404`. |
| `status` | `active` or `archived` → else `400 status_invalid`. |
| `limit` | Integer 1 – 100 (default 25) → else `400 limit_invalid`. |
| `cursor` | 1 – 256 chars, the previous `nextCursor` → else `400 cursor_invalid`. |
| `mode` | See common rules. |

`200` (list):

```json
{
  "items": [
    {
      "externalReference": "gold-monthly",
      "environment": "production",
      "name": "Gold membership",
      "status": "active",
      "currentVersion": {
        "version": 2, "amountMode": "fixed", "amount": "24.99", "maximumAmount": null,
        "requiresCommerceOrder": false, "currency": "USD",
        "intervalUnit": "month", "intervalCount": 1,
        "termsVersion": "2026-12-01", "termsHash": "<64 hex>",
        "createdAt": "2026-11-12T10:00:00.000Z"
      },
      "createdAt": "2026-11-01T09:00:00.000Z",
      "updatedAt": "2026-11-12T10:00:00.000Z"
    }
  ],
  "nextCursor": null
}
```

Single read: the same plan object plus `"versions": [ <version object>, … ]`.

### `POST /api/v1/subscription-plans/versions` — change a plan

Body: `externalReference`, **`expectedVersion`** (required: the plan's
current `currentVersion.version` as you read it; JSON integer ≥ 1 →
otherwise `400 expectedVersion_required` / `expectedVersion_invalid`),
`amountMode`, `amount` | `maximumAmount`, `currency`, `intervalUnit`,
`intervalCount`, `termsVersion`, `termsHash`, `requiresCommerceOrder?`,
`idempotencyKey?`, `mode?`. `name` is not accepted.

```json
{ "externalReference": "gold-monthly", "expectedVersion": 1,
  "idempotencyKey": "0b6d1c62-4f0a-4a5e-9c1b-7a2d3e4f5061",
  "amountMode": "fixed", "amount": "24.99", "currency": "USD",
  "intervalUnit": "month", "intervalCount": 1,
  "termsVersion": "2026-12-01", "termsHash": "<sha256 of the new text>" }
```

`200`: the plan object with the new `currentVersion`, plus `created` and
`idempotencyKey`. Webhook `subscription.plan_version_created` on first
creation.

`409 conflict` messages: `subscription plan version idempotency key belongs to
different facts`, `subscription plan must be active to create a version`,
`subscription plan version changed; expected version N but found M` (re-read
and retry), `subscription plan version does not change any immutable facts`,
`subscription termsVersion already belongs to plan version N` (every version
needs a never-used `termsVersion`). `404` unknown plan.

Effects: existing agreements keep the version they consented to; new setups
must send the **current** version's `termsVersion` and `termsHash`. Intents
created before the change fail at payment — create new ones.

### `POST /api/v1/subscription-plans/archive` and `…/reactivate`

Body `{ "externalReference": "gold-monthly", "idempotencyKey": "<uuid>", "mode": "live" }`.

`200`:

```json
{ "externalReference": "gold-monthly", "environment": "production", "status": "archived",
  "effectiveAt": "2026-11-12T10:00:00.000Z", "created": true,
  "idempotencyKey": "<uuid>" }
```

- Archive: new setups on the plan are refused at payment (`subscription plan
  was not found`); no new versions; existing agreements keep billing.
- `409`: `subscription plan is already archived`, `subscription plan is
  already active`, `subscription plan status cannot transition`,
  `subscription plan idempotency key belongs to different facts`. `404`
  unknown plan. Any other action segment → `404 not_found` ("No such endpoint.").
- Webhooks `subscription.plan_archived` / `subscription.plan_reactivated` on
  first execution only.

### The subscription block

Put `subscription` on `POST /api/v1/payment-intents` to sell a plan
(**setup**) or to replace the card of a `past_due` agreement (**recovery**).

#### Setup fields (omit `operation`)

| Field | Type | Required | Rule at creation | Checked when the customer pays |
| --- | --- | --- | --- | --- |
| `planExternalReference` | string | yes | 1 – 255, no surrounding whitespace | Active plan of this account in the intent's `mode` |
| `shopperExternalReference` | string | yes | 1 – 255, no surrounding whitespace, no `@` | Your customer id; reused across agreements |
| `subscriptionExternalReference` | string | yes | 1 – 255, no surrounding whitespace | Your agreement id; never reuse one whose setup was captured |
| `termsVersion` | string | yes | 1 – 64, no surrounding whitespace | Equals the plan's current version |
| `termsHash` | string | yes | 64 lowercase hex | Equals the plan's current version |
| `termsText` | string | yes | 1 – 16,000 chars; SHA-256 (UTF-8) must equal `termsHash`. Shown to the customer verbatim; never sent to the platform | — |
| `billingAnchor` | string | yes | `YYYY-MM-DDTHH:MM:SS[.fraction]` followed by `Z` or `±HH:MM` (offset mandatory), a real date, ≥ 60 minutes after creation | Still in the future at card submit |
| `billingTimezone` | string | no | IANA name, 1 – 64; canonicalised; default `UTC` | Month/year periods are added in this zone |
| `recurringSurchargeConsent` | boolean | no | Only `false` accepted | — |

Plus on the intent itself: `currency` must equal the plan's; `amount` (cents)
must equal a **fixed** plan's `amount` exactly, or be > 0 and ≤ a
**variable** plan's `maximumAmount`. Not checked at creation.

`billingAnchor` is the date of the **first renewal**. The customer pays the
intent's amount now; the next charge is at the anchor, then every interval.

#### Recovery fields

```json
"subscription": {
  "operation": "recoverPaymentMethod",
  "subscriptionExternalReference": "membership-42",
  "termsVersion": "2026-11-01",
  "termsHash": "<the agreement's plan.termsHash>",
  "termsText": "<the text that hashes to it>"
}
```

Only these five (plus `recurringSurchargeConsent: false`) are allowed.
Conditions checked when the customer pays: agreement `past_due`, no
cancellation scheduled, newest cycle `retryable` or `failed`, no other
recovery in progress; intent `amount` and `currency` equal `recovery.amount`
/ `recovery.currency` from the agreement; `termsVersion` / `termsHash` equal
the agreement's `plan.termsVersion` / `plan.termsHash` (not the plan's newest
version). 3-D Secure is always required. The period is held for 2 hours
while the customer pays.

#### Creation errors (`400 invalid_request`, in check order)

`subscription_invalid` (not an object) · `subscription_consent_not_accepted_here`
(`consent` sent — consent is the customer's act) · `subscription_operation_invalid`
· `subscription_unknown_field` · `subscription_reference_invalid` ·
`subscription_terms_version_invalid` · `subscription_terms_hash_invalid` ·
`subscription_terms_text_invalid` · `subscription_terms_hash_mismatch` ·
`subscription_surcharge_consent_invalid` · `subscription_surcharge_consent_unsupported`
· (setup only) `subscription_plan_invalid` · `subscription_shopper_invalid` ·
`subscription_shopper_reference_pii` · `subscription_billing_anchor_invalid`
· `subscription_billing_anchor_too_soon` · `subscription_billing_timezone_invalid`.

#### What the widget does with it

- Shows a subscription badge, the amount, the billing start (setup only), the
  full `termsText` and a consent checkbox; the pay button stays disabled until
  it is ticked.
- Requires the customer's email (renewal notices and receipts go there).
- Card only: Apple Pay and Google Pay are not offered.
- Refusals shown to the customer (nothing charged, intent still payable):
  `400` "Recurring payments can only be set up with a card." · `400` "Please
  accept the subscription terms to continue." · `400` "An email address is
  required for a recurring payment." · `409` "The billing start date for this
  subscription has passed. Please ask the seller for a new payment link." (create
  a new intent with a later anchor) · the platform's own message for a plan,
  terms, amount, currency or reference mismatch (for example `subscription plan
  was not found`, `subscription terms changed before consent`, `subscription
  plan amount does not match payment`, `payment amount exceeds subscription
  maximum`, `subscription setup payment was already captured`).
- On success the widget reports
  `subscription: { "status": "pending_activation", "externalReference": "membership-42" }`.
  This is never "active".

### Activation

1. Card submit creates the agreement in `pending_setup` (before any charge).
2. The setup payment is captured.
3. The card network's authentication evidence arrives at the platform. Only
   3-D Secure **with liability shift** counts.
4. When 2 and 3 are both in, the agreement turns `active`: `startedAt` is
   set, `nextBillingAt` = `billingAnchor`, `paymentMethod.status` = `active`,
   an event `subscription_activated` appears in the timeline.

There is **no activation webhook**. After the intent is confirmed
`succeeded`, poll `GET /api/v1/subscriptions/{externalReference}` (for
example after 5 s, 30 s, 2 min) until `status` is `active`, then grant
access.

Dead end: captured without liability shift → the agreement stays
`pending_setup` forever and never bills. If it is still `pending_setup` a few
minutes after a `succeeded` intent: treat the setup as failed, cancel the
agreement (`POST /api/v1/subscriptions/cancel` ends a `pending_setup`
agreement at once), fulfil the paid period as a one-off or refund it, and
start a new setup under a **new** `subscriptionExternalReference`.

### `GET /api/v1/subscriptions` and `GET /api/v1/subscriptions/{externalReference}`

- Path form or `?externalReference=…`: one agreement with its timeline. A
  reference literally equal to `cycles`, `cancel`, `pause`, `resume` or
  `contact` can only be read with the query form. Percent-encode the path
  segment.
- Without a reference: `?status=pending_setup|active|paused|past_due|cancelled|completed`,
  `limit` 1 – 100 (default 25), `cursor` → `{ "items": [...], "nextCursor": "…" | null }`;
  items have every top-level field but no `cycles` and no `events`.
- `404 not_found` when no agreement of this account carries the reference in
  that mode.

`200` (one agreement):

```json
{
  "externalReference": "membership-42",
  "environment": "production",
  "status": "past_due",
  "cancelAtPeriodEnd": false,
  "billingAnchor": "2026-12-12T10:00:00.000Z",
  "billingTimezone": "Europe/Madrid",
  "nextBillingAt": "2026-12-12T10:00:00.000Z",
  "startedAt": "2026-11-12T10:01:30.000Z",
  "pausedAt": null,
  "cancelledAt": null,
  "endedAt": null,
  "createdAt": "2026-11-12T10:00:05.000Z",
  "updatedAt": "2026-12-12T10:01:10.000Z",
  "shopperExternalReference": "customer-42",
  "customerContact": { "configured": true, "updatedAt": "2026-11-12T10:00:05.000Z" },
  "plan": {
    "externalReference": "gold-monthly", "name": "Gold membership", "version": 1,
    "amountMode": "fixed", "amount": "19.99", "maximumAmount": null,
    "requiresCommerceOrder": false, "currency": "USD",
    "intervalUnit": "month", "intervalCount": 1,
    "termsVersion": "2026-11-01", "termsHash": "<64 hex>"
  },
  "paymentMethod": { "status": "active", "bin": "411111", "lastFour": "1111",
                     "country": "US", "activatedAt": "2026-11-12T10:01:30.000Z",
                     "recoveryInProgress": false },
  "recovery": { "eligible": true, "cycleStatus": "failed",
                "periodStart": "2026-12-12T10:00:00.000Z", "periodEnd": "2027-01-12T10:00:00.000Z",
                "amount": "19.99", "currency": "USD", "order": null,
                "attemptNumber": 1, "attemptStatus": "refused", "refusalCode": "5", "retryAt": null },
  "cycles": [
    { "periodStart": "2026-12-12T10:00:00.000Z", "periodEnd": "2027-01-12T10:00:00.000Z",
      "billingAt": "2026-12-12T10:00:00.000Z", "amount": "19.99", "currency": "USD",
      "status": "failed", "paid": false, "completedAt": "2026-12-12T10:01:10.000Z",
      "createdAt": "2026-12-12T10:01:00.000Z", "updatedAt": "2026-12-12T10:01:10.000Z",
      "attempts": [
        { "attemptNumber": 1, "kind": "…", "status": "refused", "paymentId": null,
          "provider": "…", "providerReference": "…", "refusalCode": "5", "error": "…",
          "retryAt": null, "submittedAt": "…", "completedAt": "…", "createdAt": "…", "updatedAt": "…" }
      ] }
  ],
  "events": [
    { "type": "renewal_past_due", "occurredAt": "2026-12-12T10:01:10.000Z",
      "data": { "attemptNumber": 1, "outcome": "refused", "refusalCode": "5",
                "nextRetryAt": null, "retryReason": "provider_decline_terminal" } }
  ]
}
```

Field rules:

- `status`: `pending_setup`, `active`, `paused`, `past_due`, `cancelled`,
  `completed` (no current flow produces `completed`; do not wait for it).
- `nextBillingAt`: `null` until activation; the start of the next unbilled
  period.
- `paymentMethod.status`: `pending`, `active`, `revoked`, `expired`.
- `recovery` describes the newest cycle and its newest attempt;
  `recovery.eligible` is `true` only when the agreement is `past_due`, no
  cancellation is scheduled, no recovery is in progress, and that cycle is
  `retryable` or `failed`.
- `cycles[]`: newest first, ≤ 100. Cycle `status`: `scheduled`, `processing`,
  `paid`, `retryable`, `failed`, `outcome_unknown`, `skipped`.
- `attempts[]`: newest first. Attempt `status`: `intent`, `submitting`,
  `submitted`, `authorised`, `refused`, `action_required`, `failed`,
  `outcome_unknown`, `reconciled` (= paid). `paymentId` is filled only for a
  card-replacement attempt; take a renewal's payment id from its webhook.
- `events[]`: newest first, ≤ 400. `type` uses internal names without the
  `subscription.` prefix and includes steps that have no webhook
  (`setup_pending`, `setup_payment_captured`, `subscription_activated`,
  `renewal_scheduled`, …). Never match webhook types against it.

### `POST /api/v1/subscriptions/cycles` — bill one variable period

| Field | Type | Required | Rule |
| --- | --- | --- | --- |
| `externalReference` | string | yes | The agreement. |
| `idempotencyKey` | string (UUID) | **yes** | Missing → `400 idempotencyKey_required`. Generate when you decide the amount, store, reuse on retry. |
| `amount` | string | yes (plain variable plan) | Exact decimal ≥ 0, ≤ 18 decimals, ≤ `maximumAmount`. Not a string → `400 amount_invalid`; malformed or missing → `400 rejected`. `"0"` skips the period. |
| `order` | object | no | Physical-shipment plans only; do not send. |
| `mode` | string | no | Common rules. |

```bash
curl https://checkout.securepayapi.com/api/v1/subscriptions/cycles \
  -H "Authorization: Bearer sp_secret_…" \
  -H "Content-Type: application/json" \
  -d '{ "externalReference": "usage-42", "amount": "12.34",
        "idempotencyKey": "6f1c2a0e-5b1d-4c0a-9d8e-3b2a1c0d9e8f" }'
```

`200`:

```json
{
  "externalReference": "usage-42",
  "environment": "production",
  "amount": "12.34",
  "currency": "USD",
  "periodStart": "2026-12-12T10:00:00.000Z",
  "periodEnd": "2027-01-12T10:00:00.000Z",
  "billingAt": "2026-12-12T10:00:00.000Z",
  "status": "scheduled",
  "created": true,
  "idempotencyKey": "6f1c2a0e-5b1d-4c0a-9d8e-3b2a1c0d9e8f"
}
```

- The call **does not charge**. It creates the cycle; the platform charges it
  within about a minute once the customer's upcoming-renewal notice has been
  sent. The result arrives by webhook.
- `"0"` → `status: "skipped"`, `nextBillingAt` advances one interval at once,
  webhook `subscription.renewal_skipped`, no charge.
- Same key + same facts → `200`, `created: false`, the cycle's current status.
- `409` messages: `subscription cycle idempotency key belongs to different
  facts`, `subscription is not a variable-price agreement` (fixed plan),
  `subscription is not active for variable-price billing` (paused, past_due,
  pending_setup, cancelled), `subscription is cancelled at the current period
  end`, `subscription credential is unavailable`, `subscription variable-price
  period is not due` (before `nextBillingAt`), `subscription amount exceeds the
  consented maximum`, `subscription period already has a billing cycle`,
  `subscription plan changed before cycle scheduling`, `subscription credential
  changed before cycle scheduling`. `404` unknown agreement.
- Not calling means nothing is billed: no charge, no event, no error;
  `nextBillingAt` stays in the past. Each later call bills the oldest unbilled
  period; one call per missed period.
- The amount of a created cycle cannot be changed.

### `POST /api/v1/subscriptions/pause`, `/resume`, `/cancel`

Body: `externalReference`, `idempotencyKey?`, `mode?`; `/cancel` also
`atPeriodEnd` (boolean, default `true`; not a boolean → `400 atPeriodEnd_invalid`).

`200`:

```json
{ "externalReference": "membership-42", "status": "active", "cancelAtPeriodEnd": true,
  "effectiveAt": "2026-12-12T10:00:00.000Z", "created": true,
  "idempotencyKey": "3f6a2b1c-9d8e-4f70-a1b2-c3d4e5f60718" }
```

All three are refused with `409` while a cycle is `processing` or
`outcome_unknown`, has an authorised attempt being resumed, or a card
replacement is in progress (`subscription has an in-flight or unknown payment
outcome`, `subscription has a payment-method recovery in progress`). Retry
later. A replay with the same key answers `created: false` and **sends the
webhook again**.

| Call | From | Result | Webhook |
| --- | --- | --- | --- |
| pause | `active`, `past_due` (already `paused` → `200`, stays paused) | `paused`; no charges, retries or notices; `nextBillingAt` unchanged. `409 subscription cannot be paused from its current state` otherwise. | `subscription.paused` |
| resume | `paused` only (`409 only a paused subscription can be resumed`) | `past_due` if any cycle is `scheduled`, `retryable` or `failed`, else `active`. Needs a usable card (`409 subscription payment credential is unavailable`). `nextBillingAt` unchanged: a date passed during the pause is due at once. | `subscription.resumed` |
| cancel, ends now | `atPeriodEnd: false`; or any unpaid cycle (`scheduled`, `retryable`, `failed`); or `nextBillingAt` null (e.g. `pending_setup`) or past | `cancelled`; the unpaid cycle becomes `skipped` (never charged); `effectiveAt` = that cycle's `periodStart` (may be in the past) or now | `subscription.cancelled` |
| cancel, scheduled | otherwise | status unchanged, `cancelAtPeriodEnd: true`, `effectiveAt` = `nextBillingAt`; no more renewals; `/cycles` → `409`. At `effectiveAt` the platform ends it. | `subscription.cancellation_scheduled`, later `subscription.cancelled` |

Other `409`s: `subscription cancellation is already effective`, `subscription
is already ended`. There is no call to undo a scheduled cancellation. Always
read `status` in the answer instead of assuming.

### `POST /api/v1/subscriptions/contact`

Body `{ "externalReference": "membership-42", "customerEmail": "buyer@example.com", "idempotencyKey": "<uuid>" }`.
`customerEmail`: non-empty, ≤ 254 chars (else `400 customerEmail_invalid`),
trimmed before sending; an address the platform rejects → `400 rejected`
(`customerEmail is invalid`).

`200`: `{ "externalReference": "membership-42", "customerEmail": "buyer@example.com", "status": "active", "created": true, "idempotencyKey": "<uuid>" }`.

No webhook. Old cancellation links in earlier e-mails stop working. A
renewal is charged only after an upcoming-renewal notice reached the
**current** address, and such a notice is produced only while the agreement
is `active`: changing the address of a `past_due` agreement can hold up its
scheduled retry.

### Renewals and retries (platform behaviour)

- Fixed plan: at `nextBillingAt` the platform creates the cycle (amount = the
  agreement's plan version `amount`) and charges it. Variable plan: only after
  your `/cycles` call.
- Before any charge, the customer must have been sent an upcoming-renewal
  e-mail for that date. Lead: 30 days (yearly, or ≥ 12-month plans), 7 days
  (monthly), 3 days (weekly), 12 hours (daily). If the anchor is closer than
  the lead, the notice goes out at once and the charge still happens on time.
- Paid → cycle `paid`, `nextBillingAt` = that cycle's `periodEnd` (not the
  payment date).
- Retries: only `refused`/`failed` attempts whose refusal is temporary
  (refusal codes 4, 9, 12, 21; or a Mastercard advice code asking for a
  retry). Delays 1 day, 3 days, 7 days after attempts 1, 2, 3 (or the advice
  code's delay); at most 4 attempts; never later than 30 days after the
  period start. `action_required` and unknown outcomes are never retried.
- After the last refusal the agreement stays `past_due` indefinitely; nothing
  is charged again until a card replacement succeeds or you cancel.

### Webhook events

Delivered to the account's webhook URL (dashboard), JSON, with the same
signature headers, retries and coalescing as transaction webhooks (see the
webhooks chapter). Not sent when no webhook URL is configured.

Common payload rules:

- Always `id`, `type`, `environment`, `occurredAt`, `merchantid`.
- `environment` is a **number**: `0` live (production), `1` sandbox.
- Agreement events carry `processorConfigId` (an opaque routing id; ignore
  it) and `subscriptionExternalReference`. Only lifecycle and
  `payment_method_*` events carry `status`.
- Two undelivered events with the same `(type, id)` are merged; newer fields
  win.
- **Renewal event ids repeat every period** (they hold the attempt number,
  not the period). Deduplicate on `id` + `paymentId` + `occurredAt`, never on
  `id` alone. `paymentId` may be `null` on a failed or unknown attempt.

| `type` | `id` form | Extra fields |
| --- | --- | --- |
| `subscription.paused`, `.resumed`, `.cancellation_scheduled`, `.cancelled` | `subscription:<env>:<processorConfigId>:<ref>:<idempotencyKey>:subscription_<paused\|resumed\|cancellation_scheduled\|cancelled>`; a cancellation the platform finalises at period end uses `<effectiveAt>` instead of the key | `status`, `effectiveAt`, `source` (`merchant` or `customer`; absent when the platform finalised a scheduled cancellation) |
| `subscription.renewal_paid`, `.renewal_recovered`, `.renewal_retry_scheduled`, `.renewal_past_due`, `.renewal_recovery_scheduled`, `.renewal_outcome_unknown` | `subscription:<env>:<processorConfigId>:<ref>:<attemptNumber>:<type>` | `attemptNumber`, `outcome`, `paymentId`, `nextRetryAt`; `refusalCode`, `retryReason` when produced by the billing run (absent when established from a processor event) |
| `subscription.renewal_skipped` | `subscription:<env>:<processorConfigId>:<ref>:<periodStart>:subscription.renewal_skipped` | `amount` (`"0"`), `currency`, `periodStart`, `periodEnd` |
| `subscription.payment_method_recovered` | `subscription:<env>:<processorConfigId>:<ref>:<paymentId>:payment_method_recovered` | `status` (`active` or `paused`), `paymentId` |
| `subscription.payment_method_recovery_failed` | `subscription:<env>:<processorConfigId>:<ref>:<paymentId>:payment_method_recovery_failed` | `status` (`past_due`), `paymentId`, `provider`, `providerReference`, `reason` |
| `subscription.plan_version_created` | `subscription-plan:<env>:<planRef>:<version>:version-created` | `planExternalReference`, `version` (no `processorConfigId`, no agreement ref) |
| `subscription.plan_archived`, `.plan_reactivated` | `subscription-plan:<env>:<planRef>:<idempotencyKey>:subscription.plan_<archived\|reactivated>` | `planExternalReference` |

Payload examples:

```json
{
  "id": "subscription:0:<processorConfigId>:membership-42:1:subscription.renewal_paid",
  "type": "subscription.renewal_paid",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "membership-42",
  "attemptNumber": 1,
  "outcome": "paid",
  "paymentId": "sub_6b0e2f4c1a9d48e7b3c5f1a2d4e6b8c0",
  "refusalCode": null,
  "nextRetryAt": null,
  "retryReason": "outcome_not_retryable",
  "occurredAt": "2026-12-12T10:01:10.000Z",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription:0:<processorConfigId>:membership-42:1:subscription.renewal_retry_scheduled",
  "type": "subscription.renewal_retry_scheduled",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "membership-42",
  "attemptNumber": 1,
  "outcome": "refused",
  "paymentId": "sub_6b0e2f4c1a9d48e7b3c5f1a2d4e6b8c0",
  "refusalCode": "12",
  "nextRetryAt": "2026-12-13T10:01:10.000Z",
  "retryReason": "transient_refusal_12",
  "occurredAt": "2026-12-12T10:01:10.000Z",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription:0:<processorConfigId>:membership-42:<idempotencyKey>:subscription_cancellation_scheduled",
  "type": "subscription.cancellation_scheduled",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "membership-42",
  "status": "active",
  "effectiveAt": "2026-12-12T10:00:00.000Z",
  "occurredAt": "2026-11-20T09:00:00.000Z",
  "source": "merchant",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription:0:<processorConfigId>:usage-42:2026-12-12T10:00:00.000Z:subscription.renewal_skipped",
  "type": "subscription.renewal_skipped",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "usage-42",
  "amount": "0",
  "currency": "USD",
  "periodStart": "2026-12-12T10:00:00.000Z",
  "periodEnd": "2027-01-12T10:00:00.000Z",
  "occurredAt": "2026-12-12T10:05:00.000Z",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription:0:<processorConfigId>:membership-42:<paymentId>:payment_method_recovered",
  "type": "subscription.payment_method_recovered",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "membership-42",
  "status": "active",
  "paymentId": "<payment reference of the recovery payment>",
  "occurredAt": "2026-12-20T15:00:00.000Z",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription:0:<processorConfigId>:membership-42:<paymentId>:payment_method_recovery_failed",
  "type": "subscription.payment_method_recovery_failed",
  "environment": 0,
  "processorConfigId": "<processorConfigId>",
  "subscriptionExternalReference": "membership-42",
  "status": "past_due",
  "paymentId": "<payment reference>",
  "provider": "<provider>",
  "providerReference": "<provider reference>",
  "reason": "provider_authorization_refused",
  "occurredAt": "2026-12-20T15:00:00.000Z",
  "merchantid": "<your platform merchant id>"
}
```

```json
{
  "id": "subscription-plan:0:gold-monthly:2:version-created",
  "type": "subscription.plan_version_created",
  "environment": 0,
  "planExternalReference": "gold-monthly",
  "version": 2,
  "occurredAt": "2026-11-12T10:00:00.000Z",
  "merchantid": "<your platform merchant id>"
}
```

#### Decision table per event

| Event | `outcome` | Do |
| --- | --- | --- |
| `renewal_paid` | `paid` | Extend access one period. Read `cycles[0]` for amount and dates (not in the event). |
| `renewal_recovered` | `paid` | Restore access. |
| `renewal_retry_scheduled` | `refused` / `failed` | Agreement `past_due`; a retry is due at `nextRetryAt`. Grace is your choice. Send nothing. |
| `renewal_past_due` | `refused` / `failed` / `action_required` | No more retries. Restrict access; send the customer to a card-replacement checkout (recovery intent) or cancel. |
| `renewal_past_due` | `outcome_unknown` | Money may have moved. Do not ask for payment, do not cancel (it answers `409`). Wait for a later renewal event or poll the agreement. |
| `renewal_outcome_unknown` | `outcome_unknown` | Same as above; automatic retry is off for this cycle. |
| `renewal_recovery_scheduled` | `recovery_scheduled` | Informational; the same authorization is being captured. Wait for `renewal_paid` / `renewal_recovered`. |
| `renewal_skipped` | — | Record the zero period. |
| `payment_method_recovered` | — | Restore access; the overdue period is paid with the new card. No `renewal_recovered` follows. |
| `payment_method_recovery_failed` | — | The cycle is `failed` again; the customer may try another card with a new recovery intent. |
| `paused` | — | Stop expecting renewals. |
| `resumed` | — | Read the agreement; `past_due` means a period is outstanding. |
| `cancellation_scheduled` | — | Keep access until `effectiveAt`. |
| `cancelled` | — | End access at `effectiveAt`. |
| `plan_*` | — | Refresh your plan cache. |

No webhook exists for: agreement creation, **activation**, plan creation,
contact change, a positive `/cycles` submission, an abandoned or expired card
replacement, and an attempt the platform itself marks unknown or paid while
recovering an interrupted billing run. Read the agreement for those.

### Fixed vs variable

| | Fixed | Variable |
| --- | --- | --- |
| Plan carries | `amount` | `maximumAmount` |
| Setup payment (intent `amount`) | Must equal `amount` | > 0 and ≤ `maximumAmount` |
| Who creates each renewal | The platform, at `nextBillingAt` | You, with `/cycles`, once `nextBillingAt` has passed |
| Renewal amount | Plan `amount` of the agreement's version | What you send; `"0"` skips |
| If you do nothing | Renewals continue | Nothing is charged, no event; periods do not advance |
| Trial / intro price | No field. Charge the full price and choose `billingAnchor` | Small setup amount, then full amounts via `/cycles` |
| `$0` setup | Impossible | Impossible (the setup amount must be > 0) |

#### Timeline — fixed plan, $19.99 monthly (`intervalUnit: "month"`, `intervalCount: 1`)

| Day | Platform | You receive / do |
| --- | --- | --- |
| D0 | Intent `amount: 1999`, `billingAnchor` = D30. Customer pays; agreement `pending_setup`. | Confirm the intent (`succeeded`). |
| D0 + minutes | Capture and liability-shifted authentication recorded → `active`, `nextBillingAt` = D30. | No webhook. Poll the agreement until `active`; grant access. |
| D23 | Upcoming-renewal e-mail to the customer. | — |
| D30 | Cycle D30→D60 created and charged; paid → `nextBillingAt` = D60. | `subscription.renewal_paid` (attempt 1, `paymentId` `sub_…`). Extend access. |
| D60 | Refused, code `12` → cycle `retryable`, agreement `past_due`, retry D61. | `renewal_retry_scheduled` (`nextRetryAt` D61, `retryReason` `transient_refusal_12`). |
| D61 | Attempt 2 refused `12` → retry D64. | `renewal_retry_scheduled` (attempt 2). |
| D64 | Attempt 3 paid → `active`, `nextBillingAt` = D90 (period end). | `subscription.renewal_recovered`. |
| D90 | Refused, code `5` (not retryable) → cycle `failed`, `past_due`. | `renewal_past_due` (`outcome: "refused"`, `retryReason: "provider_decline_terminal"`). Read the agreement: `recovery.eligible: true`, `recovery.amount: "19.99"`. Create a recovery intent for `1999` and send the customer to it. |
| D95 | Customer pays with a new card (3-D Secure, liability shift) → cycle D90→D120 `paid`, card swapped, `active`, `nextBillingAt` = D120. | `subscription.payment_method_recovered` only. |
| D100 | `POST …/pause` → `paused`. | `subscription.paused`. |
| D120 | Nothing charged (paused). | — |
| D125 | `POST …/resume` → `active`; `nextBillingAt` D120 is overdue → notice sent at once, D120→D150 charged on the next run. | `subscription.resumed`, then `renewal_paid`. |
| D130 | `POST …/cancel` `atPeriodEnd: true` → `cancelAtPeriodEnd: true`, `effectiveAt` D150. | `subscription.cancellation_scheduled`. Keep access until D150. |
| D150 | Platform ends it: `cancelled`, `endedAt` D150, no charge. | `subscription.cancelled` (no `source`). End access. |

If nothing is done after D90, the agreement stays `past_due` with no further
charge and no further event.

#### Timeline — variable plan, $1 intro then usage up to $99 monthly

Plan: `amountMode: "variable"`, `maximumAmount: "99.00"`, monthly.

| Day | Platform | You receive / do |
| --- | --- | --- |
| D0 | Intent `amount: 100` with `billingAnchor` = D14. Paid. | Confirm; poll until `active`; `nextBillingAt` = D14. |
| D7 | Upcoming-renewal e-mail. | — |
| D14 | Period due; **the platform does nothing by itself**. | `POST …/cycles` `{amount:"99.00", idempotencyKey}` at or after D14 (earlier → `409 … not due`). Answer `status: "scheduled"`, period D14→D44. |
| D14 + ≤ 1 min | Charged; paid → `nextBillingAt` = D44. | `renewal_paid`. |
| D44 | You post `"42.10"`; refused code `12`. | `renewal_retry_scheduled`; retries D45, D48, D55; if attempt 4 also fails: `renewal_past_due` (`retryReason: "attempt_limit_reached"`). |
| D45 | Attempt 2 paid → `active`, `nextBillingAt` = D74. | `renewal_recovered`. |
| D74 | You post `"30.00"`; refused code `5` → `failed`, `past_due`. | `renewal_past_due`. `recovery.amount` = `"30.00"` → recovery intent `amount: 3000`. |
| D76 | New card pays 30.00 → `active`, `nextBillingAt` = D104. | `payment_method_recovered`. |
| D104 | You post `"0"` → cycle `skipped`, `nextBillingAt` = D134, no charge. | `renewal_skipped`. |
| D110 | `pause` → `paused`. `/cycles` now `409 subscription is not active for variable-price billing`. | `subscription.paused`. |
| D140 | `resume` → `active`; D134 is overdue. | `subscription.resumed`. Post the D134 period's amount; it is charged once the immediate notice is sent. |
| D150 | `cancel` `atPeriodEnd: true`; D134 cycle paid → scheduled for D164. `/cycles` → `409 subscription is cancelled at the current period end`. | `cancellation_scheduled`. |
| D164 | Ended. | `subscription.cancelled`. |

Variants: never posting at D14 → the agreement stays `active` with
`nextBillingAt` D14 and nothing happens; posting on D20 bills D14→D44, the
next post is accepted from D44. Cancelling with `atPeriodEnd: true` while a
posted cycle is unpaid, or while `nextBillingAt` is past → ends at once, the
cycle becomes `skipped` (never charged).

### Dead ends and what to do

| Situation | Cause | Do |
| --- | --- | --- |
| Intent `succeeded`, agreement stuck `pending_setup` | No liability shift on the setup's 3-D Secure | Cancel the agreement, refund or keep the period as a one-off, new setup with a new reference. |
| Widget: "The billing start date … has passed" | `billingAnchor` passed while the intent waited | New intent with a later anchor. |
| Widget: `subscription plan was not found` | Plan unknown, archived, or created in the other `mode` | Fix the plan or the intent's `mode`; new intent. |
| Widget: `subscription terms changed before consent` | A new plan version exists | New intent with the current `termsVersion`/`termsHash`/`termsText`. |
| Widget: `subscription setup payment was already captured` | `subscriptionExternalReference` reused | New reference. |
| `past_due` after `renewal_past_due` | Terminal decline or retries exhausted | Recovery intent for exactly `recovery.amount`, or cancel. Nothing else will charge. |
| `past_due` with newest cycle `outcome_unknown` | Charge result unknown | Do not charge, do not cancel; wait for an event or poll. |
| `/cycles` `409 … not due` | Called before `nextBillingAt` | Call at or after `nextBillingAt`. |
| `/cycles` `409 … already has a billing cycle` with a new key | Retried under a new key | Reuse the original key; read the agreement. |
| Pause/cancel `409 … in-flight or unknown payment outcome` | A charge is running or unknown | Retry later. |
| Variable agreement never billed | No `/cycles` calls | Post one call per missed period (or `"0"`). |
| `502 upstream_error` on plan create | Changed facts under an existing `externalReference`, or a bad amount | Check the request; use `/versions` to change a plan. |
| `503 subscriptions_disabled` | Feature off on the platform | Contact support; do not retry. |
| `400 rejected` `processor configuration is unavailable for this merchant` | That `mode` is not set up for the account | Contact support. |


---

## JavaScript SDK

Load the SDK from `https://checkout.securepayapi.com/sdk/v1/securepay.js`. It
defines one global, `SecurePay`. It creates an iframe served from the same
origin as the script, passes the client secret to it over `postMessage`, and
turns the widget's messages into callbacks, DOM events and promises. Card data
never reaches the merchant page.

Before mounting, the merchant's server creates a Payment Intent with its secret
key and hands the page the intent's `client_secret`. After any browser success,
the server confirms with `GET /api/v1/payment-intents/{id}` before fulfilling.
The browser's word is never proof of payment.

```html
<script src="https://checkout.securepayapi.com/sdk/v1/securepay.js"></script>
<div id="pay"></div>
<script>
  var sp = SecurePay('sp_client_…');
  var handle = sp.mount('#pay', {
    clientSecret: 'pi_…_secret_…',
    onReady:   function ()  {},
    onActive:  function (active) { /* true while a sheet or 3-D Secure is open */ },
    onSuccess: function (r) { /* r.intentId → your server confirms */ },
    onError:   function (e) { /* show e.message */ }
  });
</script>
```

### `SecurePay(publishableKey)`

- Pass the publishable key (`sp_client_…`). Works with or without `new`.
- Throws `Error("SecurePay: a publishable key is required")` when the key is
  missing or not a string.
- The key is checked only when the iframe loads. An unknown key, or an account
  with no registered domain, makes the iframe answer **404**: no `ready`, no
  `onReady`, no `onError`, nothing. Treat a widget that never calls `onReady`
  as a wiring problem (key, domain), never as a decline.

### `mount(target, options)`

`target` is a CSS selector or a DOM element. Returns a handle.

Synchronous throws:

| Condition | Error message |
| --- | --- |
| target not found | `SecurePay: mount target not found` |
| `clientSecret` missing or empty | `SecurePay: opts.clientSecret is required` |

The SDK appends an iframe to the target: `src` =
`https://checkout.securepayapi.com/embed?pk=<key>`, `title="Secure payment"`,
`allow="payment"` (set before attaching; a cross-origin frame cannot open a
wallet sheet without it), width 100%, no border, initial height 320 px. It then
resizes the iframe on every `resize` message to `max(80, height)` px.

#### Options

| Option | Type | Default | Behaviour |
| --- | --- | --- | --- |
| `clientSecret` | string | required | The intent's `client_secret`. Sent to the frame by `postMessage`, never in the URL. |
| `theme` | `'light'` \| `'dark'` | the intent's `theme` | Overrides the intent's theme for this page. Any other value is ignored. |
| `email` | boolean | `true` | Only `false` hides the email field (no receipt email is collected). Ignored for a subscription intent, where the field is always shown and required. |
| `submitMode` | `'internal'` \| `'external'` | `'internal'` | Only the exact string `'external'` hides the widget's pay button; you start the payment with `handle.submit()`. |
| `wallets` | boolean | `false` | Only `true` opts in to Apple Pay / Google Pay in external mode. Ignored in internal mode, where wallets are always offered where the device supports them. |
| `onWalletAuthorize` | function | capture | `({ method, reference }) => boolean \| Promise<boolean>`. Called in external mode with `wallets: true` after the shopper approved in the wallet sheet, **before any charge**. Exactly `true` captures; anything else aborts with nothing moved. See [Wallets under an external submit](#wallets-under-an-external-submit). |
| `onReady` | function | — | Called each time the frame posts `ready` and the SDK has answered with `init`. The intent is fetched **after** this, so an `onError` can still follow. |
| `onActive` | function | — | Called with `true` / `false` when a payment becomes active / ends. Called only on a change. Exceptions thrown inside it are swallowed. |
| `onSuccess` | function | — | Called with the success payload. |
| `onError` | function | — | Called with the error payload, including refusals of `submit()`. |
| `mode` | string | — | Legacy. Does **not** select live or sandbox. Any value logs `console.warn`. The exact value `'sandbox'` makes the widget refuse a live intent with `mode_mismatch`. Set `mode` when the server creates the intent instead. |

### The handle

| Method | Returns | Behaviour |
| --- | --- | --- |
| `submit()` | Promise | Starts a card payment. Meant for `submitMode: 'external'` (the widget does not refuse it in internal mode, but there it competes with the widget's own button). Rejects at once with `SecurePay: the payment form is not ready yet` before the frame posted `ready`. Otherwise it settles **exactly once**, on the `success` or `error` that echoes its id, with **no timeout**: a 3-D Secure challenge can take up to 15 minutes. |
| `validate()` | Promise | Asks whether the shopper still has something to do in the form. Starts nothing and sends nothing to the processor. See [`validate()`](#validate). |
| `setWalletsEnabled(enabled)` | — | External mode with `wallets: true`: `false` holds the wallet buttons (dimmed, with a "Complete your details above to pay with …" hint), `true` releases them. Coerced to a boolean. Safe before `onReady`: the last value is delivered right after `init`. |
| `destroy()` | — | Removes the message listener and the iframe. Rejects every pending `submit()` and `validate()` with `SecurePay: the widget was destroyed`. A later `submit()` / `validate()` rejects with `SecurePay: the payment form is not ready yet`. Does not call `onActive(false)`. |

A mounted widget takes its intent **once**. To pay another intent, call
`destroy()` and `mount()` again, but only while no payment is active.

#### `submit()` resolution

- Resolves with the success payload (`status: "succeeded"` or `"pending"`),
  `submitId` included.
- Rejects with an `Error` whose `message` is the widget's message (fallback
  `Payment failed`), with `.code` when the payload has a code, and `.payload`
  holding the full error payload.
- `onSuccess` / `onError` and the DOM events fire as well.
- A wallet payment never settles a `submit()`. It carries no `submitId`.
  Handle it through `onSuccess` / `onError`.

Refusals. The promise rejects with one of these messages, checked in this order.
None has a `code` or a `method`:

| Message | When |
| --- | --- |
| `The payment form is not ready yet.` | the intent is still loading |
| the widget's unavailable reason | the widget refused to load: `This payment session has expired.`, the `mode_mismatch` text, the origin text, or the load error (`intent not found`, `Service unavailable`, …) |
| `A payment is already in progress.` | a previous `submit()` has not been answered |
| `This payment is already complete.` | this widget already completed a card or wallet payment |
| `This payment is being confirmed.` | an earlier attempt on this intent ended `pending` (remembered in the browser for up to one hour) |
| `A payment is already in progress.` | a payment started from the widget's own button, or a wallet sheet, is running |
| `Please enter a valid email address.` | the email field is shown and is empty, malformed or longer than 254 characters |
| `Please complete the card details.` | cardholder, number, expiry or CVC is empty |
| `Please accept the subscription terms to continue.` | subscription setup with the consent box unticked |

The last three are also shown inline in the frame. Show `e.message` as it is.

#### `validate()`

```js
placeOrder.onclick = function () {
  handle.validate()
    .then(createOrder)                                // form is complete
    .then(function () { return handle.submit(); })
    .then(function (r) { return confirmOnServer(r.intentId); })
    .catch(function (e) { show(e.message); });
};
```

- Rejects with `SecurePay: the payment form is not ready yet` before `ready`.
- Rejects with the refusal message only when the shopper can fix it in the form:
  `Please enter a valid email address.`, `Please complete the card details.`,
  `Please accept the subscription terms to continue.`, or
  `The payment form is not ready yet.` while the intent is still loading. A
  rejection without a message uses `The payment form is not complete`.
- Resolves `true` for every other state, including an intent already paid,
  being confirmed, in progress or unavailable. These are payment states, and
  your server learns them when it reads the intent. `submit()` still refuses
  them.
- Resolves `true` if the frame does not answer within **3 seconds**. A check
  never blocks a checkout.
- Feature-detect it on older integrations:
  `typeof handle.validate === 'function'`.

### Callbacks and DOM events

Each message the SDK handles calls the callback (if given) and dispatches a
`CustomEvent` on `window`. The payload is in `event.detail`:

| Widget message | Callback | DOM event | `onActive` |
| --- | --- | --- | --- |
| `ready` | `onReady()` | — | — |
| `payment_started` | — | `securepay:payment_started` | `true` |
| `processing` | — | `securepay:processing` | — |
| `wallet_authorized` | `onWalletAuthorize(...)` | `securepay:wallet_authorized` | — |
| `payment_ended` | — | `securepay:payment_ended` | `false` |
| `success` | `onSuccess(payload)` | `securepay:success` | `false` |
| `error` | `onError(payload)` | `securepay:error` | `false` |

The SDK accepts messages only from its own origin and its own iframe's window.

#### Success payload

```json
{
  "intentId": "k3m9…",
  "status": "succeeded",
  "reference": "LU494ZZ07K7814E3",
  "submitId": "s1"
}
```

| Field | Present | Meaning |
| --- | --- | --- |
| `intentId` | always | The intent id. Send it to your server, which confirms by `GET`. Compare it with the id your server stored for the order. |
| `status` | always | `"succeeded"`: captured. `"pending"`: accepted, outcome not settled. **Do not ask for money again.** Show "being confirmed" and let the server read the intent. |
| `reference` | when known | Transaction reference. For a card it is the processor reference. For a wallet it is the wallet payment's reference. |
| `subscription` | subscription intents | `{ "status": "pending_activation", "externalReference": "…" }`. Never `active`: the platform activates the agreement later. |
| `submitId` | card payment started by `submit()` | The id of the `submit()` it answers. |

#### Error payload

```json
{ "message": "Your card was declined. Please try another card.", "method": "card", "submitId": "s2" }
```

| Field | Present | Meaning |
| --- | --- | --- |
| `message` | always | Human-readable. Show it. Do not parse it. |
| `code` | load refusals only | `origin_not_allowed`, `mode_mismatch`, `intent_not_payable`. Declines and refusals have no code. |
| `method` | payment failures | `card`, `applepay`, `googlepay` |
| `reference` | declined wallet attempt, when known | The wallet payment's reference |
| `submitId` | answers a `submit()` | The id of that `submit()` |

Load errors (sent before any payment):

| `code` | `message` | Cause | Fix |
| --- | --- | --- | --- |
| `origin_not_allowed` | `not authorised for <origin>` | page origin not on a registered domain (or port), or not HTTPS | register the exact host (with port if non-standard) |
| `mode_mismatch` | `widget requested sandbox but the intent is live` | `mount({ mode: 'sandbox' })` on a live intent | create the intent with `mode: 'sandbox'`, drop `mode` from `mount` |
| `intent_not_payable` | `This payment session has expired.` | intent expired, already succeeded, or already consumed by a charge whose outcome is open | read the intent on the server before creating a new one |
| — | `intent not found` | client secret unknown (mistyped, other account) | pass the right `client_secret` |
| — | `Service unavailable`, `Forbidden`, other | server or network failure | retry the mount later |

### Lifecycle: the active window

A payment is **active** from `payment_started` until `payment_ended`, `success`
or `error` (SDK: `onActive(true)` … `onActive(false)`). During that window a
wallet sheet or a 3-D Secure challenge is open inside the iframe.

- Do not call `destroy()`, re-create the iframe, mount a new client secret or
  navigate while active. The sheet or challenge dies with the frame. The
  prepared wallet payment is left at INIT with no provider, or a challenge is
  abandoned.
- Queue cart edits that would create a new intent until `onActive(false)`.
- After `payment_ended` with `cancelled` or `failed`, keep the widget mounted.
  The form is still there and the shopper can retry.

```js
var active = false, queued = null;
var handle = sp.mount('#pay', {
  clientSecret: cs,
  onActive: function (a) { active = a; if (!a && queued) { var q = queued; queued = null; q(); } }
});
function onCartChanged() {
  if (active) { queued = onCartChanged; return; }
  remountWithNewIntent();
}
```

### External submit

Use `submitMode: 'external'` when the store's own "Place order" button must be
the only button:

```js
var widget = sp.mount('#pay', { clientSecret: cs, submitMode: 'external' });
placeOrder.onclick = function () {
  widget.submit()
    .then(function (r) { return confirmOnServer(r.intentId); })   // r.status may be "pending"
    .catch(function (e) { show(e.message); });                    // keep the shopper on the page
};
```

- One `submit()` per click. A second `submit()` while one is pending rejects
  with `A payment is already in progress.`.
- Enter pressed inside the frame never starts a payment in external mode.
- Wallets are hidden in external mode unless you pass `wallets: true`.

### Wallets under an external submit

A wallet payment starts when the shopper taps the wallet button inside the
frame, not your button, so it answers no `submit()`. Opt in only if you handle
it:

```js
var widget = sp.mount('#pay', {
  clientSecret: cs,
  submitMode: 'external',
  wallets: true,
  onWalletAuthorize: function (info) {      // { method: 'applepay'|'googlepay', reference }
    // Shopper approved; NOTHING charged yet. Create the pending order, then:
    return createPendingOrder(info.reference).then(function () { return true; });
  },
  onSuccess: function (r) { confirmOnServer(r.intentId).then(finishOrder); },
  onError:   function (e) { show(e.message); }          // e.method names the wallet
});
widget.setWalletsEnabled(requiredFieldsComplete());     // buttons start held
```

- In this mode the buttons start **held** until `setWalletsEnabled(true)`. Call
  it again with `false` when a required field is cleared.
- `onWalletAuthorize` may return a value or a promise. Exactly `true` sends
  `wallet_capture`. `false`, `undefined`, any other value, a rejection or a
  throw sends `wallet_abort`. The message of a rejection or throw is shown in
  the frame (first 300 characters).
- Budget: **18 s for Apple Pay** (Apple allows about 30 s from approval to
  completion, and authorisation plus capture must fit in the rest), **30 s for
  Google Pay**. No answer in time is an abort.
- An abort (or timeout) charges nothing. It posts
  `payment_ended { outcome: "cancelled" }` and no `error`. The frame shows your
  message, or `The store did not confirm the order in time. Nothing was charged
  — please try again.` when there is none. Cancel or reuse the order you
  created.
- After `true`, the attempt ends with `success` (`succeeded` or `pending`), or
  with `payment_ended { outcome: "failed" }` and then `error { method,
  reference? }`.
- Without `onWalletAuthorize` an opted-in host captures at once and learns of
  the payment only through `onSuccess`.

### Domains

The widget accepts `init` only from a page whose origin passes all of these
checks:

- Scheme `https`. The only exception is hostname `localhost`.
- Host, **including a non-default port**, equals a registered base host or is a
  subdomain of one. Registered hosts are the account's website domain plus
  extra domains whitelisted for the account.
- A registered `www.example.com` is normalised to `example.com`, so the apex and
  every subdomain pass. A host registered as `shop.example.com` allows only
  that subtree.
- A registered `localhost` does **not** allow `localhost:3000`. Register
  `localhost:3000`.

Any other origin gets `error { code: "origin_not_allowed" }`, and the frame
shows `This payment widget isn't authorised for <origin>. It must be embedded on
one of the merchant's registered domains (<hosts> — or a subdomain of one).`

---

## Embedded widget protocol

Use this only when you cannot load the SDK. The SDK speaks exactly this
protocol.

### Iframe

```html
<iframe src="https://checkout.securepayapi.com/embed?pk=sp_client_…"
        title="Secure payment" allow="payment"
        style="width:100%;border:0;height:320px"></iframe>
```

- `pk` is the publishable key. An unknown key, or an account with no
  registered domain, returns **404**, and the frame then posts nothing.
- Set `allow="payment"` before the iframe is attached. A frame without it
  cannot open a wallet sheet, and the failure is silent.
- Never put the client secret in the URL.

### Envelope

Every message in both directions:

```json
{ "source": "securepay", "type": "<name>", "payload": { } }
```

- Ignore messages whose `source` is not `"securepay"`.
- On the page, accept only `event.origin === "https://checkout.securepayapi.com"`
  and `event.source === iframe.contentWindow`.
- Post to the widget with target origin `"https://checkout.securepayapi.com"`,
  never `"*"`.

### Page → widget

#### `init`

Send it in answer to `ready`:

```json
{
  "source": "securepay",
  "type": "init",
  "payload": {
    "publishableKey": "sp_client_…",
    "clientSecret": "pi_…_secret_…",
    "loc": "https://shop.example.com/checkout",
    "submitMode": "external",
    "theme": "dark",
    "collectEmail": true,
    "wallets": false
  }
}
```

| Field | Type | Required | Rule |
| --- | --- | --- | --- |
| `clientSecret` | string | yes | Non-empty. An `init` without it is ignored (the widget keeps waiting). The first accepted `init` wins, and every later `init` is ignored. |
| `loc` | string | yes in practice | `location.href` of the **top** page. Required for the 3-D Secure frame to be allowed inside your page and for Apple Pay validation. Without it the widget uses its own URL and the challenge frame is refused. |
| `publishableKey` | string | no | Informational. The account comes from the iframe's `pk`. |
| `submitMode` | string | no | `"external"` hides the pay button. Anything else means internal. |
| `theme` | string | no | `"light"` or `"dark"`. Overrides the intent's theme. |
| `collectEmail` | boolean | no | Only `false` hides the email field. Ignored for subscription intents. |
| `wallets` | boolean | no | Only `true` opts in to wallets. In external mode the buttons then start held until `set_wallets { enabled: true }`, and each wallet attempt is gated by `wallet_authorized`. |
| `mode` | string | no | Legacy guard. `"sandbox"` makes the widget refuse a live intent (`mode_mismatch`). It never selects the environment. |

After an accepted `init` the widget pins your exact origin. Every later command
must come from that origin, and every outbound message targets it.

#### `submit`

```json
{ "source": "securepay", "type": "submit", "payload": { "id": "order-123-try-1" } }
```

- Accepted only from the pinned origin. A missing, empty or non-string `id`
  is ignored, with no answer.
- Answered by exactly one `success` or `error` carrying `submitId: "<id>"`.
  Refusals (see the table in [`submit()` resolution](#submit-resolution)) come
  back as `error { submitId, message }` at once.

#### `validate`

```json
{ "source": "securepay", "type": "validate", "payload": { "id": "check-1" } }
```

Same origin and `id` rules as `submit`. Answered at once by `validated`. Starts
nothing.

#### `set_wallets`

```json
{ "source": "securepay", "type": "set_wallets", "payload": { "enabled": true } }
```

Only `enabled === true` releases the buttons. Anything else holds them. Pinned
origin only.

#### `wallet_capture` / `wallet_abort`

```json
{ "source": "securepay", "type": "wallet_capture", "payload": { "id": "w…" } }
{ "source": "securepay", "type": "wallet_abort",   "payload": { "id": "w…", "message": "Please fill in your address." } }
```

These answer a `wallet_authorized` with the same `id`. They are accepted only
from the pinned origin. An unknown, already answered or timed-out `id` is
ignored. `message` is optional, is shown in the frame and is cut to 300
characters.

### Widget → page

| `type` | `payload` | Meaning |
| --- | --- | --- |
| `ready` | — | Frame loaded. Answer with `init`. Posted with target `*` (no secret). Posted again if the frame reloads. |
| `resize` | `{ "height": 512 }` | Set `iframe.style.height = Math.max(80, height) + 'px'`. |
| `payment_started` | `{ "method": "card" }` or `{ "method": "applepay", "reference": "…" }` | A payment is now **active**. The card flow left the form, or a wallet sheet opened. |
| `processing` | `{ "method", "stage", "reference"? }` | Progress while active. Informational. Apple Pay stages: `validated`, `authorizing`, `authorized`. Google Pay stages: `authorizing`, `authenticating`. Card: the shopper-visible status text, so treat it as opaque. |
| `wallet_authorized` | `{ "id", "method", "reference" }` | External mode with `wallets: true` only. The shopper approved and **nothing is charged**. Answer with `wallet_capture` / `wallet_abort` within 18 s (Apple Pay) or 30 s (Google Pay). Silence is an abort. |
| `payment_ended` | `{ "method", "outcome", "reference"? }` | The active payment ended without a capture. `outcome`: `cancelled` (nothing follows), `failed` (an `error` follows), `pending` (wallet only, a `success` with `status: "pending"` follows). |
| `success` | `{ "intentId", "status", "reference"?, "subscription"?, "submitId"? }` | Captured (`succeeded`) or accepted with the outcome open (`pending`). |
| `error` | `{ "message", "code"?, "method"?, "reference"?, "submitId"? }` | Load refusal, command refusal or failed payment. |
| `validated` | `{ "id", "ok": true }` or `{ "id", "ok": false, "message" }` | The answer to `validate`. |

`ready`, `resize` and `origin_not_allowed` errors go to target `*` until an
`init` is accepted. After that, messages go only to the pinned origin.

### Active-window rule

From `payment_started` until `payment_ended`, `success` or `error`, do not
remove or re-create the iframe, send a new client secret or navigate. A wallet
sheet or a 3-D Secure challenge lives inside the frame and dies with it.

### Timing of `init`

Send `init` as soon as `ready` arrives. If no `init` with a client secret is
accepted within **8 s** of the frame loading, the frame shows blank. A valid
`init` that arrives later still loads it.

### Load sequence

1. Frame posts `ready`. You post `init`.
2. The widget checks the origin. On failure it posts `error origin_not_allowed`
   and stops.
3. The widget fetches the intent. If the fetch fails it posts
   `error { message }` with no code. If `mode: "sandbox"` was sent but the
   intent is live, it posts `error mode_mismatch`. If the intent is not payable,
   it posts `error intent_not_payable`.
4. Otherwise it shows the amount and the form. A sandbox intent shows the badge
   `Test mode — sandbox`. If this browser remembers a `pending` outcome for this
   intent (up to one hour), it shows "Payment is being confirmed" with the
   reference instead of the form, and `submit` is refused with
   `This payment is being confirmed.`.

---

## 3-D Secure and wallets in the widget

### Card with 3-D Secure

The whole card flow runs inside the iframe. The shopper is never redirected.
The intent reads `requires_payment` during card entry, device-data collection,
authentication and an open challenge. It moves to `processing` only when the
charge is sent, then to `succeeded`, `failed`, or stays `processing` when the
outcome is open.

What the page observes: `payment_started { method: "card" }` → several
`processing { method: "card", stage }` → `success` or
`payment_ended { outcome: "failed" }` + `error`. A card attempt whose outcome is
open ends with `success { status: "pending" }` alone, with no `payment_ended`.

#### Timings

| Limit | Value | Result |
| --- | --- | --- |
| From the start of the payment until a challenge appears or the payment completes | 120 s | `error`: `Payment timed out. Please try again.` |
| Open challenge not answered | 15 min | `error`: `The authentication step timed out. Please try again.` |
| Confirmation after the challenge | polled every 2 s, up to 5 min | `error`: `Your payment is still being confirmed. Please try again in a moment.` (no charge was sent) |
| Authentication answer "pending" | retried up to 5 times, 2 s apart | then `error` with the same message |
| Challenge outcome read while the challenge is open | every 3 s | — |
| Wallet requests (each call) | 30 s | wallet outcome `pending` after approval, `failed` before |
| `submit()` | none | settles on the payment's real outcome |
| `validate()` | 3 s | resolves `true` |

Authentication failure messages: `Your card could not be authenticated. Please
try another card.`, `Your card was declined. Please try another card.`, `This
payment attempt was not approved. Please try again.`. A card that authenticates
without liability shift is declined.

The challenge iframe is 100% wide and up to `min(100vh, 700px)` high. Honour
`resize`.

### Apple Pay

- Offered where `ApplePaySession` supports version 3 and `canMakePayments()` is
  true. It is not offered for subscription intents, for amount 0, or in
  external mode without `wallets: true`. The embedding page's domain must be
  registered for Apple Pay on the account. The SDK sets `allow="payment"`.
- Messages: `payment_started` (sheet opened, `reference`) →
  `processing validated` → `processing authorizing` → [`wallet_authorized` in
  gated mode] → `processing authorized` → `success`.
- No 3-D Secure challenge is shown for Apple Pay.
- When the authorisation answer is uncertain, the widget does **not** capture
  and reports `pending`. The intent then still reads `requires_payment`. Do not
  ask for money again. Check the transaction or the dashboard.

### Google Pay

- Offered only where Apple Pay is not, and Google reports the device ready.
  The same exclusions apply as for Apple Pay.
- Messages: `payment_started` → `processing authorizing` →
  [`wallet_authorized` in gated mode] → `processing authenticating` (3-D Secure
  or capture) → `success`.
- A dismissed sheet, a sheet that could not open, or a sheet that returned no
  token goes back to the button: `payment_ended { outcome: "cancelled" }`.
- Pending fallback message shown in the frame: `Payment status could not be
  confirmed at <stage>. Do not submit another payment.`.

#### Known defect: Google Pay redirect 3-D Secure

When the bank answers a Google Pay payment with a **redirect** challenge, the
charge is completed by the platform's own return page, not by the widget's
capture. Consequences:

- The money can be taken while the intent stays `requires_payment`.
- The page may receive no `success` or `error`. The last message can be
  `processing { stage: "authenticating" }`, and `onActive` may stay `true`.

Reconcile: for an intent that stays `requires_payment` after the shopper
approved a wallet payment, call
`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`
(or check the dashboard) **before** asking for another payment. Use the
`reference` from `payment_started` / `wallet_authorized` /
`processing`, or the intent's `transaction_reference`.

### Outcome table

| Widget result | Intent (server `GET`) | Do |
| --- | --- | --- |
| `success { status: "succeeded" }` | `succeeded` | Fulfil after checking amount, currency, mode. |
| `success { status: "pending" }` | `processing` | Do not fulfil and do not ask for money. Poll the intent. Hold the order. |
| `success { status: "pending" }` (wallet) | `requires_payment` | Do not ask for money. Check the transaction or dashboard. |
| `error`, card declined at charge | `failed` | Let the shopper retry in the same widget. |
| `error`, 3-D Secure failed or timed out | `requires_payment` | Let the shopper retry. |
| `payment_ended cancelled` | `requires_payment` | Nothing charged. Keep the widget mounted. |
| `payment_ended failed` + `error` (wallet) | `requires_payment` | Nothing charged. Retry or pay by card. |
| no terminal message after wallet approval | `requires_payment` | Check the transaction (Google Pay redirect defect). |
| any | `processing` | Never treat as paid, never as unpaid. |

`last_attempt` on the intent describes a wallet decline or cancel only after the
widget prepares the next wallet attempt. Do not rely on it being present.

---

## Sandbox and testing

### Environment

- Live versus sandbox is decided by `mode` when the server creates the intent
  (`"live"` default, `"sandbox"`). The browser cannot change it.
- `mount({ mode: 'sandbox' })` / `init.mode: "sandbox"` is only a guard. On a
  live intent the widget refuses with `mode_mismatch`. On a sandbox intent it
  changes nothing. Omitting it on a sandbox intent still runs a test payment.
- The widget shows `Test mode — sandbox` above the form whenever the intent is
  sandbox. The badge follows the intent only.
- On the server, check `mode` when you confirm the intent. A sandbox intent
  must never fulfil a live order.

### Test cards

Use them in sandbox only. Cardholder **Jonathan Suit** (required), any future
expiry `MM/YY` (e.g. `03/30`), CVC `737`.

| Card number | Behaviour |
| --- | --- |
| `4111 1111 1111 1111` | Approves straight through |
| `5201 2815 0512 9736` | Frictionless 3-D Secure |
| `4212 3456 7891 0006` | Forces a 3-D Secure challenge |
| `4917 6100 0000 0000` | 3-D Secure without liability shift: declined |

CVC `736` simulates a rejected card. Test data lives in the processor. If a
card behaves differently, trust the observed result and report it.

### Checklist

- Server creates the intent (`mode: "sandbox"` while testing), stores its `id`,
  and returns only `client_secret` to the page.
- The widget reaches `onReady` and shows the form on your domain. A wrong key
  shows nothing (404). A wrong host or port gives `origin_not_allowed`.
- `success { status: "succeeded" }` leads to a server `GET` that checks
  `status`, `amount`, `currency`, `mode` and the stored `id`.
- `success { status: "pending" }` never leads to a second payment request.
- A decline at the charge leaves the intent `failed`. A 3-D Secure failure or
  abandonment leaves it `requires_payment`. The shopper can retry in the same
  widget.
- `onActive` / `payment_started` holds remounts and intent changes until the
  window closes.
- External submit: a second `submit()` while one is pending rejects with
  `A payment is already in progress.`. `validate()` rejects on an empty card
  form, so no order is created.
- Wallets with `onWalletAuthorize`: returning anything but `true`, or answering
  late, gives `payment_ended cancelled` with nothing charged, and your order is
  cleaned up.
- Reconciliation covers an intent left `requires_payment` after a wallet
  approval (Google Pay redirect defect).
- Subscription intent: terms and checkbox shown, email required, no wallets,
  and `success.subscription.status === "pending_activation"`.


---

## Webhooks

The payment platform posts a signed JSON request to the merchant's server when a
transaction changes. Build the receiver from this section; do not assume
anything that is not stated here.

A webhook describes a **transaction** (one payment attempt), not a Payment
Intent:

- `id` is the transaction reference. For a widget payment it is the intent's
  `transaction_reference`. A new attempt on the same intent (for example after a
  wallet decline) gets a **new** reference, so one intent can produce webhooks
  for several transactions.
- `externalid` (same value as `externalReference`) is the intent's `externalid`,
  or the intent `id` when none was set. On a hosted product page it is the
  product id, which is not unique per order.

Confirm a payment synchronously with `GET /api/v1/payment-intents/{id}`. Use
webhooks for everything after it: settlement, refunds, disputes, payouts.

### Configure the endpoint

The merchant sets the URL in the dashboard: Developer → Webhook. There is no
API for it.

The URL must satisfy all of these, or every delivery to it is dropped:

- absolute, at most 2048 characters, scheme `https`;
- no username or password, no `#fragment`;
- port absent or `443`;
- hostname contains a dot, or is a public IP address;
- hostname does not end in `localhost`, `.local`, `.internal` or `.home.arpa`,
  and is not a private or reserved IP address;
- not one of the platform's own domains or a subdomain of one;
- at delivery time the hostname resolves **only** to public addresses;
- valid TLS certificate, TLS 1.2 or newer.

A query string is kept and sent with every request.

The dashboard form checks only that the value is an absolute `http` or `https`
URL of at most 2048 characters. A URL that breaks the other rules can be saved,
but each delivery to it is then dropped without a request and without retries.
Tell the merchant to use an `https` URL that meets every rule.

Signing secret:

- generated when an endpoint's URL is first saved or changed, or on request
  ("New secret"): 64 lowercase hexadecimal characters, shown **once** in the
  dashboard, never retrievable later;
- saving an unchanged URL keeps the secret; when a new one is issued the old
  secret stops working at once, and deliveries still queued or retrying are
  signed with the new secret;
- store it as a server-side secret; it is not the API secret key.

Other rules:

- There is a primary endpoint and, optionally, one additional endpoint. Both
  receive every event; each has its own secret, independent of the other's.
- The primary URL can be changed in the dashboard but not removed.
- An endpoint's URL and secret serve live and sandbox payments; split them on `env`.
- Webhooks are available only once the merchant account is activated.
- While no URL is set, nothing is queued, and nothing is sent later for those
  payments.

### The request

```http
POST <path and query of the webhook URL> HTTP/1.1
Host: <merchant host>
Content-Type: application/json
Accept: application/json
Content-Length: <byte length of the body>
User-Agent: SecurePayAPI-Webhook/1.0
X-Signature: <64 lowercase hexadecimal characters>
X-Timestamp: <unix time in seconds, an integer>

<body>
```

- Always `POST` to port 443. These six headers are the only ones sent.
- The body is compact UTF-8 JSON.
- Redirects are not followed; a `3xx` answer is a failed attempt.
- Requests currently come from `157.230.218.195`. The address can change;
  authenticate with the signature, never with the source IP alone.

### Verify the signature

```
X-Signature = hex( HMAC-SHA256( key = signing secret, message = X-Timestamp + raw body ) )
```

`X-Timestamp` is the decimal string from the header and the body is the exact
bytes received. Both headers are recomputed on every attempt, so a retry
carries a new timestamp and a new signature. There is no prefix and no key id.
The platform enforces no time window; enforce your own.

```js
import crypto from 'node:crypto';

/**
 * rawBody: Buffer holding the exact bytes received.
 * Never JSON.parse and re-stringify before verifying: that changes the bytes.
 */
export function verifySecurePayWebhook(headers, rawBody, secret, toleranceSeconds = 300) {
  const ts = String(headers['x-timestamp'] ?? '');
  const sig = String(headers['x-signature'] ?? '');
  if (!/^\d{1,12}$/.test(ts) || !/^[0-9a-f]{64}$/.test(sig)) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(ts + rawBody.toString('utf8'))
    .digest('hex');

  const authentic = crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expected, 'hex'));
  const fresh = Math.abs(Date.now() / 1000 - Number(ts)) <= toleranceSeconds;
  return authentic && fresh;
}
```

With Express, mount `express.raw({ type: 'application/json' })` on the webhook
route so `req.body` is the raw `Buffer`. Reject an unverifiable request with a
non-`2xx` status and do not act on it.

### Two kinds of payload

Both kinds arrive at the same URL with the same headers, signature and delivery
rules. Tell them apart first:

| Kind | Recognise it by |
| --- | --- |
| Transaction | **no `type` field**; has `status`, `statustext`, `statushistory` |
| Subscription event | a string `type` starting with `subscription.`; its `id` is an event id, not a transaction reference |

### Transaction payload

There is **no event id and no event type**: the payload is the transaction's
current state. A field whose value is not known yet is absent; this is normal
for payments in progress. Treat every field as optional except `id`, `status`,
`statustext`, `statushistory` and `env`.

| Field | Type | Present | Meaning |
| --- | --- | --- | --- |
| `created` | number or string | always | Creation time: epoch **milliseconds** (number) on payments in progress and on the first `PAID`; may be an ISO-8601 string on finished transactions. Do not rely on it; read `created` (unix seconds) from the transactions API. |
| `id` | string | always | Transaction reference. New ones are `LU` + 14 characters `[0-9A-Z]`; older ones match `[A-Za-z0-9_-]{8,64}`. Store in a 64-character column. |
| `famt` | number | once known | Amount in the payment currency, major units (`49.99`). |
| `currency` | string | once known | Payment currency. |
| `env` | number | always | `0` live, `1` sandbox. |
| `sent` | number or null | once payout data exists | Amount paid out to the merchant. |
| `delivery` | number or null | once known | Payout method: `0` crypto direct, `1` crypto swap, `2` wire, `3` ACH. |
| `paymenttype` | number | always | `0` none, `1` e-commerce, `2` POS, `3` wire, `4` ACH. Not the card scheme. |
| `paymenttypetext` | string | always | Key of `paymenttype`: `NONE`, `ECOM`, `POS`, `WIRE`, `ACH`. Branch on the number. |
| `payment_channel` | number | always | `0` unknown, `1` ecommerce, `2` pos, `3` bank, `4` blockchain. |
| `funding_method` | number | always | `0` unknown, `1` card, `2` ach, `3` wire, `4` usdc, `5` paypal. Apple Pay and Google Pay are `1`. |
| `payment_channel_text` | string | always | `unknown`, `ecommerce`, `pos`, `bank`, `blockchain`. Treat any other value as `unknown`. |
| `funding_method_text` | string | always | `unknown`, `card`, `ach`, `wire`, `usdc`, `paypal`. Treat any other value as `unknown`. |
| `deliverystatus` | number or null | always | Payout status (table below). |
| `deliverystatustext` | string or null | always | Key of `deliverystatus` (`DELIVERYPENDING`); `null` when `deliverystatus` is `null`. Branch on the number. |
| `externalReference` | string or null | when set | The merchant's reference (for widget payments: the intent `externalid`, else the intent `id`). |
| `externalid` | string or null | when set | Same value as `externalReference`. |
| `customerid` | string or null | sometimes | Legacy field. Ignore it. |
| `status` | number | always | Transaction status code (table below). |
| `statustext` | string | always | The status **key** (`PAID`, `CHARGEBACKOPEN`), not the human label the transactions API returns (`Paid`). Branch on `status`. |
| `statushistory` | array of `{status: number, statustext: string}` | always | Normally exactly **one** entry: the current status. More entries only when newer statuses were merged into a delivery that had not gone out; oldest first; the same status may repeat. |
| `merchantid` | string | merchant payments | The merchant id. |
| `invoice` | string | when paid against an invoice | Invoice id (UUID). |
| `order` | `{id: string, version: number}` | when paid for a platform order | |
| `hash` | string or null | crypto payouts only | Payout transaction hash. |
| `chain` | number | crypto payouts only | Chain id. |
| `nonce` | number or null | crypto payouts only | |
| `output_currency` | string | crypto payouts only | Payout token, e.g. `USDC`. |
| `three_ds_status` | string | when recorded | 3-D Secure result. Store and show; do not branch on specific values. |
| `liability_shift_status` | string | when recorded | Liability-shift result. Store and show; do not branch on specific values. |
| `three_ds_eci` | string | when recorded | ECI value. |
| `refund_reason` | string | once a refund was requested | 1–160 characters. |
| `refund_request_source` | string | once a refund was requested | `merchant_api`, `admin` or `automatic_fraud`. |
| `refund_requested_at` | string or number | once a refund was requested | Parse defensively (ISO string or epoch number). |
| `refunded_presentment_amount` | string (decimal) | usually on finished transactions | Confirmed **partial**-refund total in the payment currency. Absent = `"0"`. |
| `pending_refund_presentment_amount` | string (decimal) | usually on finished transactions | Submitted, unconfirmed partial-refund total. Absent = `"0"`. |
| `partial_refund_count` | number | usually on finished transactions | Absent = `0`. |
| `customer_card_surcharge` | object | only when a card surcharge applied | Surcharge quote, amounts and refund split; leaf values are strings or `null`. |

Never in the payload: an event id or type, a card number, BIN, cardholder name
or e-mail, the decline reason, a dispute id, reason code or deadline, a refund
id, a processor reference, USD or fee amounts. Read the transactions API or the
dashboard for those.

#### Example — paid card payment

Values in all three examples are illustrative.

```json
{
  "created": 1789123456789,
  "id": "LUZH24T2E65K3NN4",
  "famt": 49.99,
  "currency": "USD",
  "env": 0,
  "delivery": 2,
  "paymenttype": 1,
  "paymenttypetext": "ECOM",
  "payment_channel": 1,
  "funding_method": 1,
  "payment_channel_text": "ecommerce",
  "funding_method_text": "card",
  "deliverystatus": 1,
  "deliverystatustext": "DELIVERYPENDING",
  "externalReference": "ORDER-42",
  "externalid": "ORDER-42",
  "customerid": null,
  "status": 1,
  "statustext": "PAID",
  "statushistory": [{ "status": 1, "statustext": "PAID" }],
  "merchantid": "7TTR77ZC",
  "three_ds_status": "authenticated",
  "liability_shift_status": "shifted",
  "three_ds_eci": "05"
}
```

#### Example — full refund confirmed

```json
{
  "created": "2026-09-11T10:04:16.789Z",
  "id": "LUZH24T2E65K3NN4",
  "famt": 49.99,
  "currency": "USD",
  "env": 0,
  "sent": 48.24,
  "delivery": 2,
  "paymenttype": 1,
  "paymenttypetext": "ECOM",
  "payment_channel": 1,
  "funding_method": 1,
  "payment_channel_text": "ecommerce",
  "funding_method_text": "card",
  "deliverystatus": 5,
  "deliverystatustext": "DELIVERED",
  "externalReference": "ORDER-42",
  "externalid": "ORDER-42",
  "customerid": null,
  "status": 9,
  "statustext": "REFUNDED",
  "statushistory": [{ "status": 9, "statustext": "REFUNDED" }],
  "merchantid": "7TTR77ZC",
  "three_ds_status": "authenticated",
  "liability_shift_status": "shifted",
  "three_ds_eci": "05",
  "refund_reason": "customer_request",
  "refund_request_source": "merchant_api",
  "refund_requested_at": "2026-09-14T08:00:00.000Z",
  "refunded_presentment_amount": "0",
  "pending_refund_presentment_amount": "0",
  "partial_refund_count": 0
}
```

Recognise a full refund by `status: 9`. Do not infer it from the three refund
totals: they track partial refunds.

#### Example — chargeback opened

```json
{
  "created": "2026-09-11T10:04:16.789Z",
  "id": "LUZH24T2E65K3NN4",
  "famt": 49.99,
  "currency": "USD",
  "env": 0,
  "sent": 48.24,
  "delivery": 2,
  "paymenttype": 1,
  "paymenttypetext": "ECOM",
  "payment_channel": 1,
  "funding_method": 1,
  "payment_channel_text": "ecommerce",
  "funding_method_text": "card",
  "deliverystatus": 5,
  "deliverystatustext": "DELIVERED",
  "externalReference": "ORDER-42",
  "externalid": "ORDER-42",
  "customerid": null,
  "status": 24,
  "statustext": "CHARGEBACKOPEN",
  "statushistory": [{ "status": 24, "statustext": "CHARGEBACKOPEN" }],
  "merchantid": "7TTR77ZC",
  "three_ds_status": "authenticated",
  "liability_shift_status": "shifted",
  "three_ds_eci": "05",
  "refunded_presentment_amount": "0",
  "pending_refund_presentment_amount": "0",
  "partial_refund_count": 0
}
```

A dispute webhook is the ordinary transaction payload with a dispute status and
nothing else about the dispute. The reason and the defense options are in the
dashboard (see Disputes below).

### Transaction status codes

The integer `status` in webhooks and in the transactions API. Webhooks name it
with the key; the transactions API returns the label. There is no code 17 or 18.

| Code | Key | Label in the transactions API | Meaning | Usually followed by |
| --- | --- | --- | --- | --- |
| 10 | `INIT` | Payment Init | Payment opened | further in-progress statuses |
| 11 | `DDC` | Payment DDC | Device data being collected | further in-progress statuses |
| 12 | `AUTH3DS` | Payment 3DS | Authenticating, or a wallet authorizing | further in-progress statuses |
| 13 | `AUTH3DSCHALLENGE` | Payment 3DS Challenge | Issuer challenge required | further in-progress statuses |
| 14 | `AUTH3DSCHALLENGEFORM` | Payment 3DS Form | Challenge form open | further in-progress statuses |
| 15 | `AUTH3DSRESULT` | Payment 3DS Result | Authorized, ready for capture | 16, 3 |
| 16 | `PAYING` | Payment Processing | Capture sent, outcome unknown. Neither paid nor failed; never charge again | 1, 3 |
| 1 | `PAID` | Paid | **Captured** | 20, 34, 9, 21–33 |
| 20 | `SETTLED` | Settled | Captured and settled | 34, 9, 21–33 |
| 3 | `FAILED` | the decline reason, or `Failed` | Declined or failed; this attempt is over | nothing |
| 34 | `REFUNDPENDING` | Refund Pending | Full refund requested, not yet confirmed. **Never sent as a webhook** | 9 |
| 9 | `REFUNDED` | Refunded | Fully refunded: one full refund, or partial refunds adding up to the captured amount | a dispute status can still follow |
| 21 | `INFORMATIONREQUESTED` | Information Requested | Issuer asked for information | any dispute status |
| 22 | `INFORMATIONRESPONDED` | Information Responded | Information supplied | any dispute status |
| 23 | `INFORMATIONEXPIRED` | Information Expired | Information request expired | any dispute status |
| 24 | `CHARGEBACKOPEN` | Chargeback Open | Chargeback open; amount held | any dispute status |
| 25 | `CHARGEBACKREVERSED` | Chargeback Reversed | Resolved for the merchant | any dispute status |
| 26 | `CHARGEBACKWON` | Chargeback Won | Resolved for the merchant | any dispute status |
| 27 | `CHARGEBACKLOST` | Chargeback Lost | Lost or accepted | any dispute status |
| 28 | `PREARBITRATIONOPEN` | Prearbitration Open | Pre-arbitration open; amount held | any dispute status |
| 29 | `PREARBITRATIONWON` | Prearbitration Won | Pre-arbitration won | any dispute status |
| 30 | `PREARBITRATIONLOST` | Prearbitration Lost | Pre-arbitration lost or accepted | any dispute status |
| 31 | `SCHEMEARBITRATIONOPEN` | Scheme Arbitration Open | Scheme arbitration open; amount held | any dispute status |
| 32 | `SCHEMEARBITRATIONWON` | Scheme Arbitration Won | Scheme arbitration won | — |
| 33 | `SCHEMEARBITRATIONLOST` | Scheme Arbitration Lost | Scheme arbitration lost | — |
| 0 | `UNPAID` | Unpaid | Defined; no payment flow sets it. Treat as not paid | — |
| 5 | `CANCELED` | Canceled | Defined; no payment flow sets it. Treat as not paid | — |
| 35 | `OPERATIONAL` | Operational Transfer | Internal transfer, not a payment. Ignore | — |
| 2, 4, 6, 7, 8, 19 | `DELIVERED`, `DELIVERING`, `DELIVERYPENDING`, `DELIVERYUNKNOWN`, `FROZEN`, `SETTLEMENTPENDING` | `Unknown: <code>` | Unused legacy codes the platform refuses to set. On an old record, read the transaction and escalate; do not guess | — |

The last column lists the usual paths. Do not hard-code it as a strict state
machine: accept any captured-family status after `PAID`, and any dispute status
after any other.

Groupings to code against:

| Group | Codes |
| --- | --- |
| Payment in progress | 10, 11, 12, 13, 14, 15, 16 |
| End of the payment attempt | 1 (`PAID`), 3 (`FAILED`) |
| Captured at some point | 1, 20, 34, 9, 21–33 |
| `chargeback: true` in the transactions API | 24–33 (not 21–23) |
| Amount held; a refund is refused | 24, 27, 28, 30, 31, 33 |

`PAID` ends the payment attempt, not the transaction. Settlement, refunds and
disputes follow it, and a dispute can arrive even after `REFUNDED`.

#### Payout status

`deliverystatus` describes the payout to the merchant, independently of
`status`:

| Code | Key (webhook) | Label (transactions API) |
| --- | --- | --- |
| 0 | `NONE` | None |
| 1 | `DELIVERYPENDING` | Delivery Pending |
| 2 | `DELIVERING` | Delivering |
| 3 | `FAILED` | Failed |
| 4 | `DELIVERYUNKNOWN` | Unknown if failed or succeeded |
| 5 | `DELIVERED` | Delivered |
| 6 | `FROZEN` | Frozen |
| 7 | `REFUNDED` | Refunded |
| null | null | Not Set |

### What triggers a webhook

A webhook is queued when a transaction's `status` changes, and also when its
payout status changes while `status` stays the same.

| What happened | `status` received | Notes |
| --- | --- | --- |
| Payment opened (card, Apple Pay, Google Pay) | 10 `INIT` | |
| Device-data collection page served | 11 `DDC` | |
| 3-D Secure authentication started | 12 `AUTH3DS` | |
| Issuer challenge required | 13 `AUTH3DSCHALLENGE` | |
| Challenge form opened | 14 `AUTH3DSCHALLENGEFORM` | |
| Authorization complete, ready for capture | 15 `AUTH3DSRESULT` | |
| 3-D Secure failed, or any failure before or at capture | 3 `FAILED` | |
| Capture submitted | 16 `PAYING` | Outcome not known yet. |
| Capture succeeded | 1 `PAID` | `deliverystatus` `1` in live; in sandbox a simulated payout follows at once (`deliverystatus` `5`). |
| Delayed capture completed (authorized earlier, captured on shipment) | 1 `PAID` | |
| USDC invoice paid | the transaction's current status | |
| Processor settlement recorded | 20 `SETTLED` | Only when the status actually changes. |
| Payout status changed | **the same `status`**, new `deliverystatus` | |
| Full refund accepted, nothing paid out yet (always in sandbox) | 9 `REFUNDED` | Right after the refund request. |
| Full refund accepted after the payout (live) | **nothing** | Moves to 34 `REFUNDPENDING` silently. |
| Processor confirms the full refund | 9 `REFUNDED` | |
| Partial refund confirmed | the same `status`, or 9 `REFUNDED` once confirmed partial refunds equal the captured amount | Refund totals change. |
| Partial refund failed or reversed by the processor | the same `status` | Refund totals change. |
| Dispute notification that changes the status | the dispute status, 21–33 | |
| Platform operators correct a status by hand | that status | |
| Subscription lifecycle, renewal and plan events | an event payload (`type: "subscription.*"`) | See Subscription events. |

Dispute notification → status: request for information → 21 (22 if answered,
23 if expired); information supplied → 22; chargeback notification or
chargeback → 24 (27 if lost or accepted); second chargeback → 27; chargeback
reversed → 25 (26 if won); pre-arbitration opened or declined → 28;
pre-arbitration accepted or lost → 30; pre-arbitration won → 29; scheme
arbitration → 31, won → 32, lost → 33; defense period ended → 27; issuer
response time-frame expired → 26.

#### What is not sent

- **The pending state of a full refund.** No webhook carries `status: 34`.
  Either `REFUNDED` arrives, or nothing arrives until the processor confirms.
  Read the transaction to see the pending state.
- Dispute notifications that do not change the status: repeated notifications,
  issuer comments, fraud notifications.
- Separate "refund created", "dispute created", "payout" or "settlement"
  events. They do not exist; everything is the transaction payload.
- Anything at all while no webhook URL is configured. Nothing is replayed when a
  URL is added later.

### Delivery rules

| Rule | Value |
| --- | --- |
| Success | any HTTP status 200–299 |
| Response body | content ignored; more than 64 KiB makes the attempt fail |
| Deadline per attempt | 10 s in total, including DNS and TLS; 5 s without data on the socket |
| Failure | any other status, a redirect, a timeout, an oversized response, a TLS error, a host that does not resolve or resolves to a non-public address |
| Attempts | 15 in total; after the 15th failure the delivery is abandoned and never resent automatically |
| Wait after failed attempt | 1st and 2nd: 5 s · 3rd: 10 s · 4th: 30 s · 5th: 60 s · 6th: 10 min · 7th and 8th: 30 min · 9th to 14th: 60 min — about 7 h 12 min in total |
| Timing | waits are minimums; the queue is scanned about once a second, and a delivery is not necessarily sent the instant the change happens |
| Restarts | the queue survives platform restarts |
| Ordering | not guaranteed between separate deliveries |

Answer `2xx` as soon as the payload is stored durably; process afterwards.

#### Merging

While a delivery for a transaction is still waiting — not yet sent, or waiting
for a retry — a newer payload for the same transaction (same environment) is
**merged into it** instead of being queued separately:

- every field takes the newer value;
- `statushistory` becomes the old entries followed by the new ones.

**A merged status inherits the attempt count and the next-retry time of the
delivery it joined.** It does not restart the schedule:

- if the endpoint has been failing, a new status — even `PAID` — waits for that
  delivery's next retry, up to 60 minutes;
- if that delivery then fails its last attempt, the new status is lost with it.

A payload that arrives while a delivery for the same transaction is being sent
at that instant becomes a separate delivery. The same status can therefore
arrive twice, and two deliveries for one transaction can complete in either
order.

**Never rely on webhooks alone.** Run a reconciliation job (below).

#### Deliveries dropped without retries

- No webhook URL configured: nothing is queued.
- At send time the URL was removed, the secret is missing, or the URL breaks
  the rules in "Configure the endpoint": the delivery is dropped at once — no
  request, no retries.

A URL that passes the rules but resolves to a non-public address fails each
attempt and goes through the normal 15 attempts.

### Handler

The handler must survive all of the following, because all of them happen:

- there is no event id to deduplicate on;
- the same status arrives more than once (payout changes, partial refunds,
  concurrent deliveries);
- an older payload arrives after a newer one;
- one request carries several statuses in `statushistory`;
- one order can have several transactions (one per attempt), including a
  declined one before a paid one, and — rarely — two captured ones;
- statuses keep arriving **after** `PAID`: settlement, refunds, disputes;
- a status arrives late, or never.

```js
import express from 'express';
import { verifySecurePayWebhook } from './verify.js';

const app = express();

const IN_FLIGHT = new Set([10, 11, 12, 13, 14, 15, 16]);
// Captured at some point: paid, settled, refund pending, refunded, disputes.
const CAPTURED = new Set([1, 20, 34, 9, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]);

app.post('/webhooks/securepay', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!verifySecurePayWebhook(req.headers, req.body, process.env.SECUREPAY_WEBHOOK_SECRET)) {
    return res.status(401).end();               // non-2xx: the platform retries
  }
  const payload = JSON.parse(req.body.toString('utf8'));
  await inbox.enqueue(payload);                 // store durably BEFORE answering
  res.status(204).end();                        // well inside 10 seconds
});

// Worker: safe to run any number of times for the same payload.
async function handle(payload) {
  if (typeof payload.type === 'string') return handleSubscriptionEvent(payload);
  if (typeof payload.id !== 'string' || typeof payload.status !== 'number') return;

  await db.transaction(async (tx) => {
    // Find the order by a transaction reference already stored, else by externalid
    // (widget payments: the intent externalid, or the intent id).
    const order =
      (await tx.orders.lockByTransactionRef(payload.id)) ??
      (await tx.orders.lockByExternalId(payload.externalid));
    if (!order) return;                                         // not ours: ignore
    if (payload.env !== order.env) return;                      // never mix live and sandbox

    // 1. Audit trail: every status this delivery mentions (insert-if-absent).
    for (const h of payload.statushistory ?? [])
      await tx.statusLog.addOnce(order.id, payload.id, h.status);

    // 2. In progress (10–16) or declined (3): information only. A declined attempt does not
    //    end the order (the shopper may retry under a new reference), and neither can ever
    //    touch a paid order. Pre-capture state comes from the Payment Intent.
    if (IN_FLIGHT.has(payload.status) || payload.status === 3) return;
    if (!CAPTURED.has(payload.status)) return;                  // 0, 5, 35, legacy codes

    // 3. Captured family: the webhook is a signal; the transaction record is the truth.
    const txn = await securepay.getTransaction(payload.id);     // GET /api/v1/transactions/{id}
    if (!CAPTURED.has(txn.status)) return;

    // First capture: fulfil exactly once, after checking amount and currency.
    if (!order.paid) {
      if (toMinorUnits(txn.amountpaid, txn.currencypaid) !== order.amountMinor ||
          txn.currencypaid !== order.currency)
        return tx.orders.flagOnce(order.id, 'amount mismatch');
      await tx.orders.markPaidOnce(order.id, payload.id);
    } else if (order.paidTransactionRef !== payload.id) {
      await tx.orders.flagOnce(order.id, `second capture ${payload.id}`);  // paid twice: review
    }

    // 4. After the payment, per transaction: overwrite with the record just read.
    //    Repeats are harmless; a stale webhook cannot move anything backwards.
    await tx.transactions.setPostPaymentState(order.id, payload.id, {
      status: txn.status,                                       // 1, 20, 34, 9, 21–33
      chargeback: txn.chargeback,                               // true for 24–33
      refunded: txn.refunded_presentment_amount,                // decimal strings
      pendingRefund: txn.pending_refund_presentment_amount,
      payoutStatus: txn.deliverystatus,
    });
  });
}

// Reconciliation: run every few minutes. Covers late and lost webhooks and the
// refund-pending state that is never sent.
async function reconcile() {
  for (const t of await db.transactions.findOpenOlderThan('5 minutes')) {
    // open = order awaiting payment, refund requested, or dispute in progress
    const txn = await securepay.getTransaction(t.ref);
    await handle({ id: txn.id, status: txn.status, env: t.env, externalid: txn.externalid,
                   statushistory: [{ status: txn.status }] });
  }
}
```

Rules the handler encodes; keep them when adapting it:

1. Verify the signature on the raw bytes before parsing.
2. Answer `2xx` only after the payload is stored durably.
3. Never let statuses 10–16 or 3 change a paid order; never let one declined
   attempt fail an order whose intent can still be paid.
4. `PAID` means "captured", not "finished": keep processing 20, 34, 9 and
   21–33 afterwards, including a dispute after `REFUNDED`.
5. Make fulfilment a once-only action keyed on the order, and check
   `amountpaid` and `currencypaid` first.
6. For anything after capture, act on the transaction record just read, not on
   the webhook's fields.
7. Run the reconciliation job; it is not optional.

#### Google Pay in the widget — known defect

When the bank requires a redirect 3-D Secure for a Google Pay payment made in
the widget, the payment is captured on the platform's own return page and the
Payment Intent can stay `requires_payment` although the money was taken. The
transaction still moves to `PAID` and its webhook carries the intent's
`externalid`. For an intent that stays `requires_payment` after the shopper
approved a wallet payment, read
`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`
(or check the dashboard) before asking for another payment. Never ask for money
again while a transaction for that order reads `PAID` or `PAYING`.

## Subscription events

Subscription events are described field by field in the subscriptions chapter.
For the webhook receiver, apply these rules:

- Recognise them by a string `type` starting with `subscription.`. They arrive
  at the same URL with the same signature, queue, retries and merge rule (a
  repeat with the same `id` and `type` merges into one still waiting).
- Every event has string `id`, string `type`, numeric `environment` (`0` live,
  `1` sandbox), `occurredAt` and `merchantid` (lower case; there is no
  `merchantId`).
- Treat `id` as opaque; its format differs between event types. Never parse it.
- **Deduplicate renewal events (`subscription.renewal_*`) on `id` + `paymentId`
  + `occurredAt`, never on `id` alone.** A renewal event's `id` is built from
  the agreement, the attempt number and the type, so attempt 1 of every period
  has the same `id`. `paymentId` can be `null`.
- Renewal and plan events carry no `status`; read the agreement for its state.
- There is no activation event; read the agreement
  (`GET /api/v1/subscriptions/{externalReference}`).
- Answer `2xx` to types you do not handle.

## Transactions API

### `GET https://app.securepayapi.com/api/v1/transactions/{id}` — read one transaction

The authoritative current state of one transaction. Use it to confirm a capture
before fulfilment, to reconcile, and after every captured-family webhook.

#### Authentication

`Authorization: Bearer sp_secret_…` — the merchant's secret key. Server only;
never from a browser. A publishable key (`sp_client_…`) is refused. The key
returns only the merchant's own transactions.

#### Path parameter

| Parameter | Type | Rules |
| --- | --- | --- |
| `id` | string | Transaction reference: the intent's `transaction_reference`, the webhook `id`, or the reference shown in the dashboard. Must match `[A-Za-z0-9_-]{1,64}` (surrounding whitespace is trimmed). **Not** the Payment Intent id. |

No query parameters and no body. Only `GET`.

#### Example

```bash
curl https://app.securepayapi.com/api/v1/transactions/LUZH24T2E65K3NN4 \
  -H "Authorization: Bearer sp_secret_…"
```

#### Response `200`

The platform's transaction record, unchanged:

```json
{
  "id": "LUZH24T2E65K3NN4",
  "payin_method": "card",
  "card_brand": "visa",
  "payment_network": null,
  "payment_provider": "…",
  "payment_provider_config_id": null,
  "created": 1789123456.789,
  "transaction": null,
  "status": 1,
  "statustext": "Paid",
  "paymenttype": 1,
  "paymenttypetext": "ECOM",
  "payment_channel": 1,
  "funding_method": 1,
  "payment_channel_text": "ecommerce",
  "funding_method_text": "card",
  "deliverystatus": 1,
  "deliverystatustext": "Delivery Pending",
  "url": null,
  "cardholder": "Jordan Lee",
  "card": "411111xxxxxx1111",
  "cardbank": "Example Bank",
  "cardcountry": "US",
  "amountpaid": 49.99,
  "currencypaid": "USD",
  "usdpaid": 49.99,
  "usdfee": 1.75,
  "tokenssent": null,
  "product": null,
  "chain": null,
  "token": null,
  "nonce": null,
  "externalReference": "ORDER-42",
  "externalid": "ORDER-42",
  "invoice": null,
  "order": null,
  "merchantid": "7TTR77ZC",
  "chargeback": false,
  "processorid": "…",
  "refund_reason": null,
  "refund_request_source": null,
  "refund_requested_at": null,
  "refunded_presentment_amount": "0",
  "pending_refund_presentment_amount": "0",
  "partial_refund_count": 0,
  "refunds": []
}
```

| Field | Type | Meaning |
| --- | --- | --- |
| `id` | string | Transaction reference. The only identifier. |
| `created` | number | Unix **seconds**, may be fractional. |
| `status` | number | Status code (table in Webhooks). Code against it. |
| `statustext` | string | Human label (`Paid`, `Settled`). For `FAILED` (3) it is the decline reason. Never branch on it. |
| `amountpaid` | number | Amount in the payment currency, major units. |
| `currencypaid` | string | Payment currency. |
| `usdpaid` | number | Reporting amount in USD (not the settlement amount). |
| `usdfee` | number | Platform fee in USD. |
| `payin_method` | string | `card`, `applepay`, `googlepay`, `ach`, `wire`, `usdc`, `paypal`, `unknown`. |
| `card_brand` | string or null | Normalized scheme (`visa`, `mastercard`, `amex`, `discover`) for card payments, else `null`. |
| `payment_network` | string or null | Confirmed executed network (e.g. `pulse`, `visa`), else `null`. Never infer it from the brand. |
| `payment_provider`, `payment_provider_config_id` | string or null | Processor that executed the payment and its configuration. |
| `processorid` | string or null | Processor reference of the payment. |
| `card` | string or null | Masked card number. |
| `cardholder` | string or null | Name on the card. |
| `cardbank`, `cardcountry` | string or null | Issuer name and country. |
| `paymenttype`, `paymenttypetext` | number, string | Channel (`1`/`ECOM` …), not the scheme. |
| `payment_channel`, `payment_channel_text`, `funding_method`, `funding_method_text` | number, string | As in the webhook. |
| `deliverystatus`, `deliverystatustext` | number or null, string | Payout status and its label (table in Webhooks). |
| `tokenssent`, `token` | number or null, string or null | Payout amount and currency. |
| `chain`, `nonce`, `transaction`, `url` | | Crypto payout chain, nonce, payout reference and block-explorer link; `null` otherwise. |
| `externalReference`, `externalid` | string or null | The merchant's reference, same value twice. |
| `product` | number or null | SKU recorded on the payment. |
| `invoice` | string or null | Invoice id. |
| `order` | `{id, version}` or null | Platform order. |
| `merchantid` | string | The merchant id. |
| `chargeback` | boolean | `true` for statuses 24–33. `false` during an information request (21–23). |
| `refund_reason`, `refund_request_source`, `refund_requested_at` | string or null | Set once a refund was requested. Source: `merchant_api`, `admin`, `automatic_fraud`. |
| `refunded_presentment_amount`, `pending_refund_presentment_amount` | string (decimal) | Confirmed and pending partial-refund totals; default `"0"`. |
| `partial_refund_count` | number | Default `0`. |
| `refunds` | array | Refunds of the transaction; default `[]`. Do not depend on the element shape. |
| `customer_card_surcharge` | object | Only when a card surcharge applied. |

Ignore unknown fields; code only against the fields you need.

#### Errors

All errors are JSON `{"error": "<text>"}`.

| HTTP | `error` | When | Action |
| --- | --- | --- | --- |
| 401 | `Unauthorized — provide a valid secret key as a Bearer token` | header missing or not `Bearer`; token not an `sp_secret_` key; unknown key; merchant account not yet activated on the platform. Header `WWW-Authenticate: Bearer`. | Fix the key. Do not retry unchanged. |
| 403 | `Account is not active` | merchant account suspended or not active | Stop; the merchant must contact support. |
| 404 | `Transaction not found` | unknown id; another merchant's transaction; malformed id; **or the payment platform could not be reached** | For a reference you know exists, retry with backoff before concluding anything. |

#### Decision table

| Transaction read | Meaning | Do |
| --- | --- | --- |
| `status` 1 or 20, amount and currency match | Paid | Fulfil once. |
| `status` 1 or 20, amount or currency differ | Paid, wrong amount | Do not fulfil; flag for review. |
| `status` 10–15 | Attempt in progress | Wait; read again later. |
| `status` 16 | Capture sent, outcome unknown | Do not charge again; read again later. |
| `status` 3 | This attempt declined | The order is not paid by this transaction; the shopper may pay again (new reference). |
| `status` 34 | Full refund pending | Treat as refunding; read again later. |
| `status` 9 | Fully refunded | Reverse fulfilment as your policy says. |
| `status` 21–23 | Information request | Watch the dashboard; no action available there. |
| `status` 24 | Chargeback open, amount held | Respond in the dashboard (Disputes). Do not refund. |
| `status` 25, 26, 29, 32 | Dispute resolved for the merchant | Record. |
| `status` 27, 30, 33 | Dispute lost or accepted | Record the loss; do not refund. |
| `status` 28, 31 | Pre-arbitration / arbitration open, amount held | Record; do not refund. |
| `404` | Unknown or unreachable | Retry with backoff; do not treat as unpaid. |

## Disputes

Merchants handle disputes in the dashboard. There is no public API to accept or
defend a dispute.

### How a dispute is reported

- Each status change reaches the webhook as the ordinary transaction payload
  with the dispute status (21–33). It carries no reason, amount or deadline.
- Issuer comments, fraud notifications and repeated notifications that do not
  change the status send no webhook.
- The transactions API shows the state: `status` and `chargeback` (`true` for
  24–33).
- A dispute status can follow `PAID`, `SETTLED` or `REFUNDED`.

### Lifecycle

| Stage | Codes | Amount |
| --- | --- | --- |
| Information request | 21 requested, 22 responded, 23 expired | not held |
| Chargeback | 24 open, 25 reversed, 26 won, 27 lost | held while 24; lost on 27 |
| Pre-arbitration | 28 open, 29 won, 30 lost | held while 28; lost on 30 |
| Scheme arbitration | 31 open, 32 won, 33 lost | held while 31; lost on 33 |

`WON` or `REVERSED` = resolved for the merchant; `LOST` = against the merchant.
Accepting a chargeback ends in 27. A chargeback not defended before its defense
period ends becomes 27. Stages follow the card scheme's process, not a fixed
order. A refund is refused in 24, 27, 28, 30, 31 and 33.

### Dashboard: what is shown

On the transaction page a disputed transaction (24–33) has a Chargeback card
with, when the processor provides them: the reason code and description, issuer
comments with dates, issuer documents (open or download), and the required
evidence (document type codes and requirement level). The response deadline is
**not** shown in the dashboard.

### Dashboard: respond

Available **only while `status` is 24 (`CHARGEBACKOPEN`)** and only on an
active account. Not during 21–23, 28 or 31.

**Accept** — concede. Confirmed once more in the dashboard; irreversible.

**Defend** — only when the processor reports the dispute as defendable and
lists at least one defense reason. Otherwise the card says the requirements are
unavailable and offers Refresh requirements; Accept stays available.

Defense input:

| Item | Rule |
| --- | --- |
| Defense reason | exactly one, from the processor's current list |
| Files | up to 5; `application/pdf`, `image/jpeg`, `image/tiff`; PDF ≤ 2 MB, image ≤ 10 MB each |
| Written note | optional, ≤ 1000 characters; rendered to a PDF with the merchant's letterhead and the transaction details; submitted first |
| Document type | required for every file and for the note; must be one of the chosen reason's document types |
| Submission size | ≤ 16 MB in total, including the generated note PDF |

Requirement levels per document type: `Required`, `AlternativeRequired`,
`OneOrMore`, `Optional`. The dashboard accepts the defense only when:

- every type that is not `Optional` has at least one document — a document
  already supplied to the processor (marked **Already supplied**) counts;
- every type that is not `OneOrMore` has at most one document — including an
  already supplied one, so such a type cannot receive more.

Several items under one single-document type are merged into one PDF of at most
2 MB. TIFF images, encrypted PDFs, and PDFs with form fields, annotations or
attachments cannot be merged; convert them to a static PDF first. `OneOrMore`
types keep separate documents.

On submit the requirements are read again from the processor. If the chosen
reason or its document types changed, nothing is sent; the dashboard shows the
current requirements and keeps the text and files. If the processor does not
confirm the defense, refresh the transaction and check its status before
submitting again.

The outcome arrives later as a status change (webhook and transactions API).

### Rules

- Respond well before the deadline; it is not shown in the dashboard.
- Never refund a transaction in 24, 27, 28, 30, 31 or 33 — the refund is
  refused and the disputed amount is already being returned.
- Do not treat 21–23 as a chargeback: `chargeback` is `false` and nothing can
  be submitted in the dashboard.
- Keep processing dispute statuses after `REFUNDED`.


---

## Hosted checkout pages

A hosted checkout page sells one dashboard product. The merchant creates the
product in the dashboard (**Payment Links**) and shares its URL; no server
code, no API key and no Payment Intent are involved. Do not try to create or
drive a hosted product payment from code.

### `GET https://checkout.securepayapi.com/<productId>`

#### The URL

| Part | Rule |
| --- | --- |
| `<productId>` | The product id shown by the dashboard: 24–32 characters, lower-case letters and digits. Any other shape answers `404`. |
| Query string | Ignored for money. Price, currency, coupons and live/sandbox come from the product on the server. `?mode=sandbox` (which the dashboard's **Open checkout** link adds for sandbox products) changes nothing. |

- Never build a checkout URL that tries to set an amount, currency, discount or
  mode. Nothing in the URL can change what is charged.
- Share the URL exactly as the dashboard gives it.

#### When the page answers 404

- The id is malformed or unknown.
- The product is **archived** or was **deleted**.
- The merchant account is not active.

The page is rendered fresh on every request (never cached): archiving or
re-activating a product takes effect on the next load.

#### What the shopper sees

| Element | Source and limit |
| --- | --- |
| Store name | The merchant's registered business name (up to 120 characters), else "Store" |
| Website, support email | From the merchant's account profile, each shown only when set |
| Product name | Up to 200 characters |
| Description | The first 2,000 characters |
| Image | The **first** product image only; also the link-preview image |
| Features | Up to 20 lines; a line longer than 200 characters is dropped |
| Price | The product price in the product currency |
| Discount-code field | Only when the product has at least one coupon |
| Test-mode banner | "Test mode — sandbox · no real charge" on a sandbox product |

The page title for link previews is `<product name> · <store name> · securepayAPI`;
the preview description is the product description, else
`Pay for <product name> at <store name>.`

#### The payment form

| Field | Rule |
| --- | --- |
| Email | Required for a card payment: a valid address, up to 254 characters. Optional for Apple Pay. |
| Cardholder name | 1–64 characters: letters, digits, spaces, `'`, `.`, `:`, `-` |
| Card number, expiry (`MM/YY`), CVC | Entered in the page; never reach the merchant |
| Billing address | Optional. Street, house number, city, 2-letter state, postal code (up to 10 characters), 2-letter country. A malformed field is dropped, not refused. |
| Discount code | Optional; see [Coupons](#coupons) |

#### Pricing — decided on the server

1. `subtotal` = the product price.
2. The typed code is trimmed and upper-cased and looked up in the product's
   coupons. Unknown or empty → no discount, no error.
3. Known code with `p` percent → `discount = round(subtotal × p / 100, 2)`.
4. `total = max(0, subtotal − discount)`, two decimals. No tax is ever added.

The total is recomputed on the server when the payment starts, from the
product as stored at that moment. The browser cannot change it.

#### Wallets

| Wallet | On product pages |
| --- | --- |
| Apple Pay | Offered on a device that can open an Apple Pay sheet, when the payment can be prepared. The sheet shows the same server total; applying or removing a code, or changing the email, prepares the payment again. |
| Google Pay | **Not offered.** Google Pay exists in the embedded widget and, where enabled, on hosted invoices. |

The card form is always present. Only one payment runs per page: while Apple
Pay or a card attempt is running, the other cannot start.

#### Outcomes on the page

| What the shopper sees | Meaning | Merchant action |
| --- | --- | --- |
| "Thank you — your payment went through." | Captured | Fulfil from the webhook or the transaction, not from the shopper's word |
| An error message with the form still available | Declined or refused before capture; nothing charged | None; the shopper may retry |
| "Being confirmed … Do not pay again", with a reference | Outcome not known yet; money may have moved | Look the reference up before asking for any new payment |

The uncertain state is remembered in that browser: a reload does not bring the
pay button back. There is no redirect and no success URL after payment.

#### How the merchant learns the outcome

- **Webhooks.** Each status change of the payment's transaction is sent to the
  merchant's webhook endpoint. For a hosted product payment, `externalid` and
  `externalReference` are the **product id**. Fulfil on status `1` (`PAID`) or
  `20` (`SETTLED`), whichever arrives first.
  Treat `16` (`PAYING`) as "capture sent, not final": neither paid nor unpaid.
  `3` (`FAILED`) ends that attempt.
- **Transaction lookup.** `GET https://app.securepayapi.com/api/v1/transactions/{id}`
  with the secret key, using the webhook's `id`, returns the amount, currency,
  status and card details. Read it before fulfilling when in doubt.
- **Dashboard.** The payment appears under **Transactions** in the cabinet of
  the product.

There is no Payment Intent for a hosted product payment: do not call
`GET /api/v1/payment-intents/{id}` for it, and do not expect `notify_url`.

#### Sandbox

A product created while the dashboard is in **Sandbox** is a sandbox product: it
charges through the test processor, shows the test-mode banner and takes no
real money. A live product always charges live. The URL cannot move a product
between the two. Use the sandbox test cards on a sandbox product.

#### Do not

- Do not call the page's own internal endpoints (price quote, card
  submission). They are not an API, are protected against cross-site use, and
  change without notice.
- Do not embed the product page in an iframe on another site; use the embedded
  widget for checkout inside your own page.
- Do not promise customisation of the hosted page (logo, colours): it shows
  the store name and the product only.

## Products and coupons

Products are created and managed in the dashboard (**Payment Links**). There is
no public API for products: do not generate code that creates, edits or lists
them.

### Product fields

A product is created in the dashboard's current cabinet (**Live** or
**Sandbox**) and stays there; each cabinet lists only its own products.

| Field | Required | Dashboard accepts | What the checkout does | Effective rule |
| --- | --- | --- | --- | --- |
| Name | yes | 1–200 characters (trimmed) | Shows up to 200 | ≤ 200 |
| Description | no | up to 5,000 characters | Shows the first 2,000 | ≤ 2,000 to be fully visible |
| Price | yes | a number from 1.00 to 1,000,000,000, rounded to 2 decimals | Charges it (minus a coupon) | 1.00 – 1,000,000,000 |
| Currency | yes | `USD`, `EUR` or `GBP` | Charges in that currency | as accepted; confirm non-USD processing with support before use |
| Images | no | up to 5 uploads; JPEG, PNG or WEBP; ≤ 2 MB each | Shows the first only | first image matters |
| Features | no | up to 20 lines, each up to 300 characters | Drops any line over 200 characters | ≤ 20 lines × 200 characters |
| Coupons | no | up to 5 codes | Applies one per payment | see [Coupons](#coupons) |
| Category | no | `digital`, `physical`, `service`, `other` | Not used | informational |
| Unit label | no | up to 50 characters | Not shown | informational |
| Tax behavior | no | `auto`, `inclusive`, `exclusive` | **No tax is applied** | no effect |
| Metadata | no | up to 20 string pairs; key ≤ 80, value ≤ 500 characters | Not used | informational |

Dashboard errors on create: `Name is required`; `Amount must be at least 1.00`
(also shown for a price above 1,000,000,000); `Currency is required`. Image
upload errors: `Unsupported image type. Use JPEG, PNG, or WEBP.`;
`Image is larger than 2 MB.`

### Coupons

A coupon maps a **code** to a **whole percentage off**.

| Rule | Value |
| --- | --- |
| Percentage | Integer 1–100. Outside the range → the coupon is dropped on save. A fraction is truncated (`20.5` → `20`). |
| Characters | `A–Z`, `0–9`, `_`, `-`. Stored upper-cased; any other character (space, `%`, `.`) is **removed** on save, so `SUMMER 20` becomes `SUMMER20`. |
| Length | **≤ 32 characters.** The dashboard accepts up to 50, but the checkout refuses a code longer than 32 when the payment starts: the page shows the discount, then the payment is rejected. Never create a code longer than 32. |
| Count | ≤ 5 per product. Extra codes are dropped on save. |
| Matching | Case-insensitive; surrounding spaces ignored. An unknown code gives no discount and no error. |
| Stacking | One code per payment. |
| 100 % | Brings the total to `0.00`, but the checkout still runs a payment for that total, which is not guaranteed to complete. Do not use 100 % codes to give products away. |

### Status and lifecycle

| Action | Effect |
| --- | --- |
| Create | Status `active`; the checkout URL works immediately. |
| Archive | Status `archived`; the checkout URL answers `404`. |
| Re-activate | Status `active`; the same URL works again. |
| Delete | Permanent; the product and its images are removed and the URL answers `404` forever. |
| Edit | **Not available.** Only the status can change after creation. To change price, currency, coupons or content, create a new product and share its new URL. |

## Hosted invoices: bank and USDC pay-ins

A hosted invoice is paid on
`https://checkout.securepayapi.com/?invoice=<invoice-id>`. The invoice id is a
UUID; the link is issued when the invoice's payment link is enabled. This
chapter covers what the shopper sees and what the merchant must rely on.
Creating invoices from a server, and reading their bank or USDC state, belongs
to the private direct-integration contract; do not invent public endpoints for
it.

### The invoice link

- Share the link exactly as issued. Add nothing to it: the amount, currency and
  payable state come from the invoice on the server.
- `?lang=` (or the browser language) chooses the page language.
- A malformed invoice id shows "Invalid invoice link".
- The page never shows the merchant's credentials and needs none from the
  shopper.

#### What the page shows

| Invoice state | Page |
| --- | --- |
| open, link enabled, not expired | Payable: the enabled payment methods |
| open, link expired | "Expired" — not payable |
| open, link disabled | Not payable |
| open, a bank attempt pending / submitted / held | That attempt's status and instructions instead of payment methods |
| paid | Paid summary (for USDC: sender address, transaction hash, explorer link) |
| void, superseded | Not payable |

#### Payment methods per invoice

| Method | Offered when |
| --- | --- |
| Card | The invoice is payable (a USDC-only merchant setup offers no card) |
| Apple Pay, Google Pay | The platform reports them available for this invoice |
| ACH debit | USD invoice, and ACH debit is enabled for the merchant and environment |
| ACH transfer, wire | USD invoice, and the rail is enabled for the merchant and environment |
| USDC | USD or USDC invoice created with USDC enabled, and USDC pay-ins are available for the merchant |

Invoices created in the dashboard can be in `USD`, `EUR`, `GBP`, `CAD` or `AUD`
(amount up to 9 digits with up to 2 decimals, description up to 200
characters), have their payment link on by default, and never have USDC
enabled — the dashboard form has no USDC option.

Only one payment method can be in progress per invoice. Never prompt a shopper
for a second method while one is pending.

### Bank pay-ins

#### ACH debit

1. The shopper enters the account holder name (1–80 characters), account
   number (4–17 digits), routing number (exactly 9 digits), account type
   (`checking` or `savings`) and holder type (`personal` or `business`).
2. The page shows a **one-time debit authorization** naming the merchant, the
   amount and a contact email. The shopper must accept it explicitly.
3. The debit is submitted. Only the last four digits of the account are kept.

A debit cannot be cancelled from the page. If it is declined, the attempt is
`failed` and the invoice is payable again.

#### ACH transfer and wire

The page shows the instructions to send from the shopper's own bank:

| Instruction | Meaning |
| --- | --- |
| Account name, bank name, account number, routing number | The receiving account |
| Reference | Put it in the transfer memo; it identifies the payment |
| Amount | The total to send |
| Recipient address, bank address | Wire only |

Amount rules — must be correct everywhere:

- The amount to send **equals the invoice amount**. No fee is added for the
  payer on either rail: the pass-through fee is always `0.00`.
- Any incoming bank fee is borne by the merchant: it may reduce the credit the
  merchant receives, never the amount the shopper sends.
- Tell the shopper to send exactly the amount shown, with the reference. A
  transfer that arrives for a different amount is `held`, not applied.

A pending transfer can be cancelled on the page only when the shopper confirms
the funds were **not sent**. The invoice becomes payable again. Cancelling is
not a recall: a transfer that arrives after cancellation is recorded as late
and does not pay the invoice.

#### Bank statuses

| Status | Meaning | Invoice | Fulfil? |
| --- | --- | --- | --- |
| `pending` | Attempt recorded; transfer awaiting funds, or debit not yet accepted | open, not payable | no |
| `submitted` | Debit accepted by the bank provider | open, not payable | no |
| `confirmed` | Matching funds arrived | **paid** | yes — and keep watching |
| `held` | Funds arrived for a different amount, or could not be applied | open, not payable | no — needs operator resolution |
| `failed` | Debit refused or failed before money moved | open, payable again | no |
| `returned` | The bank returned the debit or transfer, also after `confirmed` | a paid invoice is **reopened** | reverse fulfilment |
| `canceled` | Unused transfer instructions retired by the shopper | open, payable again | no |

### USDC pay-ins

| Instruction | Rule |
| --- | --- |
| Network | Polygon in production; Polygon Amoy in sandbox. Use the network shown, never infer it from the currency. |
| Token | USDC |
| Deposit address | The address shown for this invoice |
| Amount | The invoice amount; a USD invoice is taken 1 USDC = 1 USD |
| Expiry | About one hour by default, never more than 24 hours, never after the invoice link's expiry |

- The shopper asks for instructions on the page. While a set is still awaiting
  payment, the page shows it rather than issuing another; after expiry, the
  shopper asks again for a new set. Reloading the page does not renew expired
  instructions.
- Instruction statuses: `awaiting_payment`, `expired`, `paid`.
- Never send against expired instructions, on another network, or a second
  time to fix an uncertain first transfer. Late, wrong-network or mismatched
  transfers need operator resolution; there is no automatic recovery.
- Very small amounts can be refused when network costs would consume the
  payment.

### How the merchant learns the invoice outcome

| Method used | Signal | Rule |
| --- | --- | --- |
| Card, Apple Pay, Google Pay | Transaction webhooks carrying the `invoice` id; the invoice turns `paid` | Fulfil when the invoice is `paid` (or the transaction is `PAID`) |
| USDC | A transaction webhook when the invoice is paid; the invoice turns `paid` | Fulfil when the invoice is `paid` |
| ACH debit, transfer, wire | **No webhook to rely on.** The invoice turns `paid` on `confirmed` | Check the invoice status (dashboard **Invoices**, or the private invoice contract) |

### Never assume

- Instructions shown, a debit submitted, a transfer sent, or a wallet
  "success" screen is **not** a paid invoice.
- `confirmed` is not final forever: a bank return can reopen a paid invoice.
- `held` is not paid and is not resolved by asking the shopper to pay again.
- A cancelled transfer that later arrives does not pay the invoice.
- Bank pay-ins are USD only; USDC needs a USD or USDC invoice with USDC enabled
  at creation; neither exists on product pages, the widget or Payment Intents.
- Do not generate code that calls bank, USDC or invoice routes from a browser,
  or that puts merchant secrets in an invoice URL.
