# Subscriptions on a website
Source: https://docs.zahlo.eu/quickstarts/saas-subscriptions-website

A signed-in user starts a 14-day free trial of your Pro plan (€19.00 a month). They pay on Zahlo's hosted page, or in a form embedded in your page. The card is saved now and charged when the trial ends; Zahlo then renews the subscription every month. Your webhook handler stores the subscription, and access follows its status. 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.

**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.

<Note>
**No code:** create a payment link with your plan's recurring price under **Payment links** and share its URL. Each payment starts a subscription, which you manage in the dashboard and through the [customer portal](/guides/customer-portal). To grant access in your app automatically, follow the steps below.
</Note>

<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.

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

Test mode and live are separate, so their price IDs differ. Your code finds the price by `lookupKey` instead. This script creates the plan, its monthly price with a 14-day trial, and the `WELCOME15` coupon (15% off for 3 months) once per environment; running it again creates nothing.

<Tabs>
<Tab title="PHP">
```php setup-catalog.php
<?php
// Creates the Pro plan, its monthly price with a 14-day trial, and a coupon, once per environment.
// Run: php setup-catalog.php   (with ZAHLO_API_KEY set; ZAHLO_API_BASE is optional)
// Safe to run again: it finds the price by lookupKey and the coupon 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);
}

$exists = false;
foreach (zahlo_list_all('/prices') as $price) {
    if (!empty($price['active']) && ($price['lookupKey'] ?? null) === 'pro-monthly') {
        $exists = true;
    }
}
if ($exists) {
    echo "price pro-monthly: exists\n";
} else {
    $product = zahlo('POST', '/products', ['name' => 'Pro'], 'setup-product-pro-monthly');
    zahlo('POST', '/prices', [
        'currency' => 'EUR',
        'lookupKey' => 'pro-monthly',
        'productId' => $product['id'],
        'recurring' => ['interval' => 'month', 'trialDays' => 14],
        'type' => 'recurring',
        'unitAmountMinor' => 1900,
    ], 'setup-price-pro-monthly');
    echo "price pro-monthly: created\n";
}

$exists = false;
foreach (zahlo_list_all('/coupons') as $found) {
    if (($found['code'] ?? null) === 'WELCOME15') {
        $exists = true;
    }
}
if ($exists) {
    echo "coupon WELCOME15: exists\n";
} else {
    zahlo('POST', '/coupons', [
        'code' => 'WELCOME15',
        'duration' => 'repeating',
        'durationInMonths' => 3,
        'name' => '15% off for 3 months',
        'percentOff' => 15,
    ], 'setup-coupon-WELCOME15');
    echo "coupon WELCOME15: created\n";
}
```

```bash
set -a; source .env; set +a
php setup-catalog.php
```
</Tab>
<Tab title="Node.js">
```javascript setup-catalog.mjs
// Creates the Pro plan, its monthly price with a 14-day trial, and a coupon, once per environment.
// Run: node --env-file=.env setup-catalog.mjs
// Safe to run again: it finds the price by lookupKey and the coupon 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 PLAN = { lookupKey: "pro-monthly", name: "Pro", unitAmountMinor: 1900, trialDays: 14 };
const COUPON = { code: "WELCOME15", name: "15% off for 3 months", percentOff: 15, duration: "repeating", durationInMonths: 3 };

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");
if (prices.some((price) => price.active && price.lookupKey === PLAN.lookupKey)) {
  console.log(`price ${PLAN.lookupKey}: exists`);
} else {
  const product = await call("POST", "/products", { name: PLAN.name }, `setup-product-${PLAN.lookupKey}`);
  await call(
    "POST",
    "/prices",
    {
      currency: "EUR",
      lookupKey: PLAN.lookupKey,
      productId: product.id,
      recurring: { interval: "month", trialDays: PLAN.trialDays },
      type: "recurring",
      unitAmountMinor: PLAN.unitAmountMinor,
    },
    `setup-price-${PLAN.lookupKey}`
  );
  console.log(`price ${PLAN.lookupKey}: created`);
}

const coupons = await listAll("/coupons");
if (coupons.some((coupon) => coupon.code === COUPON.code)) {
  console.log(`coupon ${COUPON.code}: exists`);
} else {
  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 sign-in, access and checkout">

<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. Users 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__ . '/app.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 users (
            id TEXT PRIMARY KEY,
            email TEXT NOT NULL UNIQUE,
            subscription_id TEXT UNIQUE,
            subscription_status TEXT,      -- trialing | active | past_due | paused | cancelled | incomplete
            past_due_since TEXT,
            current_period_end TEXT
          );
          CREATE TABLE IF NOT EXISTS processed_events (
            event_id TEXT PRIMARY KEY,
            processed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
          );
        ");
    }
    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;
    }
}
```

The sign-in is a stand-in so the quickstart runs on its own. Use your real auth instead.

```php auth.php
<?php
require_once __DIR__ . '/db.php';

// Stand-in for your auth library (your framework's sessions, Auth0, your own login). It signs in by email
// alone and keeps the user id in a cookie, so anyone can claim any email. Replace both functions with real
// authentication before you go live.
function current_user(): ?array
{
    $id = $_COOKIE['uid'] ?? '';
    if ($id === '') {
        return null;
    }
    $stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$id]);
    return $stmt->fetch() ?: null;
}

function sign_in(string $email): array
{
    $email = strtolower(trim($email));
    db()->prepare('INSERT INTO users (id, email) VALUES (?, ?) ON CONFLICT (email) DO NOTHING')
        ->execute([bin2hex(random_bytes(16)), $email]);
    $stmt = db()->prepare('SELECT * FROM users WHERE email = ?');
    $stmt->execute([$email]);
    return $stmt->fetch();
}
```

```php signin.php
<?php
require_once __DIR__ . '/auth.php';

// Demo sign-in: replace with your auth library (see auth.php).
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}
$user = sign_in((string) ($_POST['email'] ?? ''));
setcookie('uid', $user['id'], ['path' => '/', 'httponly' => true, 'samesite' => 'Lax']);
header('Location: /account.php', true, 303);
```

Access is decided from the stored subscription, never from the customer returning from checkout:

```php access.php
<?php
// Your grace period setting (14 days by default). After it, Zahlo cancels the subscription.
const GRACE_DAYS = 14;

/** Access follows the subscription: trialing or active, or past_due while the grace period lasts. */
function has_access(array $user, ?int $now = null): bool
{
    $status = $user['subscription_status'] ?? null;
    if ($status === 'trialing' || $status === 'active') {
        return true;
    }
    if ($status === 'past_due' && !empty($user['past_due_since'])) {
        return ($now ?? time()) - strtotime($user['past_due_since']) < GRACE_DAYS * 86400;
    }
    return false;
}
```

```php account.php
<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/access.php';

// Shows access from the stored subscription. Returning from checkout grants nothing by itself:
// the webhook stores the subscription, usually within seconds.
$user = current_user();
if ($user === null) { ?>
<form action="signin.php" method="post">
  <input name="email" type="email" required placeholder="you@example.com" />
  <button type="submit">Sign in</button>
</form>
<?php } elseif (has_access($user)) { ?>
<p>Pro is active (<?= htmlspecialchars($user['subscription_status']) ?>). Welcome, <?= htmlspecialchars($user['email']) ?>.</p>
<?php } else { ?>
<form action="subscribe.php" method="post">
  <p><?= $user['subscription_id'] ? 'Subscription ' . htmlspecialchars($user['subscription_status']) . '.' : 'Start your 14-day free trial.' ?></p>
  <input name="promoCode" placeholder="Promo code" />
  <button type="submit">Subscribe to Pro</button>
</form>
<p><a href="subscribe.html">Pay without leaving the page</a></p>
<?php }
```

```php subscribe_lib.php
<?php
require_once __DIR__ . '/zahlo.php';
require_once __DIR__ . '/auth.php';

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

/** Starts a subscription checkout for the signed-in user. The price is found by lookupKey. */
function create_subscription_session(array $user, string $mode): array
{
    $promoCode = trim((string) ($_POST['promoCode'] ?? ''));
    $price = null;
    foreach (zahlo_list_all('/prices') as $candidate) {
        if (!empty($candidate['active']) && ($candidate['lookupKey'] ?? null) === 'pro-monthly') {
            $price = $candidate;
            break;
        }
    }
    if ($price === null) {
        throw new RuntimeException('No price with lookupKey pro-monthly; 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;
            }
        }
    }
    $body = [
        'type' => 'subscription',
        'mode' => $mode,
        'lineItems' => [['priceId' => $price['id'], 'quantity' => 1]],
        'customerEmail' => $user['email'],
        'reference' => $user['id'],
        'successUrl' => site_url() . '/account.php?session_id={CHECKOUT_SESSION_ID}',
        'cancelUrl' => site_url() . '/account.php',
    ];
    if ($couponId !== null) {
        $body['couponId'] = $couponId;
    }
    // One key per attempt; a network retry inside zahlo() reuses it.
    return zahlo('POST', '/checkout-sessions', $body, 'subscribe-' . $user['id'] . '-' . bin2hex(random_bytes(8)));
}

/** Runs $respond with the new session; Zahlo errors become a 400 (bad request) or 502 (Zahlo unavailable). */
function subscribe_or_fail(string $mode, callable $respond): void
{
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        exit;
    }
    $user = current_user();
    if ($user === null) {
        http_response_code(401);
        header('content-type: application/json');
        echo json_encode(['error' => ['message' => 'Sign in first']]);
        exit;
    }
    try {
        $respond(create_subscription_session($user, $mode));
    } catch (ZahloError $error) {
        error_log("subscribe 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()]]);
    }
}
```

**Hosted checkout:** the server creates the session and redirects to its `url`.

```php subscribe.php
<?php
require_once __DIR__ . '/subscribe_lib.php';

// Hosted checkout: create the session on the server, then send the browser to session.url.
subscribe_or_fail('hosted', function (array $session) {
    header('Location: ' . $session['url'], true, 303);
});
```

**Embedded checkout:** the server gives the browser only the session ID and short-lived client token; the page loads `/sdk/v1/zahlo.js` and mounts the form. Its callbacks only change what the customer sees.

```php subscribe-session.php
<?php
require_once __DIR__ . '/subscribe_lib.php';

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

```html subscribe.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Subscribe to Pro</title>
  </head>
  <body>
    <main>
      <h1>Subscribe to Pro</h1>
      <form id="subscribe">
        <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 subscription checkout. Callbacks only change what the customer sees; access is
      // granted 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("subscribe").addEventListener("submit", async (event) => {
        event.preventDefault();
        errorBox.textContent = "";
        try {
          const response = await fetch("subscribe-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: () => window.location.assign("account.php"),
            onError: (failure) => { errorBox.textContent = failure.message; },
          });
          await checkout.mount("#zahlo-checkout");
        } catch (failure) {
          errorBox.textContent = failure.message;
        }
      });
    </script>
  </body>
</html>
```
</Tab>
<Tab title="Node.js">
One file serves the pages and the API routes: sign-in (a stand-in for your real auth), the account page with access from the stored subscription, hosted checkout (`POST /subscribe`, a redirect to the session `url`), embedded checkout (`POST /subscribe-session`, only the session ID and client token) and the webhook. 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.

```javascript server.mjs
// One-file Zahlo SaaS site: demo sign-in, hosted and embedded subscription checkout, account 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 ?? "app.db");
db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY,
    email TEXT NOT NULL UNIQUE,
    subscription_id TEXT UNIQUE,
    subscription_status TEXT,      -- trialing | active | past_due | paused | cancelled | incomplete
    past_due_since TEXT,
    current_period_end TEXT
  );
  CREATE TABLE IF NOT EXISTS processed_events (
    event_id TEXT PRIMARY KEY,
    processed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  );
`);
/** 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;
}

// ---- Sign-in (demo) ----
// Stand-in for your auth library (Auth.js, Lucia, your own sessions). It signs in by email alone and keeps
// the user id in a cookie, so anyone can claim any email. Replace both functions with real authentication.
function userFromRequest(request) {
  const id = /(?:^|;\s*)uid=([^;]+)/.exec(request.headers.cookie ?? "")?.[1];
  return id ? db.prepare("SELECT * FROM users WHERE id = ?").get(decodeURIComponent(id)) : undefined;
}

function signIn(email) {
  const clean = email.trim().toLowerCase();
  db.prepare("INSERT INTO users (id, email) VALUES (?, ?) ON CONFLICT (email) DO NOTHING").run(randomUUID(), clean);
  return db.prepare("SELECT * FROM users WHERE email = ?").get(clean);
}

// ---- Access ----
// Your grace period setting (14 days by default). After it, Zahlo cancels the subscription.
const GRACE_DAYS = 14;

/** Access follows the subscription: trialing or active, or past_due while the grace period lasts. */
function hasAccess(user, now = new Date()) {
  if (user.subscription_status === "trialing" || user.subscription_status === "active") return true;
  if (user.subscription_status === "past_due" && user.past_due_since) {
    return now.getTime() - new Date(user.past_due_since).getTime() < GRACE_DAYS * 86_400_000;
  }
  return false;
}

// ---- Subscribe ----
/** Starts a subscription checkout for the signed-in user. The price is found by lookupKey. */
async function createSubscriptionSession(user, mode, promoCode) {
  const price = (await listAll("/prices")).find((p) => p.active && p.lookupKey === "pro-monthly");
  if (!price) throw new Error("No price with lookupKey pro-monthly; run setup-catalog.mjs");
  let couponId;
  if (promoCode) {
    couponId = (await listAll("/coupons")).find(
      (c) => c.active && c.code?.toUpperCase() === promoCode.toUpperCase()
    )?.id;
  }
  return zahlo("POST", "/checkout-sessions", {
    // One key per attempt; a network retry inside zahlo() reuses it.
    idempotencyKey: `subscribe-${user.id}-${randomUUID()}`,
    body: {
      type: "subscription",
      mode,
      lineItems: [{ priceId: price.id, quantity: 1 }],
      couponId,
      customerEmail: user.email,
      reference: user.id,
      successUrl: `${siteUrl}/account?session_id={CHECKOUT_SESSION_ID}`,
      cancelUrl: `${siteUrl}/account`,
    },
  });
}

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

/** Reads a urlencoded or multipart (FormData) body. */
async function readForm(request) {
  const body = await readBody(request);
  const type = request.headers["content-type"] ?? "";
  return type.startsWith("multipart/form-data")
    ? await new Response(body, { headers: { "content-type": type } }).formData()
    : new URLSearchParams(body.toString());
}

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 subscribeFailed(response, error) {
  if (!(error instanceof ZahloError)) throw error;
  console.error("subscribe failed", error.code, error.requestId);
  sendJson(response, error.status >= 500 ? 502 : 400, { error: { code: error.code, message: error.message } });
}

const saveSubscription = (subscription, userId) => {
  const values = [subscription.status, subscription.pastDueSince, subscription.currentPeriodEnd];
  if (userId) {
    // First sight of this subscription: link it to the user who started checkout.
    db.prepare(
      "UPDATE users SET subscription_id = ?, subscription_status = ?, past_due_since = ?, current_period_end = ? WHERE id = ?"
    ).run(subscription.id, ...values, userId);
  } else {
    db.prepare(
      "UPDATE users SET subscription_status = ?, past_due_since = ?, current_period_end = ? WHERE subscription_id = ?"
    ).run(...values, subscription.id);
  }
};

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

  if (route === "POST /signin") {
    const user = signIn(String((await readForm(request)).get("email") ?? ""));
    return send(response, 303, "", { location: "/account", "set-cookie": `uid=${user.id}; Path=/; HttpOnly; SameSite=Lax` });
  }

  // Shows access from the stored subscription. Returning from checkout grants nothing by itself:
  // the webhook stores the subscription, usually within seconds.
  if (route === "GET /account") {
    const user = userFromRequest(request);
    if (!user) {
      return send(
        response,
        200,
        `<form action="/signin" method="post"><input name="email" type="email" required placeholder="you@example.com" /><button type="submit">Sign in</button></form>`
      );
    }
    if (hasAccess(user)) {
      return send(response, 200, `<p>Pro is active (${escapeHtml(user.subscription_status)}). Welcome, ${escapeHtml(user.email)}.</p>`);
    }
    return send(
      response,
      200,
      `<form action="/subscribe" method="post"><p>${
        user.subscription_id ? `Subscription ${escapeHtml(user.subscription_status)}.` : "Start your 14-day free trial."
      }</p><input name="promoCode" placeholder="Promo code" /><button type="submit">Subscribe to Pro</button></form>` +
        `<p><a href="/subscribe.html">Pay without leaving the page</a></p>`
    );
  }

  if (route === "GET /subscribe.html") return send(response, 200, await readFile(join(publicDir, "subscribe.html")));

  // Hosted checkout: create the session on the server, then send the browser to session.url.
  if (route === "POST /subscribe") {
    const user = userFromRequest(request);
    if (!user) return send(response, 401, "Sign in first");
    try {
      const promoCode = String((await readForm(request)).get("promoCode") ?? "").trim() || undefined;
      const session = await createSubscriptionSession(user, "hosted", promoCode);
      return send(response, 303, "", { location: session.url });
    } catch (error) {
      return subscribeFailed(response, error);
    }
  }

  // Embedded checkout: return only the session id and its short-lived client token to the browser.
  if (route === "POST /subscribe-session") {
    const user = userFromRequest(request);
    if (!user) return sendJson(response, 401, { error: { message: "Sign in first" } });
    try {
      const promoCode = String((await readForm(request)).get("promoCode") ?? "").trim() || undefined;
      const session = await createSubscriptionSession(user, "embedded", promoCode);
      return sendJson(response, 200, { apiUrl: apiBase, clientToken: session.clientToken, sessionId: session.id });
    } catch (error) {
      return subscribeFailed(response, error);
    }
  }

  if (route === "POST /webhooks/zahlo") {
    // 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 and store the subscription's current state; never apply the event payload, so events
    //    arriving late or out of order cannot grant or revoke access wrongly.
    const id = encodeURIComponent(event.data.object.id);
    let apply = () => {};
    if (event.type === "checkout.session.completed") {
      const session = await zahlo("GET", `/checkout-sessions/${id}`);
      if (session.type === "subscription" && session.status === "complete" && session.subscriptionId) {
        const subscription = await zahlo("GET", `/subscriptions/${encodeURIComponent(session.subscriptionId)}`);
        apply = () => saveSubscription(subscription, session.reference);
      }
    } else if (event.type.startsWith("subscription.")) {
      const subscription = await zahlo("GET", `/subscriptions/${id}`);
      apply = () => saveSubscription(subscription);
    }

    // 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 embedded page loads `/sdk/v1/zahlo.js` and mounts the form. Its callbacks only change what the customer sees.

```html public/subscribe.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Subscribe to Pro</title>
  </head>
  <body>
    <main>
      <h1>Subscribe to Pro</h1>
      <form id="subscribe">
        <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 subscription checkout. Callbacks only change what the customer sees; access is
      // granted 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("subscribe").addEventListener("submit", async (event) => {
        event.preventDefault();
        errorBox.textContent = "";
        try {
          const response = await fetch("/subscribe-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: () => window.location.assign("/account"),
            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;
}

function save_subscription(PDO $pdo, array $subscription, ?string $userId = null): void
{
    $values = [$subscription['status'], $subscription['pastDueSince'] ?? null, $subscription['currentPeriodEnd'] ?? null];
    if ($userId !== null) {
        // First sight of this subscription: link it to the user who started checkout.
        $pdo->prepare('UPDATE users SET subscription_status = ?, past_due_since = ?, current_period_end = ?, subscription_id = ? WHERE id = ?')
            ->execute([...$values, $subscription['id'], $userId]);
    } else {
        $pdo->prepare('UPDATE users SET subscription_status = ?, past_due_since = ?, current_period_end = ? WHERE subscription_id = ?')
            ->execute([...$values, $subscription['id']]);
    }
}

// 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 and store the subscription's current state; never apply the event payload, so events
//    arriving late or out of order cannot grant or revoke access wrongly.
$id = rawurlencode($event['data']['object']['id'] ?? '');
$apply = function (PDO $pdo): void {};
if ($event['type'] === 'checkout.session.completed') {
    $session = zahlo('GET', "/checkout-sessions/$id");
    if ($session['type'] === 'subscription' && $session['status'] === 'complete' && !empty($session['subscriptionId'])) {
        $subscription = zahlo('GET', '/subscriptions/' . rawurlencode($session['subscriptionId']));
        $apply = fn (PDO $pdo) => save_subscription($pdo, $subscription, $session['reference']);
    }
} elseif (str_starts_with($event['type'], 'subscription.')) {
    $subscription = zahlo('GET', "/subscriptions/$id");
    $apply = fn (PDO $pdo) => save_subscription($pdo, $subscription);
}

// 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.

The handler stores the subscription when `checkout.session.completed` arrives (the session's `reference` is your user ID) and refreshes it on every `subscription.*` event. If a `subscription.*` event arrives first, it changes nothing; the session event links the subscription a moment later.

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: 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", "subscription.created", "subscription.updated", "subscription.renewed", "subscription.past_due", "subscription.payment_failed", "subscription.cancelled", "subscription.trial_will_end"]}'
```

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

</Step>
<Step title="Test the subscription">

<Tabs>
<Tab title="PHP">
```bash
set -a; source .env; set +a
php -S localhost:8000
```

Open `http://localhost:8000/account.php`.
</Tab>
<Tab title="Node.js">
```bash
node --env-file=.env server.mjs
```

Open `http://localhost:3000/account`.
</Tab>
</Tabs>

Sign in with any email, enter `WELCOME15` and subscribe. Pay with the test card `4111 1111 1111 1111`, expiry `03/30`, CVC `737`. Nothing is charged during the trial. Check that:

- your server logs `checkout.session.completed` and `subscription.created`, and the account page shows Pro as active (`trialing`) after a reload;
- the subscription appears under **Customers** in the dashboard.

You don't have to wait 14 days. In test mode, test helpers move a subscription forward. They change Zahlo's records and send the real events, but they don't go through the card network. Find the subscription ID in the dashboard or with `GET /subscriptions`, then:

```bash
curl -X POST "https://merchant.zahlo.eu/api/v1/test-helpers/subscriptions/$SUBSCRIPTION_ID/advance" \
  -H "x-api-key: $ZAHLO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"to": "renewal_failed"}'
```

| `to` | What it does |
|---|---|
| `trial_will_end` | moves the trial to 3 days before its end and sends `subscription.trial_will_end` |
| `renewal_succeeded` | the next charge succeeds |
| `renewal_failed` | the next charge is declined |
| `renewal_requires_action` | the next charge needs the customer to authenticate |
| `period_end` | ends the current period; a subscription set to cancel at period end is cancelled |

After each step, reload the account page: it shows the status your handler stored from the events.

</Step>
<Step title="Let customers manage billing">

Link to your no-code customer portal from the account page. Customers enter their email and get a single-use link to update their card, pay what is overdue or cancel. Its address is shown in the dashboard under **Settings → Customer emails and portal**, where you also choose what customers may change. With only your secret key, read it as `noCodePortalUrl` from [`GET /customer-portal/configuration`](/guides/customer-portal#no-code-link). Changes arrive as the usual `subscription.*` events, which your handler already stores. To open the portal without the email step, create a portal session from your server instead; see [Customer portal](/guides/customer-portal).

</Step>
<Step title="Handle failed payments, refunds and disputes">

- **Failed renewals**: a failed card renewal is retried automatically. The subscription is `past_due` meanwhile, and `hasAccess` keeps access for your grace period (14 days by default). If it is still unpaid then, the subscription is `cancelled` with `cancellationReason: "payment_failed"` and access stops. See [Failed payments](/guides/failed-payments) and [SaaS entitlements](/guides/saas-entitlements).
- **Cancellation**: `subscription.cancelled` ends access; the handler stores the new status.
- **Refunds**: refund a payment from the dashboard or with `POST /refunds`. A refund doesn't cancel the subscription; cancel it as well if the customer leaves. See [Refunds](/guides/refunds).
- **Disputes**: respond in the dashboard before the deadline. See [Disputes](/guides/disputes).

</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>
