# Checkout

The shopper pays on OnCharge's checkout page. Your server creates a **checkout session**, and you show the session's checkout page in one of five ways:

| Option | Best for |
|---|---|
| [Hosted redirect](#hosted-redirect) | The fastest integration. Works everywhere, including in-app browsers. |
| [Embedded iframe](#embedded-iframe) | Keeping the shopper on your checkout page, with no JavaScript library. |
| [Script tag](#script-tag) | Embedding on any site with automatic resizing and events. |
| [React component](#react) | React apps. |
| [Next.js](#nextjs) | Next.js App Router stores. |

Whichever you choose, the payment is confirmed on your server by a [webhook](https://oncharge.io/docs/webhooks), never by the browser.

## Create a checkout session

Call [`POST /api/v1/checkout/sessions`](https://oncharge.io/docs/api#createcheckoutsession) from your server (see [Authentication](https://oncharge.io/docs/authentication) for signing).

| Field | Required | Notes |
|---|---|---|
| `amount` | Yes | Integer in minor units (`4900` = $49.00). |
| `currency` | Yes | ISO 4217 code, e.g. `USD`. |
| `reference` | Yes | Your order number or cart ID, up to 255 characters. Returned in webhooks. |
| `return_url` | Yes | Where the shopper goes after checkout. Must be on a registered store domain. |
| `order_id` | No | Your order ID if the order already exists. Otherwise [attach it later](#create-the-session-before-the-order-exists). |
| `customer_email`, `customer_phone` | No | Used for fraud screening and receipts. Phone in E.164 (`+15551234567`). |
| `shipping` | For physical goods | `name`, `line1`, `line2`, `city`, `state`, `postal_code`, `country`. The payout is released after the carrier confirms delivery to this address. It cannot be changed later. |
| `line_items` | No | `[{ description, quantity, amount_including_tax }]`. |
| `metadata` | No | Your own key-value data. |

Send an `Idempotency-Key` header (your order or cart ID) so retries return the same open session.

If OnCharge has closed your store to new payments (for example while the account is being offboarded), session creation fails with `403 store_checkout_closed` and sessions that are already open can no longer be paid; the checkout shows the shopper an error. The rest of the API keeps working, so you can still report shipments and refund paid orders.

```json title="201 Created"
{
  "session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
  "status": "created",
  "iframe_url": "/checkout/8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11?token=pt_eyJ…",
  "pay_token": "pt_eyJ…",
  "created_at": "2026-01-01T00:00:00.000Z",
  "expires_at": "2026-01-01T00:30:00.000Z"
}
```

`iframe_url` is a path. The **checkout URL** is `https://app.oncharge.io` followed by `iframe_url`; the Node SDK returns it ready-made as `checkout_url`, and `@oncharge/js` accepts either. It already contains the short-lived `pay_token`, so pass it to the browser as-is and create a new session if the shopper comes back after 30 minutes.

## Hosted redirect

Send the shopper to the checkout URL with a `303` redirect (or a link). They pay on OnCharge's page and are returned to your `return_url`.

```ts title="server"
const session = await oncharge.checkout.sessions.create(params, { idempotencyKey: order.id });
return Response.redirect(session.checkout_url, 303);
```

```php title="PHP"
$session = oncharge_request('POST', '/api/v1/checkout/sessions', $params, $orderId);
header('Location: https://app.oncharge.io' . $session['iframe_url'], true, 303);
exit;
```

On the `return_url` page, look the order up on your server. Do not mark it paid because the shopper arrived there; wait for the `payment.captured` webhook or check [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession).

## Embedded iframe

Put the checkout in an iframe on a page served from one of your store's registered domains (merchant portal → **Security → Domains**). The checkout's `Content-Security-Policy: frame-ancestors` lists exactly those domains over HTTPS; any other page, and any request whose token or session cannot be resolved, is refused (`frame-ancestors 'none'`). A registered `localhost` may frame the checkout from any port for local development. Full-page use is never affected.

Add three query parameters to the checkout URL when you embed it:

| Parameter | Value |
|---|---|
| `embed` | `1`. The checkout shows its own pay button, and links that would leave the frame become `redirect` messages. |
| `parent_origin` | Your page's origin, e.g. `https://shop.example.com`. Messages are only addressed to it if it is one of your store's origins. |
| `embed_nonce` | A fresh random value per page load, 16–128 characters of `A-Z a-z 0-9 _ -`. Every message echoes it. |

```html title="checkout.html"
<div id="oncharge-checkout"></div>

<script>
  const CHECKOUT_URL = 'https://app.oncharge.io/checkout/8b0f6f2e-…?token=pt_…'; // from your server
  const checkoutUrl = new URL(CHECKOUT_URL);
  const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join('');
  checkoutUrl.searchParams.set('embed', '1');
  checkoutUrl.searchParams.set('parent_origin', window.location.origin);
  checkoutUrl.searchParams.set('embed_nonce', nonce);

  const frame = document.createElement('iframe');
  frame.src = checkoutUrl.toString();
  frame.title = 'Secure checkout';
  frame.allow = 'payment';
  frame.referrerPolicy = 'origin';
  frame.style.cssText = 'width:100%;height:480px;border:0;display:block';
  document.getElementById('oncharge-checkout').appendChild(frame);

  window.addEventListener('message', (event) => {
    // Trust only the checkout iframe, at the checkout's origin, with this load's nonce.
    if (event.origin !== checkoutUrl.origin || event.source !== frame.contentWindow) return;
    const msg = event.data;
    if (!msg || msg.source !== 'oncharge-checkout' || msg.version !== 1 || msg.nonce !== nonce) return;

    if ((msg.type === 'ready' || msg.type === 'resize') && typeof msg.height === 'number') {
      frame.style.height = `${Math.max(480, Math.ceil(msg.height))}px`;
    }
    if (msg.type === 'complete') {
      // A signal for the shopper's journey, not proof of payment: confirm on your server.
      window.location.href = `/checkout/complete?session=${encodeURIComponent(msg.sessionId)}`;
    }
    if (msg.type === 'error') console.warn('Checkout error:', msg.status, msg.message);
    if (msg.type === 'redirect') window.location.assign(msg.url);
  });
</script>
```

### Messages from the checkout

The checkout posts messages to the parent window, only at your store's own origins (never `*`):

```json
{ "source": "oncharge-checkout", "version": 1, "type": "complete", "sessionId": "8b0f6f2e-…", "nonce": "<your embed_nonce>", "status": "captured" }
```

| `type` | Fields | When |
|---|---|---|
| `ready` | `height` | The payment form is shown (once per load). |
| `resize` | `height` (CSS pixels) | The content height changed. |
| `complete` | `status`: `captured` or `authorized` | The payment succeeded. |
| `error` | `message`, `status`: `refused` or `error` | The payment failed or the form could not load. |
| `redirect` | `url` | The checkout wants to leave the frame (embed mode); navigate the top window there. |

Accept a message only when `event.origin` is the checkout's origin, `event.source` is the checkout iframe's window, `source` and `version` match, and `nonce` equals the `embed_nonce` you passed. `@oncharge/js` does all of this for you.

## Script tag

The hosted script adds `window.OnCharge.mountCheckout`: it builds the iframe with the parameters above, checks every message, resizes the frame and turns the messages into callbacks.

```html title="checkout.html"
<div id="oncharge-checkout"></div>
<script src="https://app.oncharge.io/js/v1/oncharge.js"></script>
<script>
  const checkout = window.OnCharge.mountCheckout('#oncharge-checkout', {
    url: CHECKOUT_URL, // session.checkout_url (or iframe_url), from your server
    onReady: () => console.log('checkout ready'),
    onComplete: ({ sessionId, status }) => {
      window.location.href = `/checkout/complete?session=${encodeURIComponent(sessionId)}`;
    },
    onError: ({ message, status }) => console.warn('Checkout error:', status, message),
    // onRedirect defaults to navigating this window; pass one to handle it yourself.
  });

  // Later, e.g. when the shopper goes back to edit the cart:
  // checkout.destroy();
</script>
```

With a bundler, use the npm package instead (same options):

```js
import { mountCheckout } from '@oncharge/js';

const checkout = mountCheckout('#oncharge-checkout', { url: checkoutUrl, onComplete: ({ sessionId }) => { /* … */ } });
```

> **Coming soon to npm.** `@oncharge/js` is not yet published. The hosted script above is the same code; until the package is out, use the script tag or the [plain iframe](#embedded-iframe).

| Option | Type | Default | Purpose |
|---|---|---|---|
| `url` | string | (required) | The session's `checkout_url`, or its `iframe_url` resolved against `baseUrl`. Must be HTTPS. |
| `baseUrl` | string | `https://app.oncharge.io` | Used to resolve a relative `url`. |
| `onReady` | `() => void` | | The payment form is shown. |
| `onComplete` | `({ sessionId, status }) => void` | | The payment succeeded (`status` is `captured` or `authorized`). Confirm on your server before fulfilling. |
| `onError` | `({ message, status? }) => void` | | The payment failed (`status: 'refused'`) or the form could not load. |
| `onRedirect` | `({ url }) => void` | navigate the top window | The checkout wants to leave the frame. |
| `autoResize` | boolean | `true` | Follow the checkout's content height. |
| `minHeight` | number | `480` | Minimum iframe height in pixels. |
| `title` | string | `Secure checkout` | Accessible title of the iframe. |

`mountCheckout(target, options)` takes a CSS selector or an element and returns `{ iframe, sessionId, destroy() }`; `destroy()` removes the iframe and its listener and is safe to call twice.

## React

```tsx title="Checkout.tsx"
import { OnChargeCheckout } from '@oncharge/js/react';

export function Checkout({ checkoutUrl }: { checkoutUrl: string }) {
  return (
    <OnChargeCheckout
      url={checkoutUrl}
      className="w-full"
      onComplete={({ sessionId }) => {
        window.location.href = `/checkout/complete?session=${encodeURIComponent(sessionId)}`;
      }}
      onError={({ message }) => console.warn(message)}
    />
  );
}
```

`<OnChargeCheckout>` takes the same options as `mountCheckout` as props, plus `className` and `style` for its container. It remounts the iframe only when `url`, `baseUrl`, `minHeight`, `autoResize` or `title` change; callbacks can change on every render. Your React app gets `checkoutUrl` from your own backend endpoint, which creates the session. See the [React guide](https://oncharge.io/docs/react).

## Next.js

Create the session in a server action or route handler and render the component in a client component. The [Next.js guide](https://oncharge.io/docs/nextjs) has the full code, including the webhook route.

## Create the session before the order exists

Many checkouts show the payment form before the order is saved (WooCommerce does this). Create the session from the cart with `reference` set to your cart ID and the cart ID as the idempotency key. When the shopper places the order, attach it:

```http
POST /api/v1/checkout/sessions/{session_id}/order
{ "order_id": "1001", "shipping": { "name": "Alex Rivera", "line1": "500 Market St", "city": "San Francisco", "state": "CA", "postal_code": "94105", "country": "US" } }
```

Each value is recorded once. The shipping address is accepted only while the session has none, no tracking has been reported, and the session is less than 24 hours old. The response tells you what is on file (`shipping_recorded`, `shipping_on_file`).

## Content Security Policy

If your site sends a `Content-Security-Policy` header, allow the checkout:

```text
frame-src https://app.oncharge.io;
script-src https://app.oncharge.io;   # only if you use the hosted script
```

The embedding page must be served over HTTPS from a registered domain (or a registered `localhost` during development).

## After the payment

| Session status | What happened | Your action |
|---|---|---|
| `captured` | Paid. | Fulfil the order. |
| `authorized` | Approved, not captured yet. | Wait for `payment.captured`, or [cancel](https://oncharge.io/docs/api#cancelcheckoutsession). |
| `pending` | The shopper must complete a step. | Wait. |
| `refused` | Declined. | Let the shopper try again. A declined payment is never retried automatically; the checkout lets the shopper try another card. |
| `cancelled`, `expired`, `error` | Not paid. | Create a new session if the shopper wants to retry. |

Refund captured payments with [`POST /api/v1/refunds`](https://oncharge.io/docs/api#createrefund).
