# Embedded checkout on a website
Source: https://docs.zahlo.eu/quickstarts/ecommerce-embedded-website

The customer pays in a form that Zahlo renders inside your page, loaded with one script tag (`/sdk/v1/zahlo.js`); card details never touch your server. Your webhook handler marks the order paid. Pick **PHP** (any PHP 8.1+ host with the `curl` and `pdo_sqlite` extensions) or **Node.js** (22.5 or later, no dependencies); every file is complete.

**Integration checklist.** A complete integration does all five, including when you adapt these steps to an existing app instead of copying the files:

1. Create the checkout session on your server.
2. Fulfil the order on `checkout.session.completed`.
3. Mark the order `refunded` on `refund.succeeded`.
4. Flag the order `disputed` on `dispute.created`, and hold the shipment.
5. Run the refund test: refund a paid test order and check that it shows `refunded` (see [Reverse on refunds and disputes](/guides/fulfillment#reverse-on-refunds-and-disputes)).

An integration without 3–4 is incomplete: refunded orders stay paid. Subscribe your webhook endpoint to all four events. If your orders have no `refunded` or `disputed` state yet, add them: a new value in the existing status column is enough.

**You need:** a Zahlo account and its `zk_test_` API key (**Developers → API keys**, with **Test mode** on), and `cloudflared` (`brew install cloudflared`, or a package from Cloudflare's downloads page) to receive webhooks on your machine.

<Steps>
<Step title="Set environment variables">

Your server reads these; the key never reaches the browser. On a host, set them in the server configuration (for example `SetEnv` for Apache or `env[...]` for PHP-FPM). Locally, put them in a `.env` file that stays out of version control:

```bash .env
ZAHLO_API_KEY=zk_test_your_key
ZAHLO_WEBHOOK_SECRET=set_in_step_6
SITE_URL=http://localhost:8000
```

PHP reads them from the environment: `set -a; source .env; set +a` before `php -S`. Node.js reads the file with `--env-file=.env`. With Node.js, use port 3000 (`SITE_URL=http://localhost:3000`).

</Step>
<Step title="Register your domains">

Customers return to your site through Zahlo, which only sends them to hosts you registered. Register your site's host once per environment, in the dashboard (**Developers → Checkout domains**) or with the API. It takes effect immediately.

```bash
curl -X POST "https://merchant.zahlo.eu/api/v1/checkout-domains" \
  -H "x-api-key: $ZAHLO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"domain": "shop.example.com"}'
```

A session whose `successUrl` or `cancelUrl` uses an unregistered host fails with `checkout_domain_not_registered` (400). A `checkout_domain_pending` (409) means Zahlo is still enabling checkout for your account, once, after approval; retry later or contact support.

<Note>
**Local development:** in test mode (`zk_test_` keys) you can register `localhost:3000` (or `127.0.0.1:3000`) and use `http://` return URLs. Live requires HTTPS.
</Note>

For this quickstart, register `localhost:8000` (PHP) or `localhost:3000` (Node.js) in test mode.

<Note>
**Apple Pay in embedded checkout** needs your page's host registered with `"applePay": true` on a real HTTPS domain (not `localhost` or a quick tunnel). Cards and Google Pay work without it.
</Note>

</Step>
<Step title="Create the catalogue">

Test mode and live are separate, so their product and price IDs differ. Your code finds prices by `lookupKey` instead. This script creates them once per environment, and running it again creates nothing.

<Tabs>
<Tab title="PHP">
```php setup-catalog.php
<?php
// Creates the store's products, prices and coupon once per environment (test mode, then live).
// Run: php setup-catalog.php   (with ZAHLO_API_KEY set; ZAHLO_API_BASE is optional)
// Safe to run again: it finds existing prices by lookupKey and coupons by code, and creates nothing twice.
require_once __DIR__ . '/zahlo.php';

if (!getenv('ZAHLO_API_KEY')) {
    fwrite(STDERR, "Set ZAHLO_API_KEY\n");
    exit(1);
}

$products = [
    ['lookupKey' => 'tshirt', 'name' => 'T-shirt', 'unitAmountMinor' => 2500],
    ['lookupKey' => 'mug', 'name' => 'Mug', 'unitAmountMinor' => 1200],
];
$coupons = [['code' => 'WELCOME15', 'name' => 'Welcome 15%', 'percentOff' => 15, 'duration' => 'once']];

$prices = zahlo_list_all('/prices');
foreach ($products as $item) {
    foreach ($prices as $price) {
        if (!empty($price['active']) && ($price['lookupKey'] ?? null) === $item['lookupKey']) {
            echo "price {$item['lookupKey']}: exists\n";
            continue 2;
        }
    }
    $product = zahlo('POST', '/products', ['name' => $item['name']], "setup-product-{$item['lookupKey']}");
    zahlo('POST', '/prices', [
        'currency' => 'EUR',
        'lookupKey' => $item['lookupKey'],
        'productId' => $product['id'],
        'type' => 'one_time',
        'unitAmountMinor' => $item['unitAmountMinor'],
    ], "setup-price-{$item['lookupKey']}");
    echo "price {$item['lookupKey']}: created\n";
}

$existing = zahlo_list_all('/coupons');
foreach ($coupons as $coupon) {
    foreach ($existing as $found) {
        if (($found['code'] ?? null) === $coupon['code']) {
            echo "coupon {$coupon['code']}: exists\n";
            continue 2;
        }
    }
    zahlo('POST', '/coupons', $coupon, "setup-coupon-{$coupon['code']}");
    echo "coupon {$coupon['code']}: created\n";
}
```

```bash
set -a; source .env; set +a
php setup-catalog.php
```
</Tab>
<Tab title="Node.js">
```javascript setup-catalog.mjs
// Creates the store's products, prices and coupon once per environment (test mode, then live).
// Run: node --env-file=.env setup-catalog.mjs
// Safe to run again: it finds existing prices by lookupKey and coupons by code, and creates nothing twice.
const apiKey = process.env.ZAHLO_API_KEY;
if (!apiKey) throw new Error("Set ZAHLO_API_KEY");
const apiBase =
  process.env.ZAHLO_API_BASE ??
  "https://merchant.zahlo.eu";

const PRODUCTS = [
  { lookupKey: "tshirt", name: "T-shirt", unitAmountMinor: 2500 },
  { lookupKey: "mug", name: "Mug", unitAmountMinor: 1200 },
];
const COUPONS = [{ code: "WELCOME15", name: "Welcome 15%", percentOff: 15, duration: "once" }];

async function call(method, path, body, idempotencyKey) {
  for (let attempt = 0; ; attempt += 1) {
    const response = await fetch(`${apiBase}/api/v1${path}`, {
      body: body === undefined ? undefined : JSON.stringify(body),
      headers: {
        "content-type": "application/json",
        "x-api-key": apiKey,
        ...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
      },
      method,
    });
    if (response.ok) return response.json();
    const error = (await response.json().catch(() => ({}))).error ?? {};
    const retry = response.status === 429 || response.status >= 500 || error.code === "request_in_progress";
    if (retry && attempt < 2) {
      await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** attempt));
      continue;
    }
    throw new Error(`${method} ${path} -> ${response.status} ${error.code}: ${error.message}`);
  }
}

async function listAll(path) {
  const items = [];
  for (let after = ""; ; ) {
    const page = await call("GET", `${path}?limit=100${after ? `&startingAfter=${after}` : ""}`);
    items.push(...page.data);
    if (!page.hasMore || page.data.length === 0) return items;
    after = page.data.at(-1).id;
  }
}

const prices = await listAll("/prices");
for (const item of PRODUCTS) {
  if (prices.some((price) => price.active && price.lookupKey === item.lookupKey)) {
    console.log(`price ${item.lookupKey}: exists`);
    continue;
  }
  const product = await call("POST", "/products", { name: item.name }, `setup-product-${item.lookupKey}`);
  await call(
    "POST",
    "/prices",
    {
      currency: "EUR",
      lookupKey: item.lookupKey,
      productId: product.id,
      type: "one_time",
      unitAmountMinor: item.unitAmountMinor,
    },
    `setup-price-${item.lookupKey}`
  );
  console.log(`price ${item.lookupKey}: created`);
}

const coupons = await listAll("/coupons");
for (const coupon of COUPONS) {
  if (coupons.some((existing) => existing.code === coupon.code)) {
    console.log(`coupon ${coupon.code}: exists`);
    continue;
  }
  await call("POST", "/coupons", coupon, `setup-coupon-${coupon.code}`);
  console.log(`coupon ${coupon.code}: created`);
}
```

```bash
node --env-file=.env setup-catalog.mjs
```
</Tab>
</Tabs>

</Step>
<Step title="Add the payment page and session route">

<Tabs>
<Tab title="PHP">
The API client sends one `Idempotency-Key` per operation and retries only network errors, `409 request_in_progress`, `429` and `5xx`, at most twice, with the same key. Orders are stored in SQLite; use your own database the same way, since what matters is the transaction.

```php zahlo.php
<?php
// Server-only Zahlo API client. Never expose ZAHLO_API_KEY to the browser.
const ZAHLO_MAX_RETRIES = 2;

class ZahloError extends RuntimeException
{
    public function __construct(public int $status, public string $errorCode, string $message, public ?string $requestId)
    {
        parent::__construct($message);
    }
}

/** One host for both modes: the key prefix selects test or live. */
function zahlo_base(): string
{
    $base = getenv('ZAHLO_API_BASE');
    if ($base) {
        return rtrim($base, '/');
    }
    return 'https://merchant.zahlo.eu';
}

/** Retry only what can succeed on a second try: 409 request_in_progress, 429 and 5xx (network errors are handled by the caller). */
function zahlo_retryable(int $status, string $code): bool
{
    return $status === 429 || $status >= 500 || ($status === 409 && $code === 'request_in_progress');
}

function zahlo_sleep(int $attempt, ?string $retryAfter): void
{
    $seconds = $retryAfter !== null && is_numeric($retryAfter) ? (float) $retryAfter : 0;
    usleep((int) (($seconds > 0 ? $seconds : 0.5 * (2 ** $attempt)) * 1_000_000));
}

/**
 * Calls the Zahlo API. Every POST carries one Idempotency-Key, reused on each retry,
 * so a retried request can never create a second object.
 */
function zahlo(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): ?array
{
    $headers = ['content-type: application/json', 'x-api-key: ' . (getenv('ZAHLO_API_KEY') ?: '')];
    if ($method === 'POST') {
        $headers[] = 'idempotency-key: ' . ($idempotencyKey ?? bin2hex(random_bytes(16)));
    }
    for ($attempt = 0;; $attempt++) {
        $retryAfter = null;
        $ch = curl_init(zahlo_base() . '/api/v1' . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
                if (stripos($line, 'retry-after:') === 0) {
                    $retryAfter = trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $networkError = curl_error($ch);

        if ($raw === false) {
            if ($attempt < ZAHLO_MAX_RETRIES) {
                zahlo_sleep($attempt, null);
                continue;
            }
            throw new RuntimeException('Zahlo request failed: ' . $networkError);
        }
        $payload = json_decode($raw, true);
        if ($status >= 200 && $status < 300) {
            return $status === 204 ? null : $payload;
        }
        $code = $payload['error']['code'] ?? 'unknown';
        if ($attempt < ZAHLO_MAX_RETRIES && zahlo_retryable($status, $code)) {
            zahlo_sleep($attempt, $retryAfter);
            continue;
        }
        throw new ZahloError($status, $code, $payload['error']['message'] ?? 'Request failed', $payload['requestId'] ?? null);
    }
}

/** Lists return one page at a time; follow startingAfter until hasMore is false. */
function zahlo_list_all(string $path): array
{
    $items = [];
    $after = '';
    for (;;) {
        $page = zahlo('GET', $path . '?limit=100' . ($after !== '' ? '&startingAfter=' . rawurlencode($after) : ''));
        $items = array_merge($items, $page['data']);
        $last = end($page['data']);
        if (empty($page['hasMore']) || !$last) {
            return $items;
        }
        $after = $last['id'];
    }
}
```

```php db.php
<?php
// Any database with transactions works; SQLite keeps the quickstart self-contained.
function db(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO('sqlite:' . (getenv('DATABASE_PATH') ?: __DIR__ . '/store.db'));
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $pdo->exec('PRAGMA busy_timeout = 5000');
        $pdo->exec("
          CREATE TABLE IF NOT EXISTS orders (
            id TEXT PRIMARY KEY,
            items TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending', -- pending | paid | expired | refunded | disputed
            session_id TEXT UNIQUE,
            payment_id TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
          );
          CREATE TABLE IF NOT EXISTS processed_events (
            event_id TEXT PRIMARY KEY,
            processed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
          );
          -- Work that cannot join the transaction (emails, shipping APIs) is queued here inside it.
          CREATE TABLE IF NOT EXISTS jobs (
            id INTEGER PRIMARY KEY,
            kind TEXT NOT NULL,
            order_id TEXT NOT NULL,
            done INTEGER NOT NULL DEFAULT 0,
            UNIQUE (kind, order_id)
          );
        ");
    }
    return $pdo;
}

/** Runs $fn in one transaction: all of its writes commit together, or none do. */
function transaction(callable $fn): mixed
{
    $pdo = db();
    $pdo->exec('BEGIN IMMEDIATE');
    try {
        $result = $fn($pdo);
        $pdo->exec('COMMIT');
        return $result;
    } catch (Throwable $error) {
        $pdo->exec('ROLLBACK');
        throw $error;
    }
}
```

```php checkout_lib.php
<?php
require_once __DIR__ . '/zahlo.php';
require_once __DIR__ . '/db.php';

function site_url(): string
{
    return rtrim(getenv('SITE_URL') ?: 'http://localhost:8000', '/');
}

/**
 * Saves a pending order and creates its Checkout Session from the POST fields lookupKey, quantity and
 * promoCode. Prices are found by lookupKey, so the same code works in test mode and live, where every ID differs.
 */
function create_order_session(string $mode): array
{
    $lookupKey = (string) ($_POST['lookupKey'] ?? 'tshirt');
    $quantity = max(1, (int) ($_POST['quantity'] ?? 1));
    $promoCode = trim((string) ($_POST['promoCode'] ?? ''));

    $price = null;
    foreach (zahlo_list_all('/prices') as $candidate) {
        if (!empty($candidate['active']) && ($candidate['lookupKey'] ?? null) === $lookupKey) {
            $price = $candidate;
            break;
        }
    }
    if ($price === null) {
        throw new RuntimeException("No price with lookupKey $lookupKey; run php setup-catalog.php");
    }
    $couponId = null;
    if ($promoCode !== '') {
        foreach (zahlo_list_all('/coupons') as $coupon) {
            if (!empty($coupon['active']) && strcasecmp($coupon['code'] ?? '', $promoCode) === 0) {
                $couponId = $coupon['id'];
                break;
            }
        }
    }

    $orderId = bin2hex(random_bytes(16));
    db()->prepare('INSERT INTO orders (id, items) VALUES (?, ?)')
        ->execute([$orderId, json_encode([['lookupKey' => $lookupKey, 'quantity' => $quantity]])]);
    $body = [
        'type' => 'payment',
        'mode' => $mode,
        'lineItems' => [['priceId' => $price['id'], 'quantity' => $quantity]],
        'reference' => $orderId,
        'successUrl' => site_url() . '/success.php?session_id={CHECKOUT_SESSION_ID}',
        'cancelUrl' => site_url() . '/',
    ];
    if ($couponId !== null) {
        $body['couponId'] = $couponId;
    }
    // One key per order: a retried request returns the same session instead of a second one.
    $session = zahlo('POST', '/checkout-sessions', $body, "order-$orderId");
    db()->prepare('UPDATE orders SET session_id = ? WHERE id = ?')->execute([$session['id'], $orderId]);
    return $session;
}

/** Runs $respond with the new session; Zahlo errors become a 400 (bad request) or 502 (Zahlo unavailable). */
function checkout_or_fail(string $mode, callable $respond): void
{
    try {
        $respond(create_order_session($mode));
    } catch (ZahloError $error) {
        error_log("checkout failed {$error->errorCode} {$error->requestId}");
        http_response_code($error->status >= 500 ? 502 : 400);
        header('content-type: application/json');
        echo json_encode(['error' => ['code' => $error->errorCode, 'message' => $error->getMessage()]]);
    }
}
```

The server creates the session and gives the browser only its ID and short-lived client token, never your API key:

```php checkout-session.php
<?php
require_once __DIR__ . '/checkout_lib.php';

// Embedded checkout: return only the session id and its short-lived client token to the browser.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}
checkout_or_fail('embedded', function (array $session) {
    header('content-type: application/json');
    echo json_encode(['apiUrl' => zahlo_base(), 'clientToken' => $session['clientToken'], 'sessionId' => $session['id']]);
});
```

The page loads the browser SDK and mounts the payment form. Its callbacks only change what the customer sees; the webhook fulfils the order.

```html pay.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Checkout</title>
  </head>
  <body>
    <main>
      <h1>Checkout</h1>
      <form id="cart">
        <select name="lookupKey">
          <option value="tshirt">T-shirt (€25.00)</option>
          <option value="mug">Mug (€12.00)</option>
        </select>
        <input name="quantity" type="number" min="1" max="999" value="1" />
        <input name="promoCode" placeholder="Promo code" />
        <button type="submit">Continue to payment</button>
      </form>
      <p id="error" role="alert"></p>
      <div id="zahlo-checkout"></div>
    </main>
    <script>
      // Embedded checkout: the payment form renders inside this page. Callbacks only change what the
      // customer sees; the order is fulfilled by the webhook.
      const errorBox = document.getElementById("error");
      let checkout = null;

      function loadScript(src) {
        return new Promise((resolve, reject) => {
          if (window.ZahloCheckout) return resolve();
          const script = document.createElement("script");
          script.src = src;
          script.async = true;
          script.onload = () => resolve();
          script.onerror = () => reject(new Error("Could not load " + src));
          document.head.append(script);
        });
      }

      document.getElementById("cart").addEventListener("submit", async (event) => {
        event.preventDefault();
        errorBox.textContent = "";
        try {
          const response = await fetch("checkout-session.php", {
            method: "POST",
            body: new FormData(event.target),
          });
          const body = await response.json();
          if (!response.ok) {
            errorBox.textContent = (body.error && body.error.message) || "Checkout is unavailable";
            return;
          }
          await loadScript(body.apiUrl + "/sdk/v1/zahlo.js");
          if (checkout) checkout.destroy();
          checkout = new window.ZahloCheckout({
            apiUrl: body.apiUrl,
            sessionId: body.sessionId,
            clientToken: body.clientToken,
            onSuccess: (sessionId) => window.location.assign("success.php?session_id=" + encodeURIComponent(sessionId)),
            onError: (failure) => { errorBox.textContent = failure.message; },
          });
          await checkout.mount("#zahlo-checkout");
        } catch (failure) {
          errorBox.textContent = failure.message;
        }
      });
    </script>
  </body>
</html>
```

The success page shows the order's state. It never marks an order paid: anyone can open the success URL.

```php success.php
<?php
require_once __DIR__ . '/zahlo.php';
require_once __DIR__ . '/db.php';

// Reads state and never fulfils: only the webhook marks an order paid,
// because a customer can open the success URL without paying.
$sessionId = (string) ($_GET['session_id'] ?? '');
if ($sessionId === '') {
    echo '<p>Missing session.</p>';
    exit;
}
$session = zahlo('GET', '/checkout-sessions/' . rawurlencode($sessionId));
$stmt = db()->prepare('SELECT * FROM orders WHERE session_id = ?');
$stmt->execute([$session['id']]);
$order = $stmt->fetch();
if (!$order) {
    echo '<p>Order not found.</p>';
} elseif ($order['status'] === 'paid') {
    echo '<p>Thank you! Order ' . htmlspecialchars($order['id']) . ' is paid.</p>';
} else {
    // The webhook usually arrives within seconds; reload to check again.
    echo '<p>Payment processing. Order ' . htmlspecialchars($order['id']) . ' will be confirmed by email.</p>';
}
```
</Tab>
<Tab title="Node.js">
One file serves the pages and the API routes. Its API client sends one `Idempotency-Key` per operation and retries only network errors, `409 request_in_progress`, `429` and `5xx`, at most twice, with the same key. The success page shows the order's state and never marks an order paid. Orders are stored in SQLite (`node:sqlite`); use your own database the same way.

```javascript server.mjs
// One-file Zahlo store: static pages, hosted and embedded checkout, success page and webhook.
// Needs Node 22.5+ and no dependencies. Run: node --env-file=.env server.mjs
// Env: ZAHLO_API_KEY, ZAHLO_API_BASE (optional), ZAHLO_WEBHOOK_SECRET, SITE_URL, DATABASE_PATH, PORT







const apiKey = process.env.ZAHLO_API_KEY ?? "";
const webhookSecret = process.env.ZAHLO_WEBHOOK_SECRET ?? "";
const port = Number(process.env.PORT ?? 3000);
const siteUrl = process.env.SITE_URL ?? `http://localhost:${port}`;
// One host for both modes: the key (zk_test_ or zk_live_) selects test or live.
const apiBase =
  process.env.ZAHLO_API_BASE ??
  "https://merchant.zahlo.eu";
const publicDir = join(dirname(fileURLToPath(import.meta.url)), "public");

// ---- Database (any database with transactions works; SQLite keeps this self-contained) ----
const db = new DatabaseSync(process.env.DATABASE_PATH ?? "store.db");
db.exec(`
  CREATE TABLE IF NOT EXISTS orders (
    id TEXT PRIMARY KEY,
    items TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending', -- pending | paid | expired | refunded | disputed
    session_id TEXT UNIQUE,
    payment_id TEXT,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  );
  CREATE TABLE IF NOT EXISTS processed_events (
    event_id TEXT PRIMARY KEY,
    processed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  );
  -- Work that cannot join the transaction (emails, shipping APIs) is queued here inside it.
  CREATE TABLE IF NOT EXISTS jobs (
    id INTEGER PRIMARY KEY,
    kind TEXT NOT NULL,
    order_id TEXT NOT NULL,
    done INTEGER NOT NULL DEFAULT 0,
    UNIQUE (kind, order_id)
  );
`);

/** Runs fn in one transaction: all of its writes commit together, or none do. */
function transaction(fn) {
  db.exec("BEGIN IMMEDIATE");
  try {
    const result = fn();
    db.exec("COMMIT");
    return result;
  } catch (error) {
    db.exec("ROLLBACK");
    throw error;
  }
}

// ---- Zahlo API client ----
class ZahloError extends Error {
  constructor(status, code, message, requestId) {
    super(message);
    this.status = status;
    this.code = code;
    this.requestId = requestId;
  }
}

const MAX_RETRIES = 2;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const backoff = (attempt, response) =>
  Number(response?.headers.get("retry-after") ?? 0) * 1000 || 500 * 2 ** attempt;
// Retry only what can succeed on a second try: network errors, 409 request_in_progress, 429 and 5xx.
const retryable = (status, code) =>
  status === 429 || status >= 500 || (status === 409 && code === "request_in_progress");

/** Every POST carries one Idempotency-Key, reused on each retry, so a retry can never create a second object. */
async function zahlo(method, path, { body, idempotencyKey } = {}) {
  const key = method === "POST" ? (idempotencyKey ?? randomUUID()) : undefined;
  for (let attempt = 0; ; attempt += 1) {
    let response;
    try {
      response = await fetch(`${apiBase}/api/v1${path}`, {
        body: body === undefined ? undefined : JSON.stringify(body),
        headers: {
          "content-type": "application/json",
          "x-api-key": apiKey,
          ...(key ? { "idempotency-key": key } : {}),
        },
        method,
        signal: AbortSignal.timeout(15_000),
      });
    } catch (error) {
      if (attempt < MAX_RETRIES) {
        await sleep(backoff(attempt));
        continue;
      }
      throw error;
    }
    if (response.ok) return response.status === 204 ? undefined : await response.json();
    const payload = await response.json().catch(() => ({}));
    const code = payload?.error?.code ?? "unknown";
    if (attempt < MAX_RETRIES && retryable(response.status, code)) {
      await sleep(backoff(attempt, response));
      continue;
    }
    throw new ZahloError(
      response.status,
      code,
      payload?.error?.message ?? response.statusText,
      payload?.requestId ?? response.headers.get("x-request-id")
    );
  }
}

/** Lists return one page at a time; follow startingAfter until hasMore is false. */
async function listAll(path) {
  const items = [];
  let startingAfter = "";
  for (;;) {
    const page = await zahlo("GET", `${path}?limit=100${startingAfter ? `&startingAfter=${startingAfter}` : ""}`);
    items.push(...page.data);
    const last = page.data.at(-1);
    if (!(page.hasMore && last)) return items;
    startingAfter = last.id;
  }
}

// ---- Webhook signature ----
/** Checks `Zahlo-Signature: t=<unix>,v1=<hex>` on the raw body; any matching v1 passes (secret rotation). */
function verifyZahloEvent(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = (header ?? "").split(",").map((part) => part.trim().split("="));
  const timestamp = Number(parts.find(([key]) => key === "t")?.[1]);
  const signatures = parts.filter(([key]) => key === "v1").map(([, value]) => value ?? "");
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return null;
  const expected = Buffer.from(createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex"));
  const valid = signatures.some((signature) => {
    const given = Buffer.from(signature);
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
  return valid ? JSON.parse(rawBody) : null;
}

// ---- Checkout ----
/** Saves a pending order and creates its Checkout Session. Prices are found by lookupKey, so the same code works in test mode and live. */
async function createOrderSession(form, mode) {
  const lookupKey = form.get("lookupKey") || "tshirt";
  const quantity = Math.max(1, Number(form.get("quantity") ?? 1) || 1);
  const promoCode = String(form.get("promoCode") ?? "").trim();

  const price = (await listAll("/prices")).find((p) => p.active && p.lookupKey === lookupKey);
  if (!price) throw new Error(`No price with lookupKey ${lookupKey}; run setup-catalog.mjs`);
  let couponId;
  if (promoCode) {
    couponId = (await listAll("/coupons")).find(
      (c) => c.active && c.code?.toUpperCase() === promoCode.toUpperCase()
    )?.id;
  }

  const orderId = randomUUID();
  db.prepare("INSERT INTO orders (id, items) VALUES (?, ?)").run(orderId, JSON.stringify([{ lookupKey, quantity }]));
  const session = await zahlo("POST", "/checkout-sessions", {
    // One key per order: a retried request returns the same session instead of a second one.
    idempotencyKey: `order-${orderId}`,
    body: {
      type: "payment",
      mode,
      lineItems: [{ priceId: price.id, quantity }],
      couponId,
      reference: orderId,
      successUrl: `${siteUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancelUrl: `${siteUrl}/`,
    },
  });
  db.prepare("UPDATE orders SET session_id = ? WHERE id = ?").run(session.id, orderId);
  return session;
}

async function readBody(request) {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  return Buffer.concat(chunks);
}

const send = (response, status, body, headers = {}) => {
  response.writeHead(status, { "content-type": "text/html; charset=utf-8", ...headers });
  response.end(body);
};
const sendJson = (response, status, body) =>
  send(response, status, JSON.stringify(body), { "content-type": "application/json" });
const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

/** Zahlo errors become 400 (bad request) or 502 (Zahlo unavailable); anything else is a 500. */
function checkoutFailed(response, error) {
  if (!(error instanceof ZahloError)) throw error;
  console.error("checkout failed", error.code, error.requestId);
  sendJson(response, error.status >= 500 ? 502 : 400, { error: { code: error.code, message: error.message } });
}

// ---- Routes ----
async function handle(request, response) {
  const url = new URL(request.url ?? "/", siteUrl);
  const route = `${request.method} ${url.pathname}`;

  if (route === "GET /" || route === "GET /index.html" || route === "GET /pay.html") {
    const file = url.pathname === "/pay.html" ? "pay.html" : "index.html";
    return send(response, 200, await readFile(join(publicDir, file)));
  }

  // Hosted checkout: create the session on the server, then send the browser to session.url.
  if (route === "POST /checkout") {
    try {
      const form = new URLSearchParams((await readBody(request)).toString());
      const session = await createOrderSession(form, "hosted");
      return send(response, 303, "", { location: session.url });
    } catch (error) {
      return checkoutFailed(response, error);
    }
  }

  // Embedded checkout: return only the session id and its short-lived client token to the browser.
  if (route === "POST /checkout-session") {
    try {
      const body = await readBody(request);
      const type = request.headers["content-type"] ?? "";
      // The page posts FormData (multipart); a plain HTML form posts urlencoded.
      const form = type.startsWith("multipart/form-data")
        ? await new Response(body, { headers: { "content-type": type } }).formData()
        : new URLSearchParams(body.toString());
      const session = await createOrderSession(form, "embedded");
      return sendJson(response, 200, { apiUrl: apiBase, clientToken: session.clientToken, sessionId: session.id });
    } catch (error) {
      return checkoutFailed(response, error);
    }
  }

  // Reads state and never fulfils: only the webhook marks an order paid, because a customer can open this URL without paying.
  if (route === "GET /success") {
    const sessionId = url.searchParams.get("session_id");
    if (!sessionId) return send(response, 200, "<p>Missing session.</p>");
    const session = await zahlo("GET", `/checkout-sessions/${encodeURIComponent(sessionId)}`);
    const order = db.prepare("SELECT * FROM orders WHERE session_id = ?").get(session.id);
    if (!order) return send(response, 200, "<p>Order not found.</p>");
    return send(
      response,
      200,
      order.status === "paid"
        ? `<p>Thank you! Order ${escapeHtml(order.id)} is paid.</p>`
        : // The webhook usually arrives within seconds; reload to check again.
          `<p>Payment processing. Order ${escapeHtml(order.id)} will be confirmed by email.</p>`
    );
  }

  if (route === "POST /webhooks/zahlo") {
    // Adapting this to an existing app? Keep the refund.succeeded and dispute.created branches and subscribe the endpoint to their events. Without them a refunded order stays paid, and a disputed order is never flagged, so it can still ship.
    // 1. Verify the signature on the raw body before trusting anything in it.
    const rawBody = (await readBody(request)).toString("utf8");
    const event = verifyZahloEvent(rawBody, request.headers["zahlo-signature"] ?? null, webhookSecret);
    if (!event) return send(response, 400, "Invalid signature");

    // 2. Re-fetch the object and act on its current state, so a late, older event cannot undo a newer one.
    const id = encodeURIComponent(event.data.object.id);
    let apply = () => {};
    if (event.type === "checkout.session.completed" || event.type === "checkout.session.expired") {
      const session = await zahlo("GET", `/checkout-sessions/${id}`);
      apply = () => {
        if (session.paymentStatus === "paid") {
          const paid = db
            .prepare("UPDATE orders SET status = 'paid', payment_id = ? WHERE session_id = ? AND status = 'pending'")
            .run(session.paymentId, session.id);
          if (paid.changes === 1) {
            db.prepare("INSERT OR IGNORE INTO jobs (kind, order_id) VALUES ('confirmation_email', ?)").run(
              session.reference
            );
          }
        } else if (session.status === "expired") {
          db.prepare("UPDATE orders SET status = 'expired' WHERE session_id = ? AND status = 'pending'").run(session.id);
        }
      };
    } else if (event.type === "refund.succeeded") {
      const refund = await zahlo("GET", `/refunds/${id}`);
      apply = () => {
        if (refund.status === "succeeded") {
          db.prepare("UPDATE orders SET status = 'refunded' WHERE payment_id = ?").run(refund.paymentId);
        }
      };
    } else if (event.type === "dispute.created") {
      const dispute = await zahlo("GET", `/disputes/${id}`);
      apply = () => {
        // Hold the shipment and answer the dispute in the dashboard.
        db.prepare("UPDATE orders SET status = 'disputed' WHERE payment_id = ? AND status = 'paid'").run(
          dispute.paymentId
        );
      };
    }

    // 3. Record the event and apply the change in ONE transaction, and answer 2xx only after it commits.
    //    A crash before the commit rolls back both, so Zahlo's retry does the work again.
    transaction(() => {
      const fresh = db
        .prepare("INSERT INTO processed_events (event_id) VALUES (?) ON CONFLICT DO NOTHING")
        .run(event.id);
      if (fresh.changes === 1) apply();
    });
    return send(response, 200, "ok");
  }

  return send(response, 404, "Not found");
}

createServer((request, response) => {
  handle(request, response).catch((error) => {
    console.error("request failed", error);
    if (!response.headersSent) send(response, 500, "Internal error");
  });
}).listen(port, () => console.log(`Listening on ${siteUrl}`));
```

The page loads the browser SDK and mounts the payment form. Its callbacks only change what the customer sees; the webhook fulfils the order.

```html public/pay.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Checkout</title>
  </head>
  <body>
    <main>
      <h1>Checkout</h1>
      <form id="cart">
        <select name="lookupKey">
          <option value="tshirt">T-shirt (€25.00)</option>
          <option value="mug">Mug (€12.00)</option>
        </select>
        <input name="quantity" type="number" min="1" max="999" value="1" />
        <input name="promoCode" placeholder="Promo code" />
        <button type="submit">Continue to payment</button>
      </form>
      <p id="error" role="alert"></p>
      <div id="zahlo-checkout"></div>
    </main>
    <script>
      // Embedded checkout: the payment form renders inside this page. Callbacks only change what the
      // customer sees; the order is fulfilled by the webhook.
      const errorBox = document.getElementById("error");
      let checkout = null;

      function loadScript(src) {
        return new Promise((resolve, reject) => {
          if (window.ZahloCheckout) return resolve();
          const script = document.createElement("script");
          script.src = src;
          script.async = true;
          script.onload = () => resolve();
          script.onerror = () => reject(new Error("Could not load " + src));
          document.head.append(script);
        });
      }

      document.getElementById("cart").addEventListener("submit", async (event) => {
        event.preventDefault();
        errorBox.textContent = "";
        try {
          const response = await fetch("/checkout-session", {
            method: "POST",
            body: new FormData(event.target),
          });
          const body = await response.json();
          if (!response.ok) {
            errorBox.textContent = (body.error && body.error.message) || "Checkout is unavailable";
            return;
          }
          await loadScript(body.apiUrl + "/sdk/v1/zahlo.js");
          if (checkout) checkout.destroy();
          checkout = new window.ZahloCheckout({
            apiUrl: body.apiUrl,
            sessionId: body.sessionId,
            clientToken: body.clientToken,
            onSuccess: (sessionId) => window.location.assign("/success?session_id=" + encodeURIComponent(sessionId)),
            onError: (failure) => { errorBox.textContent = failure.message; },
          });
          await checkout.mount("#zahlo-checkout");
        } catch (failure) {
          errorBox.textContent = failure.message;
        }
      });
    </script>
  </body>
</html>
```
</Tab>
</Tabs>

</Step>
<Step title="Handle webhooks">

<Tabs>
<Tab title="PHP">
```php webhook.php
<?php
require_once __DIR__ . '/zahlo.php';
require_once __DIR__ . '/db.php';

/**
 * Checks `Zahlo-Signature: t=<unix>,v1=<hex>` against the raw body. During a secret rotation the header
 * carries one v1 per secret, so any matching v1 is accepted. Rejects timestamps older than 5 minutes.
 */
function verify_zahlo_signature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't') {
            $timestamp = $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === null || !ctype_digit($timestamp) || abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

// Adapting this to an existing app? Keep the refund.succeeded and dispute.created branches and subscribe the endpoint to their events. Without them a refunded order stays paid, and a disputed order is never flagged, so it can still ship.

// 1. Verify the signature on the raw body before trusting anything in it.
$rawBody = file_get_contents('php://input');
if (!verify_zahlo_signature($rawBody, $_SERVER['HTTP_ZAHLO_SIGNATURE'] ?? '', getenv('ZAHLO_WEBHOOK_SECRET') ?: '')) {
    http_response_code(400);
    echo 'Invalid signature';
    exit;
}
$event = json_decode($rawBody, true);

// 2. Re-fetch the object and act on its current state, so a late, older event cannot undo a newer one.
$id = rawurlencode($event['data']['object']['id'] ?? '');
$apply = function (PDO $pdo): void {};
if ($event['type'] === 'checkout.session.completed' || $event['type'] === 'checkout.session.expired') {
    $session = zahlo('GET', "/checkout-sessions/$id");
    $apply = function (PDO $pdo) use ($session): void {
        if ($session['paymentStatus'] === 'paid') {
            $paid = $pdo->prepare("UPDATE orders SET status = 'paid', payment_id = ? WHERE session_id = ? AND status = 'pending'");
            $paid->execute([$session['paymentId'], $session['id']]);
            if ($paid->rowCount() === 1) {
                $pdo->prepare("INSERT OR IGNORE INTO jobs (kind, order_id) VALUES ('confirmation_email', ?)")
                    ->execute([$session['reference']]);
            }
        } elseif ($session['status'] === 'expired') {
            $pdo->prepare("UPDATE orders SET status = 'expired' WHERE session_id = ? AND status = 'pending'")
                ->execute([$session['id']]);
        }
    };
} elseif ($event['type'] === 'refund.succeeded') {
    $refund = zahlo('GET', "/refunds/$id");
    $apply = function (PDO $pdo) use ($refund): void {
        if ($refund['status'] === 'succeeded') {
            $pdo->prepare("UPDATE orders SET status = 'refunded' WHERE payment_id = ?")->execute([$refund['paymentId']]);
        }
    };
} elseif ($event['type'] === 'dispute.created') {
    $dispute = zahlo('GET', "/disputes/$id");
    $apply = function (PDO $pdo) use ($dispute): void {
        // Hold the shipment and answer the dispute in the dashboard.
        $pdo->prepare("UPDATE orders SET status = 'disputed' WHERE payment_id = ? AND status = 'paid'")
            ->execute([$dispute['paymentId']]);
    };
}

// 3. Record the event and apply the change in ONE transaction, and answer 2xx only after it commits.
//    A crash before the commit rolls back both, so Zahlo's retry does the work again.
try {
    transaction(function (PDO $pdo) use ($event, $apply) {
        $fresh = $pdo->prepare('INSERT INTO processed_events (event_id) VALUES (?) ON CONFLICT DO NOTHING');
        $fresh->execute([$event['id']]);
        if ($fresh->rowCount() === 1) {
            $apply($pdo);
        }
    });
} catch (Throwable $error) {
    error_log('webhook failed: ' . $error->getMessage());
    http_response_code(500); // not 2xx: Zahlo retries the event
    echo 'error';
    exit;
}
echo 'ok';
```
</Tab>
<Tab title="Node.js">
The handler is the `POST /webhooks/zahlo` route in `server.mjs` above.
</Tab>
</Tabs>

The webhook handler is the only place that fulfils orders or grants access. It follows three rules, which the code above implements:

1. **Verify first.** Check `Zahlo-Signature` on the raw request body and answer `400` when it is missing, wrong or older than 5 minutes.
2. **Act on current state.** Events can arrive late, twice or out of order. Re-fetch the object (`GET /checkout-sessions/:id`, `GET /subscriptions/:id`) and act on what it says now, not on the event payload.
3. **Commit, then answer.** Record the event ID and apply the change in **one** database transaction, and return `2xx` only after it commits. A duplicate event inserts nothing and changes nothing. If your server crashes before the commit, nothing is saved, and Zahlo's retry (1 minute, 5 minutes, … up to 3 days) does the work again. Never record the event, answer `200`, and do the work afterwards.

Work that can't join the transaction, such as emails, goes into a job row inside it and runs afterwards.

Webhooks need a public HTTPS URL. Start a tunnel to your server and note its `https://….trycloudflare.com` URL:

```bash
cloudflared tunnel --url http://localhost:8000
```

Add the endpoint in **Developers → Webhooks**, or with the API, subscribed to every event the handler reacts to: `checkout.session.completed` and `checkout.session.expired` for orders, `refund.succeeded` and `dispute.created` for reversals. The URL is `https://your-tunnel.trycloudflare.com/webhook.php` for PHP and `…/webhooks/zahlo` for Node.js. The response shows the signing `secret` once: put it in `ZAHLO_WEBHOOK_SECRET` and restart the server.

```bash
curl -X POST "https://merchant.zahlo.eu/api/v1/webhook-endpoints" \
  -H "x-api-key: $ZAHLO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-tunnel.trycloudflare.com/webhook.php", "enabledEvents": ["checkout.session.completed", "checkout.session.expired", "refund.succeeded", "dispute.created"]}'
```

A quick tunnel's URL changes every time you start it; update the endpoint when it does.

</Step>
<Step title="Handle refunds and disputes">

The handler also reacts to reversals. If you adapt it to an existing app instead of copying it, keep these branches and subscribe your webhook endpoint to their events. Without them, a refunded order stays `paid`, and a disputed order is never flagged, so it can still ship:

- **`refund.succeeded`**: the order is marked `refunded`. A refund is final only when `refund.succeeded` or `refund.failed` arrives. See [Refunds](/guides/refunds).
- **`dispute.created`**: the order is marked `disputed`. Hold the shipment and respond in the dashboard before the deadline. See [Disputes](/guides/disputes).

Test this once you have paid a test order in the next step. Refund it with its payment ID (the handler stores it on the order; it is also under **Payments** in the dashboard):

```bash
curl -X POST "https://merchant.zahlo.eu/api/v1/refunds" \
  -H "x-api-key: $ZAHLO_API_KEY" \
  -H "Idempotency-Key: refund-test-1" \
  -H "Content-Type: application/json" \
  -d '{"paymentId": "<payment ID>", "reason": "requested_by_customer"}'
```

Within a few seconds your server logs a `refund.succeeded` delivery and the order shows `refunded`. If it still shows `paid`, your handler is missing the `refund.succeeded` branch.

</Step>
<Step title="Test a payment">

<Tabs>
<Tab title="PHP">
```bash
set -a; source .env; set +a
php -S localhost:8000
```
</Tab>
<Tab title="Node.js">
```bash
node --env-file=.env server.mjs
```
</Tab>
</Tabs>

Open `/pay.html`, choose 3 T-shirts with the promo code `WELCOME15`, and pay in the embedded form with the test card `4111 1111 1111 1111`, expiry `03/30`, CVC `737`. Check that:

- the embedded form shows €63.75 (3 × €25.00, minus 15%);
- your server logs a `checkout.session.completed` delivery, and the success page shows the order as paid after a reload;
- the payment appears under **Payments** in the dashboard, and the delivery under **Developers → Webhooks**.

Then check the failure paths: abandon a checkout (the order stays `pending` until `checkout.session.expired` marks it `expired`), and resend a delivery from **Developers → Webhooks** (nothing changes the second time).

Then refund the test order as the previous step shows, and check that it shows `refunded`.

</Step>
<Step title="Go live">

Your live account starts empty, and Test-mode IDs, keys and secrets don't work there. Recreate what this integration uses, in this order (details: [Go live](/go-live#recreate-in-live); your live dashboard's **Go live** page at `https://merchant.zahlo.eu/merchant/go-live` tracks each step):

1. Create a live API key and set `ZAHLO_API_KEY` to it (`zk_live_…`). Code that reads `ZAHLO_API_BASE` sets it to `https://merchant.zahlo.eu`.
2. Run `setup-catalog` against live. It creates the same `lookupKey`s and coupon codes, so your code needs no change.
3. Recreate your payment links; live links have new URLs.
4. Add your live webhook endpoint, set `ZAHLO_WEBHOOK_SECRET` to its new signing secret, and confirm one live delivery arrives.
5. Register your site's checkout domain in live (HTTPS only), plus the Apple Pay domain if you embed checkout with wallets.
6. Customers, subscriptions and saved payment methods don't carry over; real checkouts create them.
7. Make one small live payment, check that `payment.confirmed` and your fulfilment ran, then refund it.

</Step>
</Steps>
