## JavaScript SDK

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

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

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

### `SecurePay(publishableKey)`

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

### `mount(target, options)`

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

Synchronous throws:

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

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

#### Options

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

### The handle

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

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

#### `submit()` resolution

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

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

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

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

#### `validate()`

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

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

### Callbacks and DOM events

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

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

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

#### Success payload

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

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

#### Error payload

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

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

Load errors (sent before any payment):

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

### Lifecycle: the active window

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

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

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

### External submit

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

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

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

### Wallets under an external submit

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

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

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

### Domains

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

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

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

---

## Embedded widget protocol

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

### Iframe

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

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

### Envelope

Every message in both directions:

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

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

### Page → widget

#### `init`

Send it in answer to `ready`:

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

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

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

#### `submit`

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

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

#### `validate`

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

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

#### `set_wallets`

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

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

#### `wallet_capture` / `wallet_abort`

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

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

### Widget → page

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

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

### Active-window rule

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

### Timing of `init`

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

### Load sequence

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

---

## 3-D Secure and wallets in the widget

### Card with 3-D Secure

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

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

#### Timings

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

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

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

### Apple Pay

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

### Google Pay

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

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

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

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

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

### Outcome table

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

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

---

## Sandbox and testing

### Environment

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

### Test cards

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

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

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

### Checklist

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