# Embedded checkout

URL: https://doc.securepayapi.com/embedded-checkout
Last updated: 2026-11-12

> Drop a secure payment widget into your own site and collect cards without handling card data yourself — the iframe and postMessage protocol the SDK is built on.

The embedded widget is an iframe you place on your own page. It collects the
card, runs authentication, and reports the result back to you — card details
never touch your server.

> **Note:**
The fastest way to embed is the [JavaScript SDK](https://doc.securepayapi.com/sdk) — it wraps everything on
this page in a few lines. Read on if you'd rather wire the iframe and
`postMessage` yourself; the protocol below is exactly what the SDK speaks.

## 1. Create a Payment Intent

On your server, [create a Payment Intent](https://doc.securepayapi.com/payment-intents) and keep its
`client_secret`.

## 2. Embed the widget

Add the iframe with your **publishable** key. `allow="payment"` lets the frame
open a wallet payment sheet where one is offered; set it before the frame is
attached.

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

The widget loads only for a known publishable key (an unknown key, or an account
with no registered domain, answers **404** — the frame then posts nothing, not
even `ready`), and it accepts commands only from a page on one of your
**registered domains**: your account's website domain, any extra domains
whitelisted for you, and any subdomain of those — over HTTPS. Elsewhere it
refuses with `origin_not_allowed`. Matching is on the host **including the
port**: a page on a non-standard port matches only an entry registered with that
port. For development, `http://localhost` passes the HTTPS requirement, but it
still has to be registered with its port (`localhost:3000`). A registered
`www.example.com` counts as `example.com`, so the whole apex and its subdomains
are allowed; a host registered as a subdomain allows only that subtree.

## 3. The message envelope

Every message in both directions is an object with a `source` marker, a `type`
and an optional `payload`:

```js
{ source: 'securepay', type: '<name>', payload: { … } }
```

Ignore anything whose `source` is not `'securepay'`, and always check
`e.origin`.

## 4. Initialize it

The widget posts `ready` once loaded. Answer with `init`, carrying the
`client_secret` — over `postMessage` targeted at the securepayAPI origin, never
in the iframe URL:

```js
const iframe = document.querySelector('iframe');
const ORIGIN = 'https://checkout.securepayapi.com';

window.addEventListener('message', (e) => {
  if (e.origin !== ORIGIN || e.source !== iframe.contentWindow) return;
  const d = e.data;
  if (!d || d.source !== 'securepay') return;

  if (d.type === 'ready') {
    iframe.contentWindow.postMessage({
      source: 'securepay',
      type: 'init',
      payload: {
        publishableKey: 'sp_client_…',
        clientSecret: 'pi_…_secret_…',
        loc: location.href,          // your page URL — see below
        submitMode: 'internal',      // or 'external'
        theme: 'light',              // optional: overrides the intent's theme
        collectEmail: true           // false hides the email field
      }
    }, ORIGIN);
  }
});
```

| `init` field | Required | Description |
| --- | --- | --- |
| `publishableKey` | no | Your `sp_client_…` key. The SDK sends it; the widget identifies your account from the iframe URL's `pk`, so this field is informational. |
| `clientSecret` | yes | From your Payment Intent. An `init` without it is ignored; the first `init` that carries one is the one the widget takes, and later `init` messages are ignored. |
| `loc` | yes | The URL of **your page** (the top window). The iframe cannot read it cross-origin, and the payment platform needs it to allow its 3-D Secure page to be framed inside yours and to validate Apple Pay. Not enforced by the protocol, but without it the widget falls back to its own URL and challenges and Apple Pay fail. |
| `submitMode` | no | `internal` (default): the widget shows its own pay button. `external`: no button; you start the payment with the `submit` command. |
| `theme` | no | `light` or `dark`. Overrides the intent's `theme`. |
| `collectEmail` | no | `false` hides the email field. Ignored for a subscription, where the email is required. |
| `mode` | no | Legacy. `sandbox` makes the widget refuse a **live** intent with `mode_mismatch`; it never selects the environment. |
| `wallets` | no | `true` offers Apple Pay / Google Pay in `external` submit mode (off there by default). The buttons stay disabled until you send `set_wallets { enabled: true }`, and the widget asks you with `wallet_authorized` before it charges — see below. |

Send `init` as soon as you receive `ready`: if none has arrived **8 seconds**
after the widget loaded, it shows a blank frame until one does. `ready`,
`resize` and an `origin_not_allowed` error are posted to any origin (they carry
no secret); after an accepted `init`, every message targets the exact origin
`init` came from. A frame that reloads posts `ready` again and needs a new
`init`.

> **Note:**
Testing? Create the Payment Intent with `mode: 'sandbox'` (on your server) —
the intent decides, not the widget. See **[Sandbox](https://doc.securepayapi.com/sandbox)**.

## 5. Handle the result

The widget posts these messages back to your page (same envelope):

| `type` | `payload` | Meaning |
| --- | --- | --- |
| `ready` | — | The widget has loaded; send `init`. |
| `resize` | `{ height }` | Set the iframe to this height (px). |
| `payment_started` | `{ method, reference? }` | A payment is now **active** inside the frame: a wallet sheet opened (`method: "applepay"` \| `"googlepay"`) or the card flow started (`"card"`). `reference` is the payment platform's reference for a wallet attempt. |
| `processing` | `{ method, stage, reference? }` | Progress while active. Apple Pay `stage`: `validated`, `authorizing`, `authorized`. Google Pay `stage`: `authorizing`, `authenticating`. For `card` it is the status text the customer sees (free text — do not match on it). Informational. |
| `payment_ended` | `{ method, outcome, reference? }` | The active payment ended **without** a capture: `outcome` is `"cancelled"` (the customer closed the sheet, the sheet could not complete, or you aborted — nothing else follows), `"failed"` (declined — an `error` follows) or `"pending"` (a wallet outcome still open — a `success` with `status: "pending"` follows). A capture ends with `success` alone, and so does a card payment whose outcome is pending. The card flow's messages carry no `reference`. |
| `success` | `{ intentId, status, reference?, subscription?, submitId? }` | The payment was captured (`status: "succeeded"`) — **or** accepted with its outcome still open (`status: "pending"`: do not ask for money again). `subscription` is present for a recurring setup: `{ status: "pending_activation", externalReference }`. |
| `error` | `{ message, code?, reference?, method?, submitId? }` | The payment failed, a command was refused, or the widget could not load (`origin_not_allowed`, `mode_mismatch`, `intent_not_payable`; an unresolvable client secret or a server failure has no `code` — message `intent not found` or `Service unavailable`). For a declined wallet payment, `reference` names the declined attempt. Refusals carry no `method`. |
| `wallet_authorized` | `{ id, method, reference }` | `init` with `wallets: true` and `submitMode: 'external'` only. The customer approved in the wallet sheet; **nothing has been charged**. Answer within **18 s (Apple Pay) or 30 s (Google Pay)** with `wallet_capture { id }` to charge or `wallet_abort { id, message? }` to end the attempt with nothing moved (the message, up to 300 characters, is shown in the frame). No answer is an abort. |
| `validated` | `{ id, ok, message? }` | The answer to your `validate` command (below): `ok: false` with a `message` when the customer still has to complete the form. |

And two more commands you send in that mode: `set_wallets { enabled }` releases
or holds the wallet buttons (they start held, with a "complete your details"
hint), and `wallet_capture` / `wallet_abort` answer a `wallet_authorized`. All
three are accepted only from the origin that sent `init`.

> **Warning:**
**While a payment is active — from `payment_started` until `payment_ended`,
`success` or `error` — do not remove or re-create the iframe, change its
`client_secret`, or navigate.** A wallet sheet and a 3-D Secure challenge live
inside the frame; tearing it down kills them, and the payment the widget had
prepared is left behind unfinished (the platform then shows it as initialised
with no provider). A checkout that creates a new Payment Intent on every cart
change must defer that until the active payment has ended.

```js
  if (d.type === 'resize')  iframe.style.height = Math.max(80, d.payload.height) + 'px';
  if (d.type === 'success') { /* d.payload.intentId → confirm on your server */ }
  if (d.type === 'error')   { /* show d.payload.message */ }
```

Then [confirm the intent on your server](https://doc.securepayapi.com/payment-intents#confirm-the-payment-on-your-server)
before you fulfil — the browser's `success` is not evidence.

### Message order

What your page receives for each kind of attempt (`processing` messages may
repeat and are left out where they add nothing):

| Attempt | Messages | Intent on your server |
| --- | --- | --- |
| Card, approved | `payment_started` → `processing`… → `success { status: "succeeded" }` | `succeeded` |
| Card, charge outcome open | `payment_started` → `processing`… → `success { status: "pending" }` | `processing` — never paid, never unpaid |
| Card, declined at the charge | `payment_started` → `processing`… → `payment_ended { outcome: "failed" }` → `error` | `failed` (retryable) |
| Card, 3-D Secure failed, abandoned or timed out | `payment_started` → `processing`… → `payment_ended { outcome: "failed" }` → `error` | `requires_payment` — nothing charged |
| Wallet, sheet closed | `payment_started` → (`processing`) → `payment_ended { outcome: "cancelled" }` | `requires_payment` |
| Wallet, paid | `payment_started` → `processing`… → `success { status: "succeeded" }` | `succeeded` |
| Wallet, outcome open | `payment_started` → `processing`… → `payment_ended { outcome: "pending" }` → `success { status: "pending" }` | `processing`, or `requires_payment` when the authorisation itself is open — do not ask for money again |
| Wallet, declined | `payment_started` → `processing`… → `payment_ended { outcome: "failed" }` → `error { method, reference }` | `requires_payment` |
| Wallet, you aborted (`wallet_abort` or silence) | `payment_started` → `processing { stage: "authorizing" }` → `wallet_authorized` → `payment_ended { outcome: "cancelled" }` | `requires_payment` |
| `submit` refused | `error { message, submitId }` only | unchanged |

> **Warning:**
**Known issue — Google Pay with a redirect for 3-D Secure.** When the
customer's bank answers a Google Pay payment with a redirect, the charge is
completed outside the widget's flow. The money can be taken while the intent
stays `requires_payment`, and your page may receive no `success` at all (the
last message is `processing { stage: "authenticating" }`). For an intent that
stays `requires_payment` after the customer approved a wallet payment, check the
transaction —
`GET https://app.securepayapi.com/api/v1/transactions/{transaction_reference}`
— or the dashboard before asking for another payment.

## 6. External submit (optional)

With `submitMode: 'external'` your own button starts the payment. Send a
`submit` command with an id of your choosing; the one `success` or `error` that
answers it echoes the same `submitId`:

```js
iframe.contentWindow.postMessage(
  { source: 'securepay', type: 'submit', payload: { id: 'order-123-try-1' } },
  ORIGIN
);
```

A `submit` is accepted only from the origin that sent `init`; one with a missing
or empty `id` is silently ignored. It is refused — with an `error` carrying your
`submitId` — while the widget is still loading or unavailable (the message then
says why), while another payment is in flight, after the payment is complete,
while a wallet payment is "being confirmed", when the email or card fields are
incomplete, or, for a subscription, until the customer has ticked the consent
box. The exact messages are listed on the [SDK page](https://doc.securepayapi.com/sdk#the-result).

### Check the form first (`validate`)

A checkout that creates its order before charging can ask whether the form is
filled in, without starting anything:

```js
iframe.contentWindow.postMessage(
  { source: 'securepay', type: 'validate', payload: { id: 'check-1' } },
  ORIGIN
);
// → { source: 'securepay', type: 'validated', payload: { id: 'check-1', ok: true } }
// → …or { id: 'check-1', ok: false, message: 'Please complete the card details.' }
```

`ok` is `false` only for what the customer can fix in the form — a missing card
field, a missing or malformed email, an unticked subscription consent box, or a
form still loading; the message is shown in the frame too. A payment that is
already complete, being confirmed or no longer payable answers `ok: true`: that
is for your server to resolve by reading the intent, and `submit` still refuses
it. Like `submit`, the command is accepted only from the origin that sent
`init`, and one without an `id` is ignored. Nothing is sent to the payment
platform.

## Subscriptions

When the intent carries a [`subscription`](https://doc.securepayapi.com/payment-intents#recurring-payments-subscriptions),
the widget renders the recurring-payment badge, the first charge and billing
start, the consent text and checkbox itself, requires the email and offers no
wallets. Nothing changes in your integration except the `subscription` field on
`success`.

## Theming

Set `theme` (`light` or `dark`) when you
[create the Payment Intent](https://doc.securepayapi.com/api-reference#create-a-payment-intent), or override
it per page in `init`. The frame's background is transparent; the widget draws
its own card.
