# Payment Intents API

URL: https://doc.securepayapi.com/api-reference
Last updated: 2026-11-12

> Reference for the Payment Intents API — authentication, every request parameter, responses, the subscription object and error codes.

The API base URL is `https://checkout.securepayapi.com`. All requests use HTTPS
and JSON.

## Endpoints overview

| Method | URL | Used from | Purpose |
| --- | --- | --- | --- |
| `POST` | `/api/v1/payment-intents` | Your server | Create a payment and get a `client_secret` |
| `GET` | `/api/v1/payment-intents/{id}` | Your server | Read an intent back to **confirm** a payment |
| `POST` | `/api/v1/payment-intents/{id}` | Your server | [Set the `externalid`](#update-the-external-id) of an unpaid intent |
| `POST` `GET` | `/api/v1/subscription-plans` | Your server | Create / list [subscription plans](#subscription-plans) |
| `POST` | `/api/v1/subscription-plans/versions`, `…/archive`, `…/reactivate` | Your server | Evolve a plan |
| `GET` | `/api/v1/subscriptions`, `/api/v1/subscriptions/{externalReference}` | Your server | Read [agreements](#subscription-agreements) |
| `POST` | `/api/v1/subscriptions/cycles`, `…/cancel`, `…/pause`, `…/resume`, `…/contact` | Your server | Bill a variable period, manage an agreement |
| `GET` | `/sdk/v1/securepay.js` | Browser | The [JavaScript SDK](https://doc.securepayapi.com/sdk) |
| `GET` | `/embed?pk=sp_client_…` | Browser (iframe) | The [embedded checkout](https://doc.securepayapi.com/embedded-checkout) widget |
| `GET` | `/<productId>` | Browser | A [hosted checkout](https://doc.securepayapi.com/hosted-checkout) page |

The full flow:

```
your server ──POST /api/v1/payment-intents──▶ { id, client_secret }
     │
     └─ pass client_secret to the browser
                              │
   browser ──SDK / iframe──▶ widget ──card, 3-D Secure──▶ success { intentId, status }
                              │
your server ──GET /api/v1/payment-intents/{id}──▶ status "succeeded"? amount? mode? → fulfil
```

The widget talks to its own internal endpoints to encrypt the card and run
3-D Secure — you never call those. Your backend calls only the
`/api/v1/payment-intents` endpoints (and the subscription ones, when you sell
recurring plans).

## Authentication

Authenticate server-to-server calls with your **secret** key as a Bearer token:

```
Authorization: Bearer sp_secret_…
```

Never call the API from a browser — the secret key must stay on your server.
The endpoints send no CORS headers, so a browser call is refused anyway.

## Create a Payment Intent

```
POST /api/v1/payment-intents
```

### Request body

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `amount` | integer | yes | Amount in the smallest currency unit (cents). 1–99,999,999. |
| `currency` | string | yes | `USD` in v1. |
| `reference` | string | no | Your own order reference, up to 200 chars. Stored on the intent and returned by `GET`. |
| `externalid` | string | no | Your identifier for the **transaction**. Keep it to **128 chars**: the endpoint accepts up to 200 (counted before trimming), but the payment platform takes 128 and refuses a longer one each time the customer submits a card. Trimmed; an empty or blank value counts as absent. Forwarded to the payment platform; appears as `externalid` in [webhooks](https://doc.securepayapi.com/webhooks) and on the [transaction](https://doc.securepayapi.com/transactions). When absent, the transaction carries the intent `id`. Can be [set later](#update-the-external-id). |
| `descriptor` | string | no | Trimmed; blank counts as absent; otherwise 5–100 chars. Accepted and stored, **not applied to the payment at present**: the statement text is your account's billing descriptor (dashboard → Settings). |
| `description` | string | no | Same rules as `descriptor`. Accepted and stored, not applied to the payment at present. |
| `metadata` | object | no | Flat object, **string values only**, ≤ 4096 bytes as JSON (UTF-8). Stored on the intent and returned by `GET`. The payment platform does not keep it: it is not on the transaction or in webhooks. |
| `notify_url` | string | no | An `https` address on your server that we call when this payment goes through — see [Payment notification](#payment-notification). Absolute URL, port 443 or none, a public host name (not an IP address, not `localhost` or a `.local` / `.internal` name), no user name or password, no `#fragment`, up to 2048 chars. `null` or `""` counts as absent. |
| `theme` | string | no | Widget colour scheme: `light` (default) or `dark`. |
| `mode` | string | no | `live` (default) or `sandbox`. Fixed on the intent at creation and decides whether real money moves; the browser cannot change it. See [Sandbox](https://doc.securepayapi.com/sandbox). |
| `subscription` | object | no | Makes this payment the setup of a recurring agreement, or a card replacement on one. See [The subscription object](#the-subscription-object). |

### Example

```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-123-2026-10-28",
    "descriptor": "ACME Store order 123",
    "description": "Pro plan — annual",
    "metadata": { "plan": "pro", "seats": "5" },
    "theme": "light",
    "mode": "live"
  }'
```

### Response `200`

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

`id` is 24 lowercase alphanumerics. `client_secret` is shown **only here** —
store it or hand it to the customer's browser; it cannot be read back later.
When a `subscription` was sent, the response also echoes it (without
`termsText`) plus `"operation": "setup"` or `"recoverPaymentMethod"`; for a
setup the echo always carries the canonical `billingTimezone` (`"UTC"` when you
sent none) and `recurringSurchargeConsent: false`.

Fields are validated in this order, and the first failure is the one reported:
`amount`, `currency`, `reference`, `metadata`, `externalid`, `descriptor`,
`description`, `theme`, `mode`, `subscription`, `notify_url`. There is **no
idempotency key**: a retried `POST` creates a second intent. An intent lives
**7 days** (`expires_at`).

### Errors

| Status | `code` | When |
| --- | --- | --- |
| `400` | `invalid_json`, `amount_invalid`, `amount_out_of_range`, `currency_unsupported`, `reference_invalid`, `metadata_invalid`, `metadata_too_large`, `externalid_invalid`, `descriptor_invalid`, `description_invalid`, `theme_invalid`, `mode_invalid`, `subscription_…` (see [below](#subscription-object-errors)), `notify_url_invalid` | The named field is invalid. |
| `401` | `missing_api_key`, `invalid_api_key` | No or bad secret key. |
| `500` | `internal_error` | The intent could not be stored. Nothing was created; retry. |

A `5xx` without this JSON body can also occur when our database is briefly
unreachable; treat it like `500`.

## The subscription object

Attach `subscription` to make the payment the first charge of a recurring
agreement. The plan itself (price, interval, terms) is created beforehand with
[`POST /api/v1/subscription-plans`](#subscription-plans) — the whole flow is
explained in [Recurring payments](https://doc.securepayapi.com/recurring-payments). The payment platform
keeps the card and bills every following period; the widget only performs the
customer-present setup, **card only**.

### New agreement

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `planExternalReference` | string | yes | The plan's external reference, 1–255 chars. The plan must exist and be active; the intent's `currency` must equal the plan's; `amount` must equal a fixed plan's amount, or be above zero and at most a variable plan's `maximumAmount` — all **checked by the payment platform when the customer pays**, not at creation. |
| `shopperExternalReference` | string | yes | **Your customer id**, 1–255 chars. Must not be personal data; a value containing `@` is refused. |
| `subscriptionExternalReference` | string | yes | Your id for this agreement, 1–255 chars. Used later to read, pause or cancel it. |
| `termsVersion` | string | yes | 1–64 chars. Must equal the plan's current terms version — checked when the customer pays. |
| `termsHash` | string | yes | 64 lowercase hex chars: the SHA-256 of `termsText`. Must equal the plan's current terms hash — checked when the customer pays. |
| `termsText` | string | yes | The exact consent text shown to the customer, 1–16,000 chars. Rejected unless its SHA-256 equals `termsHash`. |
| `billingAnchor` | string | yes | When recurring billing starts. ISO-8601 **with an explicit UTC offset** (`Z` or `±hh:mm`), e.g. `2026-11-28T12:00:00-04:00`. At least **60 minutes** in the future. |
| `billingTimezone` | string | no | IANA time zone, up to 64 chars. Default `UTC`. |
| `recurringSurchargeConsent` | boolean | no | Only `false` is accepted at present. |

The reference, version and time-zone strings must be sent without surrounding
whitespace (they are compared exactly, not trimmed); `termsText` is taken
verbatim and only has to hash to `termsHash`. Do **not** send `consent` —
consent is the customer's act in the widget. Do not send a billing interval or
price — those belong to the plan.

At creation only the shape of the block and the `termsText` ↔ `termsHash` match
are verified. A plan that does not exist or is archived, terms that are not the
plan's current ones, or a wrong amount or currency produce a normal `200`
intent whose payment is then refused in the widget. The plan must exist in the
intent's `mode`: a plan created with `mode: "sandbox"` is unknown to a live
intent. `subscriptionExternalReference` must be new: once a setup payment for
it was captured, another intent reusing it is refused when the customer pays.

### Subscription object errors

All `400` `invalid_request`, checked in this order:

| `code` | When |
| --- | --- |
| `subscription_invalid` | `subscription` is not an object. |
| `subscription_consent_not_accepted_here` | `consent` was sent. |
| `subscription_operation_invalid` | `operation` is neither absent nor `"recoverPaymentMethod"`. |
| `subscription_unknown_field` | A field not listed for that operation. |
| `subscription_reference_invalid` | `subscriptionExternalReference` not 1–255 chars without surrounding whitespace. |
| `subscription_terms_version_invalid` | `termsVersion` not 1–64 chars without surrounding whitespace. |
| `subscription_terms_hash_invalid` | `termsHash` not 64 lowercase hex chars. |
| `subscription_terms_text_invalid` | `termsText` not a string of 1–16,000 chars. |
| `subscription_terms_hash_mismatch` | SHA-256 (UTF-8) of `termsText` ≠ `termsHash`. |
| `subscription_surcharge_consent_invalid` | `recurringSurchargeConsent` not a boolean. |
| `subscription_surcharge_consent_unsupported` | `recurringSurchargeConsent: true`. |
| `subscription_plan_invalid` | New agreement: `planExternalReference` not 1–255 chars without surrounding whitespace. |
| `subscription_shopper_invalid` | New agreement: `shopperExternalReference` not 1–255 chars without surrounding whitespace. |
| `subscription_shopper_reference_pii` | `shopperExternalReference` contains `@`. |
| `subscription_billing_anchor_invalid` | `billingAnchor` not ISO-8601 with an explicit offset, or not a real date. |
| `subscription_billing_anchor_too_soon` | `billingAnchor` less than 60 minutes ahead. |
| `subscription_billing_timezone_invalid` | `billingTimezone` not a known IANA zone of 1–64 chars. |

### When the customer pays

These refusals reach the customer in the widget (and your `onError`); the
intent stays payable and nothing is charged:

| Refusal | Cause |
| --- | --- |
| "Recurring payments can only be set up with a card." | A wallet was used. |
| "Please accept the subscription terms to continue." | The consent box was not ticked. |
| "An email address is required for a recurring payment." | No email. |
| "The billing start date for this subscription has passed. Please ask the seller for a new payment link." | New agreement whose `billingAnchor` is no longer in the future — create a new intent with a later anchor. |
| The payment platform's own message | Unknown or archived plan, terms that are not the plan's current ones, amount or currency that does not fit the plan, a reused `subscriptionExternalReference`, and for a card replacement any mismatch with the unpaid period. |

### Card replacement on an existing agreement

```json
"subscription": {
  "operation": "recoverPaymentMethod",
  "subscriptionExternalReference": "membership-42",
  "termsVersion": "2026-10-01",
  "termsHash": "<sha256 hex of termsText>",
  "termsText": "<the consent text>"
}
```

`amount` must be the exact recovery amount of the agreement's unpaid period, as
the payment platform reports it. The plan, shopper and anchor fields are not
accepted here. Send the `termsVersion` and `termsHash` of the **agreement's own
plan version** — `plan.termsVersion` / `plan.termsHash` from the agreement read
— not the plan's newest version, if the plan has changed since.

### What the customer sees and what you receive

The widget shows a subscription badge, the first charge, the billing start, the
full `termsText` and a consent checkbox; the email field is always shown and
required; wallets are not offered. After payment, the `success` result carries
`subscription: { status: "pending_activation", externalReference }` — the
payment is captured, the agreement is activated by the payment platform
moments later. No webhook announces activation — read it with
[`GET /api/v1/subscriptions/{externalReference}`](#subscription-agreements)
until `status` is `active`.

## Retrieve a Payment Intent

```
GET /api/v1/payment-intents/{id}
```

The server-to-server confirmation step. Read the intent **you created** for an
order and compare it with the order before you fulfil — the browser's `success`
message is not evidence.

### Path parameters

| Parameter | Description |
| --- | --- |
| `id` | The intent id returned at creation (24 lowercase alphanumerics). |

### Example

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

### Response `200`

```json
{
  "id": "k3m9q2x7v1b8n4c6d0f5g7h2",
  "status": "succeeded",
  "amount": 2000,
  "currency": "USD",
  "mode": "live",
  "reference": "order_123",
  "externalid": "shop-123-2026-10-28",
  "metadata": { "plan": "pro", "seats": "5" },
  "transaction_reference": "LU494ZZ07K7814E3",
  "last_attempt": null,
  "created_at": "2026-10-28T19:02:11.000Z",
  "expires_at": "2026-11-04T19:02:11.000Z",
  "paid_at": "2026-10-28T19:04:58.000Z"
}
```

| Field | Description |
| --- | --- |
| `status` | `requires_payment` (nothing charged — also while the customer is in 3-D Secure), `processing` (the charge was sent, result not final), `succeeded` or `failed` — see [Payment statuses](https://doc.securepayapi.com/payment-intents#payment-statuses). |
| `amount`, `currency`, `mode` | As created. Compare all three with your order; a `sandbox` intent moved no money. |
| `reference`, `externalid`, `metadata` | As created, except `externalid` may be updated while unpaid. `externalid` is `null` when you never set one (the transaction then carries the intent `id`). |
| `transaction_reference` | The payment platform's reference for the **current** attempt, set as soon as an attempt is opened — for Apple Pay and Google Pay that is when the widget loads, before the customer does anything. Once the intent `succeeded` it is the reference of the payment that was captured. It is the `id` in [webhooks](https://doc.securepayapi.com/webhooks) and on the [transaction](https://doc.securepayapi.com/transactions) — store it against the order. `null` before any attempt. |
| `last_attempt` | `null`, or `{ reference, outcome, message, at }` — how the **previous** attempt ended when the widget has since prepared another one: `outcome` is `declined`, `cancelled`, `failed` or `pending`; `message` is the text the customer saw (≤ 200 chars, or `null` — a closed sheet has no message). A wallet decline happens between the sheet and the platform, and the widget then prepares a fresh attempt, so `transaction_reference` points at a reference that has done nothing yet; this field is where the decline went. It is the browser's account, for explaining a stuck-looking payment — not evidence for settling one. |
| `created_at`, `expires_at` | ISO-8601. The intent cannot be paid after `expires_at`; its `status` does not change when it expires. |
| `paid_at` | ISO-8601 when `status` is `succeeded`; `null` otherwise. Gate on `status`, not on this field alone. |

The `client_secret` is never returned.

> **Warning:**
A Google Pay payment made in the widget through a bank's redirect 3-D Secure
page can be captured while the intent still reads `requires_payment`. If the
customer approved a wallet payment and the intent stays `requires_payment`,
read the transaction (`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`,
see [Transactions](https://doc.securepayapi.com/transactions)) or check the dashboard before asking for
another payment.

### Errors

| Status | `code` | When |
| --- | --- | --- |
| `401` | `missing_api_key`, `invalid_api_key` | No or bad secret key. |
| `404` | `intent_not_found` | Unknown or malformed id — **or** an id that belongs to another account. The cases are indistinguishable, so ids cannot be probed. |

## Payment notification

When you create the intent with a `notify_url`, our server calls that address
once the payment has gone through — server to server, so your order does not
depend on the customer's browser getting back to your site (a closed tab, a
page that reloaded during 3-D Secure).

```http
POST /your/notify/address HTTP/1.1
Content-Type: application/json
User-Agent: securepayAPI-Notify/1.0

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

`status` is `succeeded`, or `processing` when the charge was sent and its
outcome is not final yet (hold the order; do not charge again). A `processing`
call may later be followed by a `succeeded` one for the same `id`. Nothing is
sent for a declined charge. `externalid` is the value stored on the intent —
`null` if you never set one.

> **Warning:**
**The call is a hint, not proof.** It is not signed. On receiving it,
[read the intent back](#retrieve-a-payment-intent) with your secret key — the
`id` must be one you stored on an order — and settle the order from that
answer, exactly as you do after the browser's `success`. Never mark an order
paid from the body of this call.

- It is sent about **10 seconds** after the charge, so your normal
  browser-driven confirmation usually settles the order first; make the handler
  idempotent (an order already settled needs nothing).
- Answer any **2xx**. Otherwise (another status, a timeout, a connection or
  DNS error) it is tried again one and five minutes after the charge, then
  given up — three tries at most. Redirects are not followed (a `3xx` counts as
  a failure); the request times out after 15 seconds.
- An address whose host name resolves to a private, loopback or link-local
  network address is never called and not retried.
- Delivery is best effort: in rare cases (a restart on our side within those
  five minutes) a call is lost. Do not make it your only way to learn about a
  payment — keep confirming from the browser's `success` and, for orders still
  open, read the intent back yourself.
- It concerns this payment only. For everything that happens to a transaction
  afterwards — settlement, refunds, disputes — use [webhooks](https://doc.securepayapi.com/webhooks).

## Update the external id

```
POST /api/v1/payment-intents/{id}
```

Sets your own reference on an intent created before you knew it — an order
number that exists only once the customer places the order. Allowed only while
the intent is **unpaid**.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `externalid` | string \| null | yes | Up to 128 chars after trimming. `null` (or an empty or blank string) clears it, and 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" }'
```

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

The value reaches the payment platform with the **next** payment attempt. An
attempt that was already started keeps the reference it was opened with; Apple
Pay and Google Pay are prepared as soon as the widget loads, so a wallet payment
carries whatever the intent held at that moment. The call does not rewrite an
existing transaction and does not change `reference`.

| Status | `code` | When |
| --- | --- | --- |
| `400` | `invalid_json`, `externalid_invalid` | The body is not JSON, or `externalid` is missing, not a string, or longer than 128 chars. |
| `401` | `missing_api_key`, `invalid_api_key` | No or bad secret key. |
| `404` | `intent_not_found` | Unknown id, or another account's. |
| `409` | `intent_not_updatable` | The intent is already paid, or closed after a charge with an uncertain outcome. The `type` of this error is `invalid_request`, not `conflict`. |

The body is checked before the id: a malformed body on an unknown id answers
`400`, not `404`. An expired intent that was never paid can still be updated.

## Subscription plans

All subscription endpoints take the same Bearer secret key, JSON bodies, and
an optional `mode` (`"live"` default, or `"sandbox"`) as a body field (`POST`)
or query parameter (`GET`). Money is an exact **decimal string** (`"19.99"`),
not minor units. Mutations take an `idempotencyKey` (UUID): optional on every
call except `/subscriptions/cycles`, where it is required; when absent one is
generated. The key used is always echoed in the answer as `idempotencyKey`.
A key is scoped to its action, so one UUID may serve a pause and a later
resume. Plan **creation** is the exception: it is idempotent on
`externalReference` plus the plan's facts, and the key has no effect there.
**Always send your own key** on a mutation and reuse it when you retry: a
`502` can mean the platform applied the call but the answer was lost, and only
the same key makes the retry safe. Replaying a pause, resume or cancel with the
same key sends its webhook again.

Use the same `mode` for a plan, the intents that sell it and every later call
on its agreements: each cabinet has its own plans and agreements. Bodies are
capped at 16 KB. Answers never contain the platform's internal routing id.
The concepts are explained in [Recurring payments](https://doc.securepayapi.com/recurring-payments).

### `POST /api/v1/subscription-plans`

| Field | Required | Contract |
| --- | --- | --- |
| `externalReference` | yes | 1–255 chars, no surrounding whitespace. Replaying it with the plan's **original (version 1) facts**, `name` included, returns the existing plan (`created: false`); with a changed fact the request fails — change a plan through `/versions` instead. |
| `name` | yes | Display name, 1–255 chars. |
| `amountMode` | yes | `"fixed"` or `"variable"`. |
| `amount` | fixed only | Positive decimal string. |
| `maximumAmount` | variable only | Positive decimal string: the cap for one period. |
| `currency` | yes | `"USD"` — the only currency a Payment Intent can carry, so the only one a plan can be sold in. |
| `intervalUnit` | yes | `"day"`, `"week"`, `"month"`, `"year"`. |
| `intervalCount` | yes | Integer 1–365 (periods of `intervalUnit`). |
| `termsVersion` | yes | 1–64 chars. |
| `termsHash` | yes | 64 lowercase hex chars (SHA-256 of the consent text). |
| `requiresCommerceOrder` | no | Physical-shipment plans only; needs a variable plan and the feature enabled. |

> **Warning:**
Two kinds of bad request on this endpoint do **not** come back as a clean `400`
or `409` at present, but as `502 upstream_error`: a replay of an existing
`externalReference` with a changed fact, and an amount the platform cannot take
(not a positive decimal, or `amount` on a variable plan / `maximumAmount` on a
fixed one). A `502` here is therefore not always transient — check your request
before retrying. Shape errors (`amountMode`, `intervalUnit`, `intervalCount`,
`termsHash`, lengths, a missing amount) are `400 rejected` as usual.

Response `200` (the plan as created; `created` is `false` when the reference
was replayed with identical facts and the existing plan is returned):

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

Reads (`GET`) and the `/versions` call answer the plan in its presented form
instead: `{ externalReference, environment, name, status,
currentVersion: { version, amountMode, amount, maximumAmount, requiresCommerceOrder,
currency, intervalUnit, intervalCount, termsVersion, termsHash, createdAt },
createdAt, updatedAt }` (plus `versions[]` on a single-plan read, `created` and
`idempotencyKey` on `/versions`). `environment` is `"production"` or
`"sandbox"`. Amounts come back as the stored decimal, so trailing zeros may
differ from what you sent.

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

| Query | Required | Contract |
| --- | --- | --- |
| `externalReference` | no | Returns one plan with `versions: [...]` (newest first, up to 100), or `404`. The other parameters are then ignored. |
| `status` | no | `active` or `archived`. |
| `limit` | no | 1–100, default 25. |
| `cursor` | no | The `nextCursor` of the previous page. |

Without `externalReference`: `{ "items": [plan, …], "nextCursor": "…" | null }`.

### `POST /api/v1/subscription-plans/versions`

Same body as creation, keyed by the plan's `externalReference`, plus
**`expectedVersion`** (required: the plan's current `currentVersion.version`
as you last read it, an integer ≥ 1); `name` is not taken. Answers the plan
with the new `currentVersion`. Every version needs a **`termsVersion` that was
never used on this plan** (and normally a new consent text and `termsHash`):
reusing one — even for a price-only change — is `409`. So is a version that
changes nothing, one on an archived plan, one whose `expectedVersion` is no
longer current (re-read the plan and retry), and an `idempotencyKey` reused
with different facts. Missing or malformed → `400`
`expectedVersion_required` / `expectedVersion_invalid`.

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

Body `{ externalReference, idempotencyKey?, mode? }`. Answer
`{ externalReference, environment, status, effectiveAt, created, idempotencyKey }`.
An archived plan cannot be named by a new intent (the payment is refused) and
cannot receive a version; agreements already on it keep billing. Archiving an
archived plan, or reactivating an active one, is `409`. Any other action name
is `404 not_found`.

## Subscription agreements

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

The path form, or `?externalReference=…`, returns one agreement with its
timeline (`cycles[]` with `attempts[]`, and `events[]`) — the full shape is in
[Recurring payments → Reading an agreement](https://doc.securepayapi.com/recurring-payments#3-reading-an-agreement).
Percent-encode the reference in the path form; a reference that is literally
`cycles`, `cancel`, `pause`, `resume` or `contact` can only be read through the
query form. Without a reference, a page:

| Query | Required | Contract |
| --- | --- | --- |
| `status` | no | `pending_setup`, `active`, `paused`, `past_due`, `cancelled`, `completed`. |
| `limit` | no | 1–100, default 25. |
| `cursor` | no | The `nextCursor` of the previous page. |

### `POST /api/v1/subscriptions/cycles`

Bills one due period of a **variable** plan.

| Field | Required | Contract |
| --- | --- | --- |
| `externalReference` | yes | The agreement. |
| `amount` | variable plan | Non-negative decimal string, ≤ 18 decimals, ≤ the plan's `maximumAmount`. `"0"` records a `skipped` period without a charge. |
| `order` | commerce-order plan | `{ id, version }` of the physical order; `403` without the feature. |
| `idempotencyKey` | **yes** | UUID you generate and store (`400 idempotencyKey_required` without it). Owns the submitted facts permanently: same key + same amount → the same cycle; same key + other amount → `409`; a second key for a period that already has a cycle → `409`. |

Answer: `{ externalReference, environment, amount, currency, periodStart, periodEnd, billingAt, status, created, idempotencyKey }`.

The call **schedules** the charge; it does not wait for it. A positive amount
answers `status: "scheduled"`, `created: true`: the card is charged shortly
afterwards and the result arrives by [webhook](https://doc.securepayapi.com/webhooks#subscription-events)
and in the agreement's `cycles`. `nextBillingAt` moves forward only when that
charge is paid. `"0"` answers `status: "skipped"` and moves the schedule at
once. A replay of the same key answers `created: false`.

`409` when the agreement is not active (including `paused` and `past_due`),
not due yet (`nextBillingAt` in the future), has a cancellation scheduled at
period end, or has no active card credential; when the amount is above the
plan's `maximumAmount`; when the period already has a cycle; and on a fixed
plan (its renewals are billed by the platform). A missing or malformed decimal
string is `400 rejected`.

```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"
}
```

### `POST /api/v1/subscriptions/cancel` · `…/pause` · `…/resume`

| Field | Required | Contract |
| --- | --- | --- |
| `externalReference` | yes | The agreement. |
| `atPeriodEnd` | cancel only | Boolean, default `true`. `false` ends the agreement immediately. |
| `idempotencyKey` | no | UUID; the same key repeats the same transition. |

Answer `{ externalReference, status, cancelAtPeriodEnd, effectiveAt, created, idempotencyKey }`.
`409` while a cycle is processing, has an unknown outcome, or a card
replacement is in progress.

- **cancel** with `atPeriodEnd: true` still ends the agreement **at once**
  (`status: "cancelled"`, `effectiveAt` possibly in the past) when a period is
  unpaid — a retry is scheduled, or a submitted variable cycle has not been
  charged yet — or when `nextBillingAt` has already passed. That pending cycle
  becomes `skipped`. A `pending_setup` agreement is always cancelled at once.
  Reusing a cancel key with a different `atPeriodEnd` currently answers
  `502 upstream_error`, not `409`. There is no call to undo a scheduled
  cancellation.
- **pause** is possible from `active` or `past_due` (`409` from
  `pending_setup`, `cancelled` or `completed`); pausing a `paused` agreement
  answers `200` and it stays paused.
- **resume** answers `status: "past_due"` rather than `active` when a period is
  still unpaid, and `409` when the agreement is not paused, its cancellation
  already took effect, or its card credential is no longer usable. It does not
  move `nextBillingAt`: a period that fell due during the pause is charged
  after the resume.

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

`{ externalReference, customerEmail, idempotencyKey?, mode? }` — changes the
address that receives the agreement's notices and receipts. `customerEmail` is
at most 254 chars (trimmed before it is sent; `400 customerEmail_invalid`
when empty or longer). Answer `{ externalReference, customerEmail, status, created, idempotencyKey }`;
an address the platform does not accept is `400 rejected`. Reusing a key with
a different address currently answers `502 upstream_error`. No webhook reports
the change.

## Errors

Errors return a non-2xx status and a JSON body:

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

| `type` | Status | When |
| --- | --- | --- |
| `invalid_request` | `400` | A parameter is missing or invalid — `code` names the field. |
| `authentication` | `401` | The secret key is missing or invalid — or valid but the account is not active (same code, `invalid_api_key`). The `Bearer` scheme is matched case-insensitively. |
| `not_found` | `404` | No such intent, plan or agreement on your account. |
| `forbidden` | `403` | Subscription endpoints: a feature not enabled on the account (`not_enabled`). |
| `conflict` | `409` | Subscription endpoints: the current state does not allow the request (`conflict`) — `message` names the reason. (The intent update's `409 intent_not_updatable` has type `invalid_request`.) |
| `server` | `500` | An unexpected error on our side (`internal_error`). |
| `server` | `502` | Subscription endpoints: the payment platform could not be reached or answered unexpectedly (`upstream_unavailable`, `upstream_error`, `credentials_unavailable`, `processor_unconfigured`). Retry with the **same** `idempotencyKey`; contact support if it persists. `upstream_error` is also what a few bad requests produce at present (listed below) — check the request before retrying. |
| `server` | `503` | Subscription endpoints: `subscriptions_disabled` — not switched on for this platform yet. Not retryable. |

On the subscription endpoints a request the payment platform refuses comes back
as `400` `invalid_request` with code `rejected` and the platform's own message;
field checks made before the call use field codes (`invalid_json`,
`externalReference_invalid`, `mode_invalid`, `idempotencyKey_invalid`,
`idempotencyKey_required`, `expectedVersion_required`,
`expectedVersion_invalid`, `atPeriodEnd_invalid`, `amount_invalid` (only when
`amount` is not a string — a malformed decimal string is `rejected`),
`customerEmail_invalid`, `status_invalid`, `limit_invalid`, `cursor_invalid`,
`body_too_large` — bodies are capped at 16 KB). An unknown plan action
(`/subscription-plans/<anything else>`) is `404 not_found`. `503` `server` /
`subscriptions_disabled` means the subscription endpoints are not switched on
for this platform yet.

How the platform's answer is passed on:

| Platform answer | You receive |
| --- | --- |
| success | Its status and body, plus `idempotencyKey` on a mutation |
| `400` | `400 invalid_request rejected`, with its message |
| `403` | `403 forbidden not_enabled`, with its message |
| `404` | `404 not_found not_found` |
| `409` | `409 conflict conflict`, with its message |
| anything else (`5xx`), no answer within 20 seconds, or an answer that is not JSON | `502 server upstream_error` (its message) or `upstream_unavailable` |

Bad requests that currently come back as `502 upstream_error` instead of a
`4xx`: a plan created again under the same `externalReference` with any
changed fact (`name` included); a plan amount that is not a positive decimal,
or `amount` on a variable plan / `maximumAmount` on a fixed one; a cancel key
reused with a different `atPeriodEnd`; a contact key reused with a different
address.

Two `400 rejected` messages are about your account, not your request:
`processor configuration is unavailable for this merchant` (the `mode` you
used is not set up for your account) and `the selected processor is
unavailable for subscriptions` (or `… for subscription plans`, `… for
subscription billing`: recurring billing is not enabled). Contact support.

`invalid_request` codes on create: `invalid_json`, `amount_invalid`,
`amount_out_of_range`, `currency_unsupported`, `reference_invalid`,
`metadata_invalid`, `metadata_too_large`, `externalid_invalid`,
`notify_url_invalid`, `descriptor_invalid`, `description_invalid`, `theme_invalid`, `mode_invalid`,
and for the subscription object `subscription_invalid`,
`subscription_unknown_field`, `subscription_operation_invalid`,
`subscription_consent_not_accepted_here`, `subscription_plan_invalid`,
`subscription_shopper_invalid`, `subscription_shopper_reference_pii`,
`subscription_reference_invalid`, `subscription_terms_version_invalid`,
`subscription_terms_hash_invalid`, `subscription_terms_text_invalid`,
`subscription_terms_hash_mismatch`, `subscription_billing_anchor_invalid`,
`subscription_billing_anchor_too_soon`, `subscription_billing_timezone_invalid`,
`subscription_surcharge_consent_invalid`,
`subscription_surcharge_consent_unsupported`.

> **Warning:**
The endpoints return no CORS headers — they are designed to be called from your
backend, never from a browser.
