Skip to content
OnCharge.io
View as Markdown
Developer docs

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:

OptionBest for
Hosted redirectThe fastest integration. Works everywhere, including in-app browsers.
Embedded iframeKeeping the shopper on your checkout page, with no JavaScript library.
Script tagEmbedding on any site with automatic resizing and events.
React componentReact apps.
Next.jsNext.js App Router stores.

Whichever you choose, the payment is confirmed on your server by a webhook, never by the browser.

Create a checkout session#

Call POST /api/v1/checkout/sessions from your server (see Authentication for signing).

FieldRequiredNotes
amountYesInteger in minor units (4900 = $49.00).
currencyYesISO 4217 code, e.g. USD.
referenceYesYour order number or cart ID, up to 255 characters. Returned in webhooks.
return_urlYesWhere the shopper goes after checkout. Must be on a registered store domain.
order_idNoYour order ID if the order already exists. Otherwise attach it later.
customer_email, customer_phoneNoUsed for fraud screening and receipts. Phone in E.164 (+15551234567).
shippingFor physical goodsname, 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_itemsNo[{ description, quantity, amount_including_tax }].
metadataNoYour 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.

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.

server
const session = await oncharge.checkout.sessions.create(params, { idempotencyKey: order.id });
return Response.redirect(session.checkout_url, 303);
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}.

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:

ParameterValue
embed1. The checkout shows its own pay button, and links that would leave the frame become redirect messages.
parent_originYour 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_nonceA fresh random value per page load, 16–128 characters of A-Z a-z 0-9 _ -. Every message echoes it.
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" }
typeFieldsWhen
readyheightThe payment form is shown (once per load).
resizeheight (CSS pixels)The content height changed.
completestatus: captured or authorizedThe payment succeeded.
errormessage, status: refused or errorThe payment failed or the form could not load.
redirecturlThe 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.

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):

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

const checkout = mountCheckout('#oncharge-checkout', { url: checkoutUrl, onComplete: ({ sessionId }) => { /* … */ } });
OptionTypeDefaultPurpose
urlstring(required)The session's checkout_url, or its iframe_url resolved against baseUrl. Must be HTTPS.
baseUrlstringhttps://app.oncharge.ioUsed to resolve a relative url.
onReady() => voidThe payment form is shown.
onComplete({ sessionId, status }) => voidThe payment succeeded (status is captured or authorized). Confirm on your server before fulfilling.
onError({ message, status? }) => voidThe payment failed (status: 'refused') or the form could not load.
onRedirect({ url }) => voidnavigate the top windowThe checkout wants to leave the frame.
autoResizebooleantrueFollow the checkout's content height.
minHeightnumber480Minimum iframe height in pixels.
titlestringSecure checkoutAccessible 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#

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.

Next.js#

Create the session in a server action or route handler and render the component in a client component. The Next.js guide 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 statusWhat happenedYour action
capturedPaid.Fulfil the order.
authorizedApproved, not captured yet.Wait for payment.captured, or cancel.
pendingThe shopper must complete a step.Wait.
refusedDeclined.Let the shopper try again. A declined payment is never retried automatically; the checkout lets the shopper try another card.
cancelled, expired, errorNot paid.Create a new session if the shopper wants to retry.

Refund captured payments with POST /api/v1/refunds.