# Checkout in 15 minutes

Build an embedded Kustom Checkout with live Playground examples. Create an order, render the snippet, update the cart and handle confirmation and push.

Create an order on your server, render the returned HTML snippet and confirm the purchase. Try each step in the Playground demo beside the instructions. This tutorial covers the embedded checkout; see [Integration models](/checkout/#integration-models) for other options.

<a class="kd-livejump not-content" href="#try-it-live">
  <span class="kd-livedot" aria-hidden="true"></span>
  <span><b>Try it in Playground.</b> Run the tutorial calls in the interactive demo.
  <span class="kd-livejump__cta">Skip to the workbench ↓</span></span>
</a>

## What you'll build

Build order creation, checkout rendering and purchase confirmation. You'll also handle
cart changes while the checkout is open.

## Before you start

**Using an e-commerce platform?** [Start with a plugin](/partners/) to connect your store
without building a custom integration. This tutorial is for developers who need to build
one. See the [Checkout overview](/checkout/) for other options.

The demo needs no setup. These docs provide a Playground session and handle its credentials.
The session lasts two hours.

To run the code locally, you need a server that can make HTTPS requests,
[Playground credentials](/api/authentication/) and a public HTTPS URL for callbacks. Use a
tunnel such as `ngrok` or `cloudflared` to expose your local server.

## Create the order

An order is your cart plus the URLs Kustom should call back. Amounts are in minor units, so
`25000` is 250.00 SEK, and the line totals must add up to `order_amount` exactly — Kustom
rejects a mismatch rather than correcting it.

```json title="the order" wrap
{
  "purchase_country": "SE",
  "purchase_currency": "SEK",
  "locale": "en-SE",
  "order_amount": 25000,
  "order_tax_amount": 5000,
  "order_lines": [
    {
      "type": "physical",
      "reference": "tshirt-001",
      "name": "Cotton T-Shirt",
      "quantity": 1,
      "unit_price": 25000,
      "tax_rate": 2500,
      "total_amount": 25000,
      "total_tax_amount": 5000
    }
  ],
  "merchant_urls": {
    "terms": "https://your-shop.example/terms",
    "checkout": "https://your-shop.example/checkout",
    "confirmation": "https://your-shop.example/confirmation?order_id={checkout.order.id}",
    "push": "https://your-shop.example/push?order_id={checkout.order.id}"
  }
}
```

Four `merchant_urls` are required: `terms`, `checkout`, `confirmation` and `push`. Kustom
substitutes `{checkout.order.id}` into any of them before calling, and `push` should be its
own path rather than your checkout or confirmation page — it fires server-to-server even
when the browser never comes back. [Order payload](/checkout/integrate/the-order/)
documents every field, and [Checkout URLs and callbacks](/checkout/integrate/merchant-urls/)
covers the optional ones.

Send the request from your server using HTTP Basic authentication. Keep the API secret
on your server and return only `html_snippet` to the browser. There is no browser-safe API key.

```js title="server.js" wrap
// On your server, never in the browser: this needs your secret.
const auth = 'Basic ' + Buffer.from(`${id}:${secret}`).toString('base64');

const KUSTOM = 'https://api.playground.kustom.co';

const res = await fetch(`${KUSTOM}/checkout/v3/orders`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Authorization: auth },
  body: JSON.stringify(order),
});

const { order_id, html_snippet } = await res.json();

// Store order_id. Every later read and update of this order is keyed on it.
const orderUrl = (order_id) => `${KUSTOM}/checkout/v3/orders/${order_id}`;
```

The `201` response contains `html_snippet` and **`order_id`**. Render the snippet on your
checkout page and store the ID on the cart for later reads and updates. The order URL is
`{base URL}/checkout/v3/orders/{order_id}`, also returned in the `Location` header.

The pane has the same request. Switch the market, send it and watch what comes back.

## Render the snippet

The `html_snippet` is a `<div>` plus a `<script>` that loads the checkout iframe. Put it
on the page you registered as `merchant_urls.checkout`.

For server rendering, insert the snippet into your template unescaped. For browser
rendering, re-create each script as a new element: **scripts inserted through `innerHTML`
do not execute**.

```js title="render-checkout.js" wrap
// Scripts inserted via innerHTML never execute, so re-create each one.
function renderCheckout(container, htmlSnippet) {
  container.innerHTML = htmlSnippet;
  container.querySelectorAll('script').forEach((inert) => {
    const script = document.createElement('script');
    for (const a of inert.attributes) script.setAttribute(a.name, a.value);
    script.textContent = inert.textContent;
    inert.replaceWith(script);
  });
}
```

```html title="index.html" wrap
<!doctype html>
<html>
  <body>
    <!-- Your container, your id. -->
    <div id="checkout" style="min-width: 320px"></div>

    <script src="/render-checkout.js"></script>
    <script>
      fetch('/checkout', { method: 'POST' })
        .then((r) => r.json())
        .then(({ html_snippet }) => {
          renderCheckout(document.getElementById('checkout'), html_snippet);
        });
    </script>
  </body>
</html>
```

Several things break this silently — a second snippet on the page, a style rule reaching
inside the container, a `Cross-Origin-Opener-Policy` header. The "Good to know" list in
[Render and update](/checkout/integrate/render-checkout-snippet/) has them all.

## Update the order while the checkout is open

When the cart changes, pause the iframe, POST the new lines to the existing order URL and
resume the iframe.

```js title="update.js" wrap
async function updateOrder(orderId, changes) {
  window._klarnaCheckout((api) => api.suspend());
  try {
    await fetch(`/checkout/${orderId}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(changes),
    });
  } finally {
    // Always. resume() is what re-reads the order and redraws the totals.
    window._klarnaCheckout((api) => api.resume());
  }
}
```

`resume()` makes the iframe read the updated order and redraw totals. Call it in `finally`
so the checkout resumes even if the update fails.

Two more rules. **Never create a new order to reflect a change** — POST the update to the
existing one. And updates are only accepted while the order's `status` is
`checkout_incomplete`.

`suspend` and `resume` are commands the iframe accepts, not events it emits.
[Checkout JavaScript events](/checkout/client-side-events/) documents both halves — the
two commands in full, and the events you listen for to keep your own cart panel in sync.

## Confirm and acknowledge

When the customer presses **Pay order**, Kustom does two independent things: it redirects
the browser to `merchant_urls.confirmation`, and it calls `merchant_urls.push`
server-to-server. You may see both, only one, or the push first — so both paths do the
same work, idempotently.

```js title="server.js" wrap
// merchant_urls.confirmation -- the customer's browser lands here after paying.
app.get('/confirmation', async (req, res) => {
  const order = await readOrder(req.query.order_id);

  // The API returns lowercase; the spec's example is uppercase. Compare loosely.
  if (String(order.status).toLowerCase() !== 'checkout_complete') {
    return res.status(409).send('Order is not complete');
  }

  // Idempotent: the push below may have arrived first.
  await recordOrder(order);
  await acknowledge(req.query.order_id);

  // The same html_snippet field, now a receipt.
  res.send(`<div id="confirmation">${order.html_snippet}</div>`);
});

// merchant_urls.push -- server to server, independent of the browser. You may get this before the redirect, after it, or instead of it, so both paths do the same work.
app.post('/push', async (req, res) => {
  await recordOrder(await readOrder(req.query.order_id));
  await acknowledge(req.query.order_id);
  res.sendStatus(200);
});

// orderUrl(id) builds the order URL from the order_id you stored.
function readOrder(orderId) {
  return fetch(orderUrl(orderId), {
    headers: { Authorization: auth },
  }).then((r) => r.json());
}

// Stops the push retries.
function acknowledge(orderId) {
  return fetch(`${KUSTOM}/ordermanagement/v1/orders/${orderId}/acknowledge`, {
    method: 'POST',
    headers: { Authorization: auth },
  });
}
```

Both handlers must:

- **Read the order. Don't trust the query string.** The `order_id` in the URL says which
  order. The order's own `status` is the source of truth.
- **Compare the status case-insensitively.** The API returns `checkout_complete` in
  lowercase. The OpenAPI document's example shows it uppercase.
- **Acknowledge the order after recording it.** Kustom retries the push until acknowledged.
  Both handlers must work independently, including when the customer closes the tab.

The confirmation snippet is the same `html_snippet` field on the order you just read, now
rendered as a receipt.

## You now have

- A server route that creates an order with all four required `merchant_urls`, keeps the
  `order_id` and returns only the snippet to the browser.
- A checkout page that injects the snippet and executes its scripts, inside a container
  you named.
- An update path that suspends, posts and resumes without ever re-creating the order.
- A confirmation route and a push endpoint that both record the order and acknowledge it.

<span class="kd-sited__step">before checkout</span>
<span class="kd-sited__step is-here">checkout</span>
<span class="kd-sited__step">authorized</span>
<span class="kd-sited__step">captured</span>
<span class="kd-sited__step">settled</span>
<a class="kd-sited__more" href="/basics/order-lifecycle/">the whole lifecycle →</a>

<h2 class="kd-cockpit__panetitle" id="try-it-live"><span class="kd-livedot" aria-hidden="true"></span>Try it live</h2>

> Live page: a request runner, which sends this call and shows the response inline. Programmatic equivalent: `POST https://api.playground.kustom.co/checkout/v3/orders`, authenticated with HTTP Basic using your API username and API password.

```json
{
  "purchase_country": "SE",
  "purchase_currency": "SEK",
  "locale": "en-SE",
  "order_amount": 108000,
  "order_tax_amount": 21600,
  "order_lines": [
    {
      "type": "physical",
      "reference": "tshirt-001",
      "name": "Cotton T-Shirt",
      "quantity": 2,
      "quantity_unit": "pcs",
      "unit_price": 25000,
      "tax_rate": 2500,
      "total_amount": 50000,
      "total_discount_amount": 0,
      "total_tax_amount": 10000
    },
    {
      "type": "physical",
      "reference": "chinos-001",
      "name": "Slim Fit Chinos",
      "quantity": 1,
      "quantity_unit": "pcs",
      "unit_price": 70000,
      "tax_rate": 2500,
      "total_amount": 70000,
      "total_discount_amount": 0,
      "total_tax_amount": 14000
    },
    {
      "type": "discount",
      "reference": "discount-10pct",
      "name": "10% off",
      "quantity": 1,
      "quantity_unit": "pcs",
      "unit_price": -12000,
      "tax_rate": 2500,
      "total_amount": -12000,
      "total_discount_amount": 0,
      "total_tax_amount": -2400
    }
  ],
  "options": {
    "allow_separate_shipping_address": true
  }
}
```

## Next

- [Order payload](/checkout/integrate/the-order/) — every field on the order.
- [Render and update](/checkout/integrate/render-checkout-snippet/) — the injection
  reference, including the server-side variants.
- [Shipping options in the checkout](/checkout/shipping/),
  [Sell to businesses (B2B)](/checkout/use-cases/b2b/) and
  [Recurring and on-demand payments](/checkout/recurring/) — features to add once the checkout works.
- [Order lifecycle](/basics/order-lifecycle/) — capture, refund and settlement, if you're
  integrating Order Management too.
