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