# JavaScript SDK

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

> Drop in our JavaScript SDK to embed checkout in a few lines — options, results, external submit for store checkouts, and subscriptions.

The securepayAPI JavaScript SDK is the quickest way to add embedded checkout to
your page. It creates the secure iframe, wires up the messaging, and hands you
simple callbacks — you create a payment on your server and call `mount`.

## Install

```html
<script src="https://checkout.securepayapi.com/sdk/v1/securepay.js"></script>
```

It exposes a single global: `SecurePay`.

## Quick example

```html
<script src="https://checkout.securepayapi.com/sdk/v1/securepay.js"></script>
<div id="pay"></div>

<script>
  var sp = SecurePay('sp_client_…');           // your publishable key
  sp.mount('#pay', {
    clientSecret: 'pi_…_secret_…',              // from your backend
    onSuccess: function (r) { /* r = { intentId, status, reference } */ },
    onError:   function (e) { /* e = { code, message } */ }
  });
</script>
```

First, [create a Payment Intent](https://doc.securepayapi.com/payment-intents) on your server and pass the
returned `client_secret` to `mount`. When the widget reports success, have your
server [confirm the intent](https://doc.securepayapi.com/payment-intents#confirm-the-payment-on-your-server)
before you fulfil.

## API

### `SecurePay(publishableKey)`

Creates an SDK instance. Pass your **publishable** key (`sp_client_…`). Works
with or without `new`. Throws `SecurePay: a publishable key is required` if the
key is missing or not a string.

The key only selects your account; it is not checked until the iframe loads. An
unknown key (or an account with no registered domain) makes the iframe answer
**404** — the widget then never posts anything, so **no callback fires at all**.
A widget that never calls `onReady` is a wiring problem, not a decline.

### `instance.mount(target, options)`

Renders the checkout into `target` — a CSS selector string or a DOM element —
and returns a handle (below).

| Option | Type | Required | Description |
| --- | --- | --- | --- |
| `clientSecret` | string | yes | The `client_secret` from your Payment Intent. |
| `theme` | `'light'` \| `'dark'` | no | Colour scheme for this page. Overrides the `theme` set on the intent — a store's scheme belongs to the store, not to one payment. |
| `email` | boolean | no | `false` hides the widget's email field, for a checkout that already has the customer's email or needs no receipt. Ignored for a [subscription](#subscriptions), where the email is required. |
| `submitMode` | `'internal'` \| `'external'` | no | `external` hides the widget's own pay button so your page's button stays the only one; you then start the payment with `handle.submit()`. See [External submit](#external-submit-for-store-checkouts). |
| `onReady` | function | no | Called when the iframe has loaded and the SDK has handed it the `clientSecret`. The intent is fetched and checked **after** this, so an `onError` (`origin_not_allowed`, `mode_mismatch`, `intent_not_payable`, a load failure) can still follow. |
| `onActive` | function | no | Called with `true` when a payment becomes active inside the frame (a wallet sheet or 3-D Secure opened) and `false` when it ends. **While active, do not unmount the widget, change its `clientSecret` or navigate** — see [Lifecycle](#lifecycle-do-not-tear-the-widget-down-mid-payment). |
| `onSuccess` | function | no | Called with the [result](#the-result) when the payment is captured — or accepted with an outcome still pending. |
| `onError` | function | no | Called with `{ message, code?, reference?, method?, submitId? }` when a payment fails or the widget cannot load. `reference` names a declined wallet attempt; `submitId` echoes the `submit()` the error answers. |
| `wallets` | boolean | no | External submit mode only: `true` offers Apple Pay / Google Pay above the card form, which by default that mode does not. See [Wallets under your own button](#wallets-under-your-own-button). |
| `onWalletAuthorize` | function | no | With `wallets: true`: called with `{ method, reference }` after the customer approved in the wallet sheet and **before anything is charged**. Return exactly `true` (or a Promise of it) to capture; anything else — `false`, `undefined`, a forgotten `return`, a rejection, a throw — aborts with nothing moved. Answer within **18 s for Apple Pay, 30 s for Google Pay**. Without it an opted-in host captures at once. |

`mount({ mode })` is a legacy option: live vs sandbox is decided by the intent.
Passing `mode: 'sandbox'` only acts as a guard — the widget refuses to load on a
live intent and reports `mode_mismatch` instead of taking a real payment.

### The handle

```js
var handle = sp.mount('#pay', { clientSecret: 'pi_…_secret_…' });
handle.submit();   // start the payment (meant for submitMode 'external') → Promise
handle.validate(); // is the card form filled in? starts nothing → Promise
handle.setWalletsEnabled(bool); // release / hold the wallet buttons (wallets: true)
handle.destroy();  // remove the iframe and its listeners
```

`mount()` throws synchronously when the target element is not found
(`SecurePay: mount target not found`) or `clientSecret` is missing
(`SecurePay: opts.clientSecret is required`). Passing `mode` logs a console
warning (see `mode` above). `submit()` rejects at once with
`"SecurePay: the payment form is not ready yet"` before `onReady`; the widget
does not refuse it in internal mode, but there it competes with the widget's own
button. `destroy()` rejects any `submit()` or `validate()` still pending
(`"SecurePay: the widget was destroyed"`), so nothing awaiting the widget can
hang. A mounted widget takes its intent **once**: to pay a different intent,
`destroy()` and `mount()` again — a second `init` on the same frame is ignored.

### `handle.validate()`

Asks whether the customer still has something to do in the form — **without
starting a payment and without sending anything to the payment platform**. Use
it when your checkout creates its order before it charges: check the card
first, so an empty card form does not leave an unpaid order behind.

```js
placeOrderButton.onclick = function () {
  widget.validate()
    .then(createOrder)                       // the form is filled in
    .then(function () { return widget.submit(); })
    .then(confirmOnServer)
    .catch(function (e) { showError(e.message); });
};
```

- It **rejects** only for what the customer can put right in the form: a
  missing card field (`Please complete the card details.`), a missing or
  malformed email when the email field is shown, an unticked subscription
  consent box, or a form that has not finished loading. The same message is
  shown inside the frame.
- It **resolves** `true` otherwise — including when the payment is already
  complete, is being confirmed, or can no longer be paid. Those are states of
  the payment, not of the form: your server finds them out when it reads the
  intent back, as it must anyway. `submit()` still refuses them.
- It is a courtesy check, not a guarantee the payment will go through, and it
  never blocks a checkout: with no answer from the frame within 3 s it resolves
  `true`. Before `onReady` it rejects with
  `"SecurePay: the payment form is not ready yet"`; a negative answer without
  a message rejects with `"The payment form is not complete"`.

## The result

Outcomes arrive **two ways** — use whichever fits your code.

**1. Callbacks** passed to `mount`:

```js
sp.mount('#pay', {
  clientSecret: 'pi_…_secret_…',
  onSuccess: function (r) { window.location = '/thank-you?i=' + r.intentId; },
  onError:   function (e) { showError(e.message); }
});
```

**2. DOM events** on `window` (fire regardless of the callbacks):

```js
window.addEventListener('securepay:success', function (e) { /* e.detail */ });
window.addEventListener('securepay:error',   function (e) { /* e.detail */ });
```

The `success` payload:

| Field | Description |
| --- | --- |
| `intentId` | The Payment Intent id — what your server [reads back](https://doc.securepayapi.com/payment-intents#confirm-the-payment-on-your-server). |
| `status` | `"succeeded"`, or `"pending"` when the payment was **accepted but its outcome is not settled yet**. |
| `reference` | The payment platform's transaction reference, when known. |
| `subscription` | Present for a [subscription](#subscriptions) setup: `{ status: "pending_activation", externalReference }`. |
| `submitId` | Echo of the `submit()` command this answers (external mode). |

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

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

> **Warning:**
Treat `status: "pending"` as **"do not ask for money again"**: the money may be
moving and a second attempt could take it twice. Show "payment is being
confirmed", then let your server read the intent until it settles.

The `error` payload is `{ message, code?, reference?, method?, submitId? }`.
Codes you may see before any payment: `origin_not_allowed` (the page is not on
one of your registered domains), `mode_mismatch`, `intent_not_payable` (message
`This payment session has expired.` — the intent expired, is already paid, or
already had a charge sent whose outcome is still open; your server reads the
intent to tell which). A client secret the widget cannot resolve (mistyped,
another account's) or a server failure arrives as an `error` with **no code**
and the message `intent not found` or `Service unavailable`. Payment declines
also carry no code — show `message`, and do not parse it.

When a `submit()` is refused, the promise rejects with one of these messages
(the `Error` also carries `.code` and `.payload` when present). A refusal
arrives as an ordinary `error` message, so `onError` and `securepay:error` fire
for it as well:
`The payment form is not ready yet.` (or the reason the widget is unavailable),
`A payment is already in progress.`, `This payment is already complete.`,
`This payment is being confirmed.`, `Please enter a valid email address.`,
`Please complete the card details.`,
`Please accept the subscription terms to continue.`. The field refusals are
shown inline in the frame as well.

Timeouts the card flow enforces, reported as an `error`: 120 s for the
authentication to start (`Payment timed out. Please try again.`), 15 min for an
unanswered 3-D Secure challenge
(`The authentication step timed out. Please try again.`), 5 min of
post-challenge confirmation polling
(`Your payment is still being confirmed. Please try again in a moment.` — the
authentication did not settle, and no charge was sent). A `status: "pending"`
outcome is remembered in the browser per intent for up to one hour, where the
browser allows storage: remounting the widget on that intent shows "Payment is
being confirmed" instead of the form. Do not rely on that memory — your server
is what keeps the customer from paying twice.

## Lifecycle — do not tear the widget down mid-payment

A wallet sheet (Apple Pay, Google Pay) and a 3-D Secure challenge run **inside
the iframe**. If your page removes or re-creates the widget, or hands it a new
`clientSecret`, while one is open, the sheet dies with the frame and the payment
the widget had already prepared is left behind — the platform shows it as
initialised with no provider, and the customer sees nothing happen.

The SDK tells you when that window is open:

```js
var paymentActive = false;
sp.mount('#pay', {
  clientSecret: cs,
  onActive: function (active) { paymentActive = active; }
});

// in your cart / checkout code:
function onCartChanged() {
  if (paymentActive) return queueUntilInactive(onCartChanged);  // never remount now
  createNewIntentAndRemount();
}
```

`onActive(true)` fires on `payment_started` (a sheet opened, or the card flow
started); `onActive(false)` fires on `payment_ended`, `success` or `error`. It
fires only on a change, and `destroy()` does not call it. The same transitions
are available as DOM events on `window`, with the message payload in
`event.detail`: `securepay:payment_started`, `securepay:processing`,
`securepay:payment_ended`, and `securepay:wallet_authorized` (see
[Wallets under your own button](#wallets-under-your-own-button)). The order of
messages for each kind of payment is listed on the
[embedded checkout](https://doc.securepayapi.com/embedded-checkout#message-order) page.

Creating a new Payment Intent for every cart edit is fine — but apply it only
when no payment is active, and keep the previous widget mounted until then.

## External submit for store checkouts

A store checkout already has its own "Place order" button, and it has to stay
the only one. Mount with `submitMode: 'external'`, then start the payment from
your own submit handler:

```js
var widget = sp.mount('#pay', { clientSecret: cs, submitMode: 'external' });

placeOrderButton.onclick = function () {
  widget.submit().then(function (r) {
    // r = { intentId, status, reference } — paid (or pending).
    // Have your server confirm the intent, then place the order.
  }).catch(function (e) {
    // e.message — show it and keep the buyer on the checkout page.
  });
};
```

`submit()` settles exactly once per call and has **no timeout**: a 3-D Secure
challenge legitimately takes minutes, so the promise stays pending until the
payment really resolves. Calling it again while one is in flight rejects with
"A payment is already in progress". Wallet buttons are not shown in external
mode unless you opt in with `wallets: true` — a wallet payment started inside
the frame answers no `submit()`, so you handle it through `onWalletAuthorize`
and `onSuccess` instead (see [Wallets under your own button](#wallets-under-your-own-button)).

## Subscriptions

When the intent carries a [`subscription`](https://doc.securepayapi.com/payment-intents#recurring-payments-subscriptions),
the widget handles the setup by itself: it shows a recurring-payment badge, the
first charge and when billing starts, the full consent text and a checkbox, and
keeps the pay button disabled until the customer agrees. The email field is
always shown (the platform sends renewal notices to it), and wallets are not
offered. In external mode, `submit()` rejects until the customer has ticked the
box — your button cannot consent on their behalf.

The `success` result then includes
`subscription: { status: "pending_activation", externalReference }`. The payment
is captured; the agreement is activated by the payment platform moments later.
Do not treat it as active until you have read it with your API secret or
received its webhook.

## Wallets

Where the device supports it, the widget offers one wallet above the card form —
**Apple Pay** where the browser reports Apple Pay support (Safari on an Apple
Pay–capable device), **Google Pay** on every other device where Google reports
readiness — and the card form stays either way. A device never gets both. The SDK sets `allow="payment"` on the iframe, which a cross-origin
frame needs to open a payment sheet. Apple Pay additionally requires the domain
of the page that embeds the widget to be registered for Apple Pay on your
account; ask us to add it. Wallets are never offered for a
[subscription](#subscriptions) setup, and in external submit mode only when you
opt in (below).

A wallet result reaches you through `onSuccess` / `onError` like a card one. Two
wallet cases need care on your server:

- **Apple Pay `status: "pending"`** can mean the authorisation itself is still
  open, in which case no charge was sent and the intent still reads
  `requires_payment`. Do not ask for another payment; check the transaction
  (below) or the dashboard first.
- **Google Pay with a bank redirect for 3-D Secure (known issue).** When the
  bank sends the customer through a redirect, the charge is completed outside
  the widget's own flow: the money can be taken while the intent stays
  `requires_payment`, and the widget may report no final outcome. 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.

## Wallets under your own button

In `submitMode: 'external'` the wallets are off by default: a wallet payment
starts when the customer taps the wallet button inside the frame, not your
"Place order", so it answers no `submit()` and a store that is not prepared for
that would take the money without an order. Opt in with `wallets: true` and give
the widget two things:

```js
var widget = sp.mount('#pay', {
  clientSecret: cs,
  submitMode: 'external',
  wallets: true,
  // The customer approved in the sheet. Nothing has been charged yet. Create
  // your pending order now; resolve exactly true to capture — anything else
  // aborts with nothing moved. You have 18 s (Apple Pay) or 30 s (Google Pay).
  onWalletAuthorize: function (info) {          // info = { method, reference }
    return createPendingOrder().then(function () { return true; });
  },
  // Fires for card and wallet alike. For a wallet this is where you finish the
  // order: confirm the intent on your server, then redirect.
  onSuccess: function (r) { finishOrder(r.intentId); },
  onError:   function (e) { showError(e.message); }   // e.method says which wallet
});

// Hold the buttons until your form is complete; release them when it is.
widget.setWalletsEnabled(formIsComplete());
```

- The buttons are shown **disabled**, with a "complete your details" hint, until
  you call `setWalletsEnabled(true)`. Call it again with `false` when a required
  field is cleared. Safe to call before `onReady`.
- `onWalletAuthorize` runs inside the wallet's own window: for Apple Pay about
  30 s between approval and completion, in which the authorisation and capture
  still have to fit. The widget waits **18 s for Apple Pay** and **30 s for
  Google Pay**; no answer by then counts as abort, with nothing charged. A store
  that validates its whole checkout and creates the order in this window should
  keep that step well inside the budget.
- An abort ends the attempt with nothing charged (Apple Pay's sheet closes with
  a failure; Google Pay's sheet has already closed) and posts `payment_ended
  { outcome: "cancelled" }` — no `error`. The message of a rejected Promise
  (up to 300 characters) is shown inside the frame; a timeout or any other
  answer shows `The store did not confirm the order in time. Nothing was
  charged — please try again.` The customer can try again or pay by card. If
  you created an order before aborting, it stays unpaid — cancel or reuse it.
- `payment_started` has already fired when the sheet opened, and `processing`
  (`stage: "authorizing"`) just before `onWalletAuthorize`. After `true`, the
  attempt ends with `success` (`status: "succeeded"` or `"pending"`) or with
  `payment_ended { outcome: "failed" }` followed by `error`, `method` set to the
  wallet. A wallet `success` carries no `submitId` and settles no `submit()`.

## How it works

- The card form runs inside an **iframe served by securepayAPI**, so raw card
  details never touch your page or your server.
- Your `client_secret` is passed to the widget over `postMessage` (targeted at
  the securepayAPI origin) — never placed in the iframe URL.
- The widget accepts that message only from a page on one of your
  **registered domains** (your account's website domain, any extra domains
  whitelisted for you, and their subdomains, over HTTPS). For local development
  `http://localhost` is accepted too, but only when it is registered — and with
  the same port: a page on `localhost:3000` needs `localhost:3000` registered.
  Otherwise the widget refuses with `origin_not_allowed`.
- The SDK auto-resizes the iframe to fit its content.
- 3-D Secure runs inside the widget — see [3-D Secure](https://doc.securepayapi.com/authentication-3ds). The
  buyer is never redirected.

> **Note:**
Want full control instead? The SDK is a thin wrapper over the
[embedded checkout](https://doc.securepayapi.com/embedded-checkout) `postMessage` protocol — you can
integrate against that directly.
