# Embedded checkout with Next.js
Source: https://docs.zahlo.eu/quickstarts/ecommerce-embedded-nextjs

The customer picks a product and pays in a payment form that Zahlo renders inside your page; card details never touch your server. Your webhook handler marks the order paid. Every file below is complete; copy them into a Next.js 15+ App Router project.

**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), Node.js 22.5 or later, 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">

Create `.env.local` in the project root. Keep it out of version control; the key never reaches the browser.

```bash .env.local
ZAHLO_API_KEY=zk_test_your_key
ZAHLO_WEBHOOK_SECRET=set_in_step_6
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:3000` 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. Hosted checkout needs none of this.
</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:

```javascript scripts/setup-catalog.mjs
// Creates the store's products, prices and coupon once per environment (test mode, then live).
// Run: node --env-file=.env.local scripts/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.local scripts/setup-catalog.mjs
```

</Step>
<Step title="Add the API client and database">

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

```typescript lib/zahlo.ts
// Server-only Zahlo API client. Never import this file from a client component.
const apiKey = process.env.ZAHLO_API_KEY ?? "";

/** One host for both modes: the key prefix selects test or live. */
export const apiBase =
  process.env.ZAHLO_API_BASE ??
  "https://merchant.zahlo.eu";

export class ZahloError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    message: string,
    readonly requestId: string | null
  ) {
    super(message);
  }
}

const MAX_RETRIES = 2;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const backoff = (attempt: number, response?: 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: number, code: string) =>
  status === 429 ||
  status >= 500 ||
  (status === 409 && code === "request_in_progress");

/**
 * Calls the Zahlo API. Every POST carries one Idempotency-Key, reused on each retry,
 * so a retried request can never create a second object.
 */
export async function zahlo<T>(
  method: "GET" | "POST" | "PATCH" | "DELETE",
  path: string,
  options: { body?: unknown; idempotencyKey?: string } = {}
): Promise<T> {
  const idempotencyKey =
    method === "POST"
      ? (options.idempotencyKey ?? crypto.randomUUID())
      : undefined;
  for (let attempt = 0; ; attempt += 1) {
    let response: Response;
    try {
      response = await fetch(`${apiBase}/api/v1${path}`, {
        body:
          options.body === undefined ? undefined : JSON.stringify(options.body),
        headers: {
          "content-type": "application/json",
          "x-api-key": apiKey,
          ...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
        },
        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()) as T;
    }
    const payload = await response.json().catch(() => ({}));
    const code: string = 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. */
export async function listAll<T extends { id: string }>(
  path: string
): Promise<T[]> {
  const items: T[] = [];
  let startingAfter = "";
  for (;;) {
    const page = await zahlo<{ data: T[]; hasMore: boolean }>(
      "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;
  }
}
```

The quickstart stores orders in SQLite (`node:sqlite`, built into Node.js). Use your own database the same way: what matters is the transaction.

```typescript lib/db.ts


// Any database with transactions works; SQLite keeps the quickstart self-contained.
export 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. */
export function transaction<T>(fn: () => T): T {
  db.exec("BEGIN IMMEDIATE");
  try {
    const result = fn();
    db.exec("COMMIT");
    return result;
  } catch (error) {
    db.exec("ROLLBACK");
    throw error;
  }
}

export type Order = {
  id: string;
  items: string;
  status: string;
  session_id: string | null;
  payment_id: string | null;
};
```

</Step>
<Step title="Create the Checkout Session">

```typescript lib/checkout.ts



type Price = { id: string; lookupKey: string | null; active: boolean };
type Coupon = { id: string; code: string | null; active: boolean };
export type CheckoutSession = {
  id: string;
  url: string | null;
  clientToken: string | null;
  status: "open" | "complete" | "expired" | "failed";
  paymentStatus: "unpaid" | "paid" | "no_payment_required";
  paymentId: string | null;
  reference: string | null;
};

const siteUrl = process.env.SITE_URL ?? "http://localhost:3000";

/**
 * Saves a pending order and creates its Checkout Session. Prices are found by lookupKey, so the same
 * code works in test mode and live, where every ID differs.
 */
export async function createOrderSession(input: {
  items: { lookupKey: string; quantity: number }[];
  promoCode?: string;
  mode: "hosted" | "embedded";
}): Promise<CheckoutSession> {
  const prices = await listAll<Price>("/prices");
  const lineItems = input.items.map((item) => {
    const price = prices.find((p) => p.active && p.lookupKey === item.lookupKey);
    if (!price) {
      throw new Error(`No price with lookupKey ${item.lookupKey}; run scripts/setup-catalog.mjs`);
    }
    return { priceId: price.id, quantity: item.quantity };
  });
  let couponId: string | undefined;
  if (input.promoCode) {
    const coupons = await listAll<Coupon>("/coupons");
    couponId = coupons.find(
      (c) => c.active && c.code?.toUpperCase() === input.promoCode?.toUpperCase()
    )?.id;
  }

  const orderId = crypto.randomUUID();
  db.prepare("INSERT INTO orders (id, items) VALUES (?, ?)").run(
    orderId,
    JSON.stringify(input.items)
  );
  const session = await zahlo<CheckoutSession>("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: input.mode,
      lineItems,
      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;
}

/** Reads an item list from a form: lookupKey, quantity and an optional promo code. */
export function cartFromForm(form: FormData) {
  return {
    items: [
      {
        lookupKey: String(form.get("lookupKey") ?? "tshirt"),
        quantity: Math.max(1, Number(form.get("quantity") ?? 1)),
      },
    ],
    promoCode: String(form.get("promoCode") ?? "").trim() || undefined,
  };
}
```

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

```typescript app/api/checkout-session/route.ts



// Embedded checkout: return only the session id and its short-lived client token to the browser.
export async function POST(request: Request) {
  try {
    const session = await createOrderSession({
      ...cartFromForm(await request.formData()),
      mode: "embedded",
    });
    return Response.json({ apiUrl: apiBase, clientToken: session.clientToken, sessionId: session.id });
  } catch (error) {
    if (error instanceof ZahloError) {
      console.error("checkout failed", error.code, error.requestId);
      return Response.json(
        { error: { code: error.code, message: error.message } },
        { status: error.status >= 500 ? 502 : 400 }
      );
    }
    throw error;
  }
}
```

The page loads the browser SDK from `/sdk/v1/zahlo.js` and mounts the payment form. Its callbacks only change what the customer sees; the webhook fulfils the order.

```tsx app/checkout/page.tsx
"use client";



type Mounted = { mount(selector: string): Promise<void>; destroy(): void };
declare global {
  interface Window {
    ZahloCheckout: new (config: {
      apiUrl: string;
      sessionId: string;
      clientToken: string;
      onSuccess?: (sessionId: string) => void;
      onError?: (error: Error) => void;
    }) => Mounted;
  }
}

const loadScript = (src: string) =>
  new Promise<void>((resolve, reject) => {
    if (window.ZahloCheckout) return resolve();
    const script = Object.assign(document.createElement("script"), { src, async: true });
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`Could not load ${src}`));
    document.head.append(script);
  });

// Embedded checkout: the payment form renders inside this page. Callbacks only change what the
// customer sees; the order is fulfilled by the webhook.
export default function CheckoutPage() {
  const [error, setError] = useState("");
  const checkout = useRef<Mounted | null>(null);

  async function start(form: FormData) {
    setError("");
    const response = await fetch("/api/checkout-session", { body: form, method: "POST" });
    const body = await response.json();
    if (!response.ok) return setError(body.error?.message ?? "Checkout is unavailable");
    await loadScript(`${body.apiUrl}/sdk/v1/zahlo.js`);
    checkout.current?.destroy();
    checkout.current = new window.ZahloCheckout({
      apiUrl: body.apiUrl,
      sessionId: body.sessionId,
      clientToken: body.clientToken,
      onSuccess: (sessionId) => window.location.assign(`/success?session_id=${sessionId}`),
      onError: (failure) => setError(failure.message),
    });
    await checkout.current.mount("#zahlo-checkout");
  }

  useEffect(() => () => checkout.current?.destroy(), []);

  return (
    <main>
      <h1>Checkout</h1>
      <form action={start}>
        <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" defaultValue="1" />
        <input name="promoCode" placeholder="Promo code" />
        <button type="submit">Continue to payment</button>
      </form>
      {error && <p role="alert">{error}</p>}
      <div id="zahlo-checkout" />
    </main>
  );
}
```

The success page shows the order's state. It never marks an order paid: anyone can open the success URL, and the customer may close the tab before returning.

```typescript lib/orders.ts




/**
 * What the success page shows. It reads state and never fulfils: only the webhook marks an order paid,
 * because a customer can open the success URL without paying.
 */
export async function orderForSuccessPage(sessionId: string) {
  const session = await zahlo<CheckoutSession>("GET", `/checkout-sessions/${encodeURIComponent(sessionId)}`);
  const order = db.prepare("SELECT * FROM orders WHERE session_id = ?").get(session.id) as Order | undefined;
  return { order, paid: order?.status === "paid" };
}
```

```tsx app/success/page.tsx


export const dynamic = "force-dynamic";

export default async function SuccessPage({
  searchParams,
}: {
  searchParams: Promise<{ session_id?: string }>;
}) {
  const { session_id: sessionId } = await searchParams;
  if (!sessionId) return <p>Missing session.</p>;
  const { order, paid } = await orderForSuccessPage(sessionId);
  if (!order) return <p>Order not found.</p>;
  return paid ? (
    <p>Thank you! Order {order.id} is paid.</p>
  ) : (
    // The webhook usually arrives within seconds; reload to check again.
    <p>Payment processing. Order {order.id} will be confirmed by email.</p>
  );
}
```

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

```typescript lib/webhook-signature.ts


export type ZahloEvent = {
  id: string;
  type: string;
  livemode: boolean;
  createdAt: string;
  data: { object: { id: string } & Record<string, unknown> };
};

/**
 * Checks `Zahlo-Signature: t=<unix>,v1=<hex>` against the raw request body and returns the parsed event,
 * or null when the signature is missing, wrong or older than 5 minutes. During a secret rotation the
 * header carries one v1 per secret, so any matching v1 is accepted.
 */
export function verifyZahloEvent(
  rawBody: string,
  header: string | null,
  secret: string,
  toleranceSeconds = 300
): ZahloEvent | null {
  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) as ZahloEvent) : null;
}
```

```typescript app/api/webhooks/zahlo/route.ts





type Refund = { id: string; paymentId: string; status: "pending" | "succeeded" | "failed" };
type Dispute = { id: string; paymentId: string; status: string };

export async function POST(request: Request) {
  // 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 request.text();
  const event = verifyZahloEvent(
    rawBody,
    request.headers.get("zahlo-signature"),
    process.env.ZAHLO_WEBHOOK_SECRET ?? ""
  );
  if (!event) return new Response("Invalid signature", { status: 400 });

  // 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: () => void = () => {};
  if (event.type === "checkout.session.completed" || event.type === "checkout.session.expired") {
    const session = await zahlo<CheckoutSession>("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<Refund>("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<Dispute>("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 new Response("ok");
}
```

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 dev server and note its `https://….trycloudflare.com` URL:

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

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 response shows the signing `secret` once: put it in `ZAHLO_WEBHOOK_SECRET` and restart the dev 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/api/webhooks/zahlo", "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`. Refund from the dashboard or with `POST /refunds`; 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">

```bash
npm run dev
```

Open `http://localhost:3000/checkout`, 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: open a checkout and abandon it (the order stays `pending`, and `checkout.session.expired` marks it `expired` when the session ends), 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>
