# SEPA Direct Debit subscriptions (Next.js)
Source: https://docs.zahlo.eu/quickstarts/saas-sepa

A signed-in user starts a 14-day free trial of your Pro plan (€19.00 a month) and pays by SEPA Direct Debit. On Zahlo's hosted page they enter their IBAN and accept the mandate; your server never sees the IBAN. Zahlo debits the account when the trial ends and every month after, and notifies the customer before each debit.

SEPA Direct Debit subscriptions are EUR only and use hosted checkout. They work in test mode; in live, they are enabled per account on request (contact support). Use [card subscriptions](/quickstarts/saas-subscriptions-hosted-nextjs) if you need live payments without that step. This quickstart is the card quickstart with one file changed, `lib/subscribe.ts`. Turn on **SEPA Direct Debit** under **Settings → Payment methods** in the dashboard first; otherwise session create fails with `payment_method_unavailable`. Your webhook handler stores the subscription, and access follows its status. Every file below is complete; copy them into a Next.js 15+ App Router project.

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

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

```javascript scripts/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.local scripts/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.local scripts/setup-catalog.mjs
```

</Step>
<Step title="Add the API client, database and sign-in">

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 users 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 ?? "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. */
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 User = {
  id: string;
  email: string;
  subscription_id: string | null;
  subscription_status: string | null;
  past_due_since: string | null;
  current_period_end: string | null;
};
```

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

```typescript lib/auth.ts


// Stand-in for your auth library (Auth.js, Clerk, your own sessions). The quickstart signs in by email
// and keeps the user id in a cookie; replace both functions with your real sign-in.
export function userFromRequest(request: Request): User | null {
  const id = /(?:^|;\s*)uid=([^;]+)/.exec(request.headers.get("cookie") ?? "")?.[1];
  if (!id) return null;
  return (db.prepare("SELECT * FROM users WHERE id = ?").get(decodeURIComponent(id)) as User | undefined) ?? null;
}

export function signIn(email: string): User {
  db.prepare("INSERT INTO users (id, email) VALUES (?, ?) ON CONFLICT (email) DO NOTHING").run(
    crypto.randomUUID(),
    email.trim().toLowerCase()
  );
  return db.prepare("SELECT * FROM users WHERE email = ?").get(email.trim().toLowerCase()) as User;
}
```

```typescript app/api/signin/route.ts


// Demo sign-in: replace with your auth library.
export async function POST(request: Request) {
  const user = signIn(String((await request.formData()).get("email") ?? ""));
  return new Response(null, {
    headers: { location: "/account", "set-cookie": `uid=${user.id}; Path=/; HttpOnly; SameSite=Lax` },
    status: 303,
  });
}
```

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

```typescript lib/subscribe.ts



type Price = { id: string; lookupKey: string | null; active: boolean };
type Coupon = { id: string; code: string | null; active: boolean };
export type CheckoutSession = {
  id: string;
  type: "payment" | "subscription";
  url: string | null;
  clientToken: string | null;
  status: "open" | "complete" | "expired" | "failed";
  subscriptionId: string | null;
  reference: string | null;
};

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

/**
 * Starts a SEPA Direct Debit subscription for the signed-in user. The customer enters their IBAN and
 * accepts the mandate on Zahlo's hosted page; your server never sees the IBAN.
 */
export async function createSubscriptionSession(
  user: User,
  options: { mode: "hosted"; promoCode?: string }
): Promise<CheckoutSession> {
  const prices = await listAll<Price>("/prices");
  const price = prices.find((p) => p.active && p.lookupKey === "pro-monthly");
  if (!price) throw new Error("No price with lookupKey pro-monthly; run scripts/setup-catalog.mjs");
  let couponId: string | undefined;
  if (options.promoCode) {
    const coupons = await listAll<Coupon>("/coupons");
    couponId = coupons.find(
      (c) => c.active && c.code?.toUpperCase() === options.promoCode?.toUpperCase()
    )?.id;
  }
  return zahlo<CheckoutSession>("POST", "/checkout-sessions", {
    // One key per attempt; a network retry inside zahlo() reuses it.
    idempotencyKey: `subscribe-${user.id}-${crypto.randomUUID()}`,
    body: {
      type: "subscription",
      mode: "hosted", // the SEPA mandate page is hosted only
      paymentMethodTypes: ["sepa_direct_debit"],
      lineItems: [{ priceId: price.id, quantity: 1 }],
      couponId,
      customerEmail: user.email,
      reference: user.id,
      successUrl: `${siteUrl}/account?session_id={CHECKOUT_SESSION_ID}`,
      cancelUrl: `${siteUrl}/account`,
    },
  });
}
```

```typescript app/api/subscribe/route.ts




// Hosted checkout: create the session on the server, then send the browser to session.url.
export async function POST(request: Request) {
  const user = userFromRequest(request);
  if (!user) return new Response("Sign in first", { status: 401 });
  const promoCode = String((await request.formData()).get("promoCode") ?? "").trim() || undefined;
  try {
    const session = await createSubscriptionSession(user, { mode: "hosted", promoCode });
    return Response.redirect(session.url ?? "", 303);
  } catch (error) {
    if (error instanceof ZahloError) {
      console.error("subscribe failed", error.code, error.requestId);
      return new Response(error.message, { status: error.status >= 500 ? 502 : 400 });
    }
    throw error;
  }
}
```

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

```typescript lib/access.ts


// 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. */
export function hasAccess(user: User, now = new Date()): boolean {
  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;
}
```

```tsx app/account/page.tsx





export const dynamic = "force-dynamic";

// Shows access from the stored subscription. Returning from checkout grants nothing by itself:
// the webhook stores the subscription, usually within seconds.
export default async function AccountPage() {
  const id = (await cookies()).get("uid")?.value;
  const user = id ? (db.prepare("SELECT * FROM users WHERE id = ?").get(id) as User | undefined) : undefined;
  if (!user) {
    return (
      <form action="/api/signin" method="post">
        <input name="email" type="email" required placeholder="you@example.com" />
        <button type="submit">Sign in</button>
      </form>
    );
  }
  if (hasAccess(user)) {
    return (
      <form action="/api/portal" method="post">
        <p>Pro is active ({user.subscription_status}). Welcome, {user.email}.</p>
        <button type="submit">Manage billing</button>
      </form>
    );
  }
  return (
    <form action="/api/subscribe" method="post">
      <p>{user.subscription_id ? `Subscription ${user.subscription_status}.` : "Start your 14-day free trial."}</p>
      <input name="promoCode" placeholder="Promo code" />
      <button type="submit">Subscribe to Pro</button>
    </form>
  );
}
```

</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 Subscription = {
  id: string;
  status: string;
  pastDueSince: string | null;
  currentPeriodEnd: string | null;
};

const saveSubscription = (subscription: Subscription, userId?: string | null) => {
  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);
  }
};

export async function POST(request: Request) {
  // 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 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: () => void = () => {};
  if (event.type === "checkout.session.completed") {
    const session = await zahlo<CheckoutSession>("GET", `/checkout-sessions/${id}`);
    if (session.type === "subscription" && session.status === "complete" && session.subscriptionId) {
      const subscription = await zahlo<Subscription>("GET", `/subscriptions/${encodeURIComponent(session.subscriptionId)}`);
      apply = () => saveSubscription(subscription, session.reference);
    }
  } else if (event.type.startsWith("subscription.")) {
    const subscription = await zahlo<Subscription>("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 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.

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

```bash
npm run dev
```

Open `http://localhost:3000/account`, sign in with any email, enter `WELCOME15` and subscribe. On the mandate page, enter any name and a valid test IBAN such as `DE89 3704 0044 0532 0130 00`, and accept the mandate. Nothing is debited during the trial. Check that:

- your server logs `checkout.session.completed` and `subscription.created`, and `/account` 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 banking 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 |
| `sepa_returned` | the last paid debit comes back from the customer's bank (a return), as can happen days or weeks later |

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

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

The account page's **Manage billing** button posts to this route. It creates a single-use customer portal link (valid for one hour), where customers update their card, pay what is overdue or cancel. Create a fresh link on every click and never store it. You choose what customers may change in the dashboard under **Settings → Customer emails and portal**. Changes arrive as the usual `subscription.*` events, which your handler already stores. See [Customer portal](/guides/customer-portal).

```typescript app/api/portal/route.ts



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

// "Manage billing": a single-use customer portal link (valid for one hour) for the signed-in user.
// Create a fresh one on every click; never store it.
export async function POST(request: Request) {
  const user = userFromRequest(request);
  if (!user?.subscription_id) return new Response("No subscription", { status: 404 });
  const subscription = await zahlo<{ customerId: string }>(
    "GET",
    `/subscriptions/${encodeURIComponent(user.subscription_id)}`
  );
  const portal = await zahlo<{ url: string }>("POST", "/customer-portal/sessions", {
    body: { customerId: subscription.customerId, returnUrl: `${siteUrl}/account` },
  });
  return Response.redirect(portal.url, 303);
}
```

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

- **Processing debits**: a SEPA debit is `processing` for several banking days. The subscription counts as active meanwhile, so `hasAccess` keeps access; don't wait for the money to arrive.
- **Plans without a trial**: the subscription is `active` as soon as the customer accepts the mandate (`subscription.created` already carries it), and the first debit follows within minutes. Grant access from that status, not from a payment event. A failed or returned first debit makes it `past_due`, as below.
- **Returns**: the customer's bank can return a debit after it succeeded. The period becomes unpaid and the subscription `past_due`, 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>
