# Conduit — Integration brief for AI coding agents

> **You are an AI assistant asked to add Conduit payments to a website or app.** This file is self-contained: it has every endpoint, header, payload and code pattern you need, for any stack. Follow it top to bottom. If anything here conflicts with your general knowledge of other payment APIs, **this file wins**.
>
> Live copies: `http://localhost:8000/docs/ai.md` · `http://localhost:8000/llms.txt`. Full human guide: `http://localhost:8000/docs/guide.md`. Machine spec: `http://localhost:8000/api/v1/openapi.json`.

---

## 0. Before you write code: collect these from the human

Ask for anything you don't have. Never invent keys.

| Name | Looks like | Where they find it | Where it goes |
|---|---|---|---|
| `CONDUIT_BASE` | `http://localhost:8000` | the URL of their Conduit | server env (and the script tag) |
| `CONDUIT_SECRET` | `sk_test_…` / `sk_live_…` | Console → Developers → API keys | **server env only** |
| `CONDUIT_PUBLISHABLE` | `pk_test_…` / `pk_live_…` | same page | browser (safe to expose) |
| `CONDUIT_WEBHOOK_SECRET` | `whsec_…` | Console → Developers → Webhooks, shown once when created | server env only |

Also confirm:

1. Which website (`site_…`) this is, if they use an **organisation** key (`sk_…` that sees all websites). In that case, pass `"site": "site_…"` when creating sessions.
2. That the site's domain is registered in Console → Websites. Browser calls and `return_url` must be on a registered domain.
3. Start with **test keys**. Switch to live only when the human says so.

---

## 1. The model in 30 seconds

```
Website (site_…) ── Checkout session (cs_…) ── Payment (pay_…, reference "BX-…")
Customer (cus_…)  keyed by YOUR user id (customer.reference)
Events (evt_…)    every change; pushed to webhooks, also listable at GET /events
```

- **Amounts are major units** (`150` = GHS 150.00), as numbers. Currency comes from the website.
- **Auth:** `Authorization: Bearer <key>`. JSON in, JSON out. Base path `/api/v1`.
- **Every POST** should send `Idempotency-Key: <uuid>`.
- **Errors:** `{"error": {"type", "code", "message", "param"}}`. Branch on `error.code`; show `message` to users only where noted in section 10.

---

## 2. Pick the integration (decision tree)

```
Does the site have a backend you can change?
├─ NO (static site, site builder, no server)
│    └─ A. Pay button: one <script> + data attributes.               → section 3
└─ YES
     ├─ Customer buys a known thing (order, plan, cart, deposit)
     │    └─ B. Server creates a checkout session; then
     │         ├─ B1. redirect to session.url (simplest, works everywhere)      → section 4
     │         └─ B2. open it as an in-page modal with conduit.js               → section 4.3
     ├─ Staff need to see payments inside the site's admin panel
     │    └─ C. Embedded dashboard (iframe, per-staff roles)                     → section 7
     └─ Admin needs data in its own UI (tables, reports)
          └─ D. Management API with a restricted key                            → section 8
```

Every path ends the same way: **confirm on the server via webhook (section 5) or a GET (section 4.4) before giving value.** Most real integrations are **B + webhook**, and optionally C.

---

## 3. Path A — Pay button, no server code

```html
<script src="http://localhost:8000/js/v1/conduit.js" data-key="pk_test_XXXX" async></script>

<button data-conduit-pay data-amount="50" data-customer="USER_ID" data-description="Wallet top-up">Pay GHS 50</button>

<script>
  document.addEventListener("conduit:success", (e) => {
    // e.detail = the payment, e.g. { reference: "BX-…", status: "succeeded", amount: 50, … }
    // UI only! Do NOT credit anything here; the browser can lie. See section 5.
  });
  document.addEventListener("conduit:cancel", (e) => { /* modal closed or failed: e.detail.message */ });
</script>
```

Optional attributes:

- `data-ref="CODE"`: a referral code.
- `data-email`, `data-phone`, `data-name`.
- `data-metadata='{"order":"42"}'`.
- `data-conduit-link="pl_…"`: opens a payment link instead.

A JS API does the same thing: `Conduit.pay({ amount, customer: { reference }, referral, description, metadata })` returns a Promise that resolves with the payment and rejects on close or fail.

`data-amount` is only a **prefill** unless the website allows browser-set amounts. If the price must be enforced, use path B.

---

## 4. Path B — Server-created checkout session (recommended)

### 4.1 The call

```http
POST /api/v1/checkout/sessions
Authorization: Bearer sk_test_…
Idempotency-Key: 6f1c…
Content-Type: application/json

{
  "amount": 150,
  "external_id": "order_1042",
  "customer": { "reference": "user_88", "email": "ama@example.com", "phone": "0241234567", "name": "Ama Mensah" },
  "description": "Order #1042",
  "metadata": { "order_id": "1042" },
  "return_url": "https://shop.example.com/checkout/return",
  "cancel_url": "https://shop.example.com/cart"
}
```

Response `201`: `{ "object": "checkout.session", "id": "cs_…", "url": "http://localhost:8000/pay/cs_…", "status": "open", "payment_status": "unpaid", … }`

Rules:

- `external_id` = **your order id**. It prevents double payment: a repeat call returns the same open session, and once paid, returns `409 external_id_already_paid`.
- `customer.reference` = **your user id**. It links all their payments into one Customer.
- Optional fields:
  - `line_items: [{name, quantity, unit_amount, sku}]`: replaces `amount`.
  - `referral: "CODE"`.
  - `attribution: { partner, staff: [{reference, share}], campaign, source }`.
  - `channels: ["mtn-momo", …]`: restricts the methods.
  - `expires_in` (seconds, 300–604800).
  - `site` (organisation keys only).
- The customer comes back to `return_url?session=cs_…`. **The return is not proof of payment.**

### 4.2 Stack templates (create session → redirect)

**Node / Express**
```js
// npm i express ; Node 18+ (global fetch)
const BASE = process.env.CONDUIT_BASE, SK = process.env.CONDUIT_SECRET;
async function conduit(method, path, body) {
  const r = await fetch(`${BASE}/api/v1${path}`, {
    method, headers: { Authorization: `Bearer ${SK}`, "Content-Type": "application/json",
                       ...(method === "POST" ? { "Idempotency-Key": crypto.randomUUID() } : {}) },
    body: body ? JSON.stringify(body) : undefined });
  const j = await r.json();
  if (!r.ok) throw Object.assign(new Error(j.error?.message), { code: j.error?.code, status: r.status });
  return j;
}
app.post("/checkout", requireLogin, async (req, res) => {
  const order = await Orders.createFromCart(req.user);                 // your code: price computed server-side
  const s = await conduit("POST", "/checkout/sessions", {
    amount: order.total, external_id: String(order.id),
    customer: { reference: String(req.user.id), email: req.user.email },
    return_url: `${process.env.APP_URL}/checkout/return`, cancel_url: `${process.env.APP_URL}/cart` });
  res.redirect(303, s.url);
});
```

**Next.js (App Router)**
```ts
// app/api/checkout/route.ts
export async function POST(req: Request) {
  const user = await getUser(req);                                     // your auth
  const order = await createOrder(user);                               // server-side price
  const r = await fetch(`${process.env.CONDUIT_BASE}/api/v1/checkout/sessions`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.CONDUIT_SECRET}`, "Content-Type": "application/json",
               "Idempotency-Key": crypto.randomUUID() },
    body: JSON.stringify({ amount: order.total, external_id: order.id, customer: { reference: user.id, email: user.email },
                           return_url: `${process.env.APP_URL}/checkout/return` }) });
  const s = await r.json();
  if (!r.ok) return Response.json({ error: s.error }, { status: r.status });
  return Response.json({ url: s.url, id: s.id });                      // client: location.href = url  (or Conduit.checkout)
}
```

**PHP (plain) / Laravel**
```php
function conduit(string $method, string $path, ?array $body = null): array {
  $ch = curl_init(getenv('CONDUIT_BASE') . '/api/v1' . $path);
  $h = ['Authorization: Bearer ' . getenv('CONDUIT_SECRET'), 'Content-Type: application/json'];
  if ($method === 'POST') $h[] = 'Idempotency-Key: ' . bin2hex(random_bytes(16));
  curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $h, CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_TIMEOUT => 20, CURLOPT_POSTFIELDS => $body ? json_encode($body) : null]);
  $res = json_decode(curl_exec($ch), true); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
  if ($code >= 400) throw new RuntimeException($res['error']['message'] ?? 'Conduit error', $code);
  return $res;
}
// Laravel controller
public function checkout(Request $r) {
  $order = Order::fromCart($r->user());
  $s = conduit('POST', '/checkout/sessions', ['amount' => $order->total, 'external_id' => (string)$order->id,
        'customer' => ['reference' => (string)$r->user()->id, 'email' => $r->user()->email],
        'return_url' => route('checkout.return')]);
  return redirect()->away($s['url']);
}
```

**Python — Flask / Django**
```python
import os, uuid, requests
def conduit(method, path, body=None):
    r = requests.request(method, f"{os.environ['CONDUIT_BASE']}/api/v1{path}", json=body, timeout=20,
                         headers={"Authorization": f"Bearer {os.environ['CONDUIT_SECRET']}",
                                  **({"Idempotency-Key": str(uuid.uuid4())} if method == "POST" else {})})
    j = r.json()
    if r.status_code >= 400:
        raise RuntimeError(f"{j['error']['code']}: {j['error']['message']}")
    return j

# Flask
@app.post("/checkout")
@login_required
def checkout():
    order = create_order(current_user)
    s = conduit("POST", "/checkout/sessions", {"amount": float(order.total), "external_id": str(order.id),
        "customer": {"reference": str(current_user.id), "email": current_user.email},
        "return_url": url_for("checkout_return", _external=True)})
    return redirect(s["url"], 303)
# Django: same body; `return redirect(s["url"])` from a @login_required view.
```

**WordPress / WooCommerce** (minimal gateway; put in a small plugin)
```php
add_action('plugins_loaded', function () {
  class WC_Gateway_Conduit extends WC_Payment_Gateway {
    public function __construct() { $this->id = 'conduit'; $this->method_title = 'Conduit'; $this->title = 'Mobile money / card';
      $this->has_fields = false; $this->init_form_fields(); $this->init_settings(); }
    public function process_payment($order_id) {
      $o = wc_get_order($order_id);
      $r = wp_remote_post(CONDUIT_BASE . '/api/v1/checkout/sessions', ['timeout' => 20, 'headers' => [
          'Authorization' => 'Bearer ' . CONDUIT_SECRET, 'Content-Type' => 'application/json', 'Idempotency-Key' => wp_generate_uuid4()],
        'body' => wp_json_encode(['amount' => (float)$o->get_total(), 'external_id' => (string)$order_id,
          'customer' => ['reference' => (string)$o->get_customer_id(), 'email' => $o->get_billing_email(), 'phone' => $o->get_billing_phone()],
          'return_url' => $this->get_return_url($o), 'cancel_url' => wc_get_checkout_url()])]);
      $s = json_decode(wp_remote_retrieve_body($r), true);
      if (empty($s['url'])) { wc_add_notice($s['error']['message'] ?? 'Payment could not start.', 'error'); return ['result' => 'failure']; }
      return ['result' => 'success', 'redirect' => $s['url']];
    }
  }
  add_filter('woocommerce_payment_gateways', fn($g) => array_merge($g, ['WC_Gateway_Conduit']));
});
// Webhook: register_rest_route('conduit/v1','/webhook', ['methods'=>'POST','permission_callback'=>'__return_true','callback'=>…])
// In the callback, verify with $req->get_body() (section 5), then: wc_get_order($p['external_id'])->payment_complete($p['reference']);
```
Define `CONDUIT_BASE` and `CONDUIT_SECRET` in `wp-config.php`, not in the plugin.

### 4.3 In-page modal instead of redirect (B2)

Create the session on the server exactly as above. Return `id` to the browser, then:

```html
<script src="http://localhost:8000/js/v1/conduit.js" data-key="pk_test_XXXX" async></script>
<script>
  const { id } = await fetch("/api/checkout", { method: "POST" }).then(r => r.json());
  Conduit.checkout({ session: id, native: true });     // modal over your page
  Conduit.on("success", (p) => location.href = "/orders/thanks?ref=" + p.reference);   // UI only
</script>
```

You can also put `<button data-conduit-session="cs_…" data-conduit-native>` straight into server-rendered HTML.

### 4.4 The return page / polling

On `return_url?session=cs_…`, call `GET /api/v1/checkout/sessions/{cs_id}` **from your server** with the secret key:

- `payment_status: "paid"` and `payment.status: "succeeded"`: fulfil (idempotently).
- Otherwise, show "processing…" and let the webhook finish the job.

You can also look up by your own id: `GET /checkout/sessions/order_1042` or `GET /payments/order_1042` both work.

---

## 5. Webhooks — the only thing that should credit an order

1. Ask the human to add an endpoint in Console → Developers → Webhooks, or create it with `POST /api/v1/webhook_endpoints {"url":"https://YOUR_SITE/webhooks/conduit","events":["payment.*","session.*","refund.*"]}`. The response contains `secret` (`whsec_…`) **once**.
2. Verify the `Conduit-Signature` header: `t=<unix>,v1=<hex>`, where `v1 = HMAC_SHA256(secret, "<t>.<RAW body bytes>")`. Reject anything older than 300 s, and compare in constant time.
3. Use the **raw body**. Parsing then re-serialising the JSON breaks the signature.
4. Return `2xx` within 10 s. Delivery is at-least-once, so **dedupe on `event.id`** and make fulfilment idempotent on `payment.reference`.

```js
// Express — mount BEFORE app.use(express.json())
app.post("/webhooks/conduit", express.raw({ type: "application/json" }), async (req, res) => {
  const h = Object.fromEntries((req.get("Conduit-Signature") || "").split(",").map(s => s.split("=")));
  const mac = crypto.createHmac("sha256", process.env.CONDUIT_WEBHOOK_SECRET).update(`${h.t}.`).update(req.body).digest("hex");
  if (!h.v1 || Math.abs(Date.now() / 1000 - Number(h.t)) > 300 ||
      !crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(h.v1))) return res.sendStatus(400);
  const ev = JSON.parse(req.body);
  if (await Events.seen(ev.id)) return res.sendStatus(200);
  if (ev.type === "payment.succeeded") await fulfil(ev.data.object);   // see below
  await Events.markSeen(ev.id);
  res.sendStatus(200);
});
async function fulfil(p) {                       // p = payment object
  const order = await Orders.get(p.external_id);
  if (!order || order.paid) return;              // idempotent
  if (Number(p.amount_paid ?? p.amount) < Number(order.total)) return flagForReview(order, p);
  await Orders.markPaid(order.id, p.reference);
}
```

```ts
// Next.js App Router: app/api/webhooks/conduit/route.ts
import crypto from "crypto";
export async function POST(req: Request) {
  const raw = Buffer.from(await req.arrayBuffer());
  const h = Object.fromEntries((req.headers.get("conduit-signature") || "").split(",").map(s => s.split("=")));
  const mac = crypto.createHmac("sha256", process.env.CONDUIT_WEBHOOK_SECRET!).update(`${h.t}.`).update(raw).digest("hex");
  if (!h.v1 || Math.abs(Date.now() / 1000 - Number(h.t)) > 300 || !crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(h.v1)))
    return new Response("bad signature", { status: 400 });
  const ev = JSON.parse(raw.toString("utf8"));
  if (ev.type === "payment.succeeded") await fulfil(ev.data.object);
  return new Response("ok");
}
```

```php
// PHP / Laravel: exclude this route from CSRF (VerifyCsrfToken::$except)
$raw = file_get_contents('php://input');                       // Laravel: $request->getContent()
parse_str(str_replace(',', '&', $_SERVER['HTTP_CONDUIT_SIGNATURE'] ?? ''), $h);
if (empty($h['v1']) || abs(time() - (int)$h['t']) > 300 ||
    !hash_equals(hash_hmac('sha256', $h['t'] . '.' . $raw, getenv('CONDUIT_WEBHOOK_SECRET')), $h['v1'])) { http_response_code(400); exit; }
$ev = json_decode($raw, true);
if ($ev['type'] === 'payment.succeeded') fulfil($ev['data']['object']);
http_response_code(200);
```

```python
# Flask: request.get_data()   ·   Django: request.body + @csrf_exempt
import hmac, hashlib, time, json
def verify(raw: bytes, header: str, secret: str) -> bool:
    p = dict(x.split("=", 1) for x in header.split(",") if "=" in x)
    if "v1" not in p or abs(time.time() - int(p.get("t", 0))) > 300: return False
    mac = hmac.new(secret.encode(), p["t"].encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(mac, p["v1"])
```

**Events you'll usually handle:**

- `payment.succeeded`: fulfil.
- `payment.failed` and `payment.expired`: release stock, notify.
- `payment.refunded`: reverse.
- `session.abandoned`: has `recovery_url`; send it to the customer.
- `payment.held` / `payment.released`: platform risk review. **Still fulfil on `payment.succeeded`**; held only affects the merchant's payout.

**Safety net:** a cron job that calls `GET /api/v1/events?type=payment.*&created[gt]=<last seen>` and runs the same handler. Then a webhook outage can't lose orders.

---

## 6. Things you do NOT need code for (but must not break)

- **Direct payment options:** customers pay straight into the merchant's own MoMo, bank or crypto account, with no gateway. These options appear in the same checkout automatically. The payment then has `channel_kind: "direct"`, `next_action: "direct_transfer"` and a `direct` object (`account_number`, `account_name`, `amount`, `memo`, `instructions`). It confirms itself through the SMS inbox and fires the **same** `payment.succeeded`. If you build a **custom** checkout UI (rare), show `direct.account_*`, the exact `amount` and the `memo`. Otherwise do nothing.
- **Location targeting:** off by default, so payments are cross-border. If the merchant has targeted methods or bridges to places, the checkout hides what doesn't apply, using CDN headers (e.g. Cloudflare `CF-IPCountry`) and the phone's country code. If the site is behind a CDN, **forward its country header** to Conduit's checkout and don't strip it. A blocked attempt returns `403 channel_not_available_here`, which is safe to show.
- **Bridges, routing, retries and risk** are server-side at Conduit. Never hard-code a gateway.

---

## 7. Path C — Embed the whole dashboard in the site's admin panel

Prerequisites, done by the human in Console → Developers → Embedded dashboard:

- The feature must be enabled by the platform.
- Add the admin panel's origin (e.g. `https://admin.shop.example`) to **Sites allowed to frame it**.
- Create **roles** (e.g. `Finance`, `Support`, `Agent`). Each role sets its pages, read-only or can-act, websites, and data scope.

**Server:** mint a session when an authorised staff member opens the admin page. Never mint for anonymous users.

```js
// Express — inside YOUR admin auth
app.get("/admin/payments", requireAdmin, async (req, res) => {
  const s = await conduit("POST", "/embed/dashboard_sessions", {
    user: { id: String(req.user.id), name: req.user.name, email: req.user.email },
    role: req.user.isFinance ? "Finance" : "Support",          // role id (er_…) or name
    expires_in: 3600, theme: "auto", page: "payments" });
  res.render("admin/payments", { dashboardUrl: s.url });        // s.url is a secret: don't log it
});
app.get("/admin/conduit-session", requireAdmin, async (req, res) => {   // for refresh()
  const s = await conduit("POST", "/embed/dashboard_sessions", { user: { id: String(req.user.id) }, role: roleOf(req.user) });
  res.json({ url: s.url });
});
```

```php
$s = conduit('POST', '/embed/dashboard_sessions', ['user' => ['id' => (string)$admin->id, 'name' => $admin->name],
      'role' => $admin->can('finance') ? 'Finance' : 'Support', 'expires_in' => 3600]);
// echo into the page: $s['url']
```

**Page:**

```html
<div id="payments"></div>
<script src="http://localhost:8000/js/v1/conduit.js"></script>
<script>
  Conduit.dashboard({
    el: "#payments",
    url: DASHBOARD_URL_FROM_SERVER,
    refresh: () => fetch("/admin/conduit-session").then(r => r.json()).then(d => d.url),
    theme: "auto", minHeight: 600,
  });
</script>
```

- The iframe auto-resizes. On expiry it calls `refresh()` and swaps the URL.
- Returns `{ iframe, reload(url), destroy() }`.
- When a staff member is removed, call `POST /api/v1/embed/dashboard_sessions/revoke_user {"user":"<their id>"}`.
- Data scopes per role:
  - `staff_own`: shows only payments whose `attribution.staff` contains that user id. So **send `attribution.staff: [{reference: "<staff id>", share: 100}]` when staff create payments**.
  - `partner_own`: shows payments referred by that id.

---

## 8. Path D — Data for a custom admin UI

Use a **restricted key** (`rk_…`) with only the scopes you need, e.g. `payments:read`, `customers:read`, `refunds:write`.

| Need | Call |
|---|---|
| Recent payments | `GET /payments?status=succeeded&timeframe=7d&limit=50` (cursor: `starting_after=<next_cursor>`) |
| One payment | `GET /payments/{pay_… or reference or external_id}?expand[]=customer&expand[]=refunds` |
| Incremental sync | `GET /payments?sort=updated&updated[gte]=<last sync>` |
| Customer | `GET /customers/{your user id}` |
| Refund | `POST /payments/{reference}/refunds {"amount": 20, "reason": "requested_by_customer"}` |
| Totals | `GET /reports/summary?timeframe=30d` |
| What can this key do | `GET /me` |

Lists return `{ "object": "list", "data": [...], "has_more", "next_cursor" }`. The full list of 101 endpoints is at `GET /api/v1/openapi.json`.

---

## 9. Testing (do this before saying "done")

With `sk_test_` / `pk_test_` keys, sandbox phone numbers behave like this:

| Number | Result |
|---|---|
| any valid number | succeeds after ~6 s |
| ends in `000` | declined |
| ends in `111` | asks for OTP `123456` |
| ends in `222` | asks for PIN |
| ends in `999` | stays pending, then expires |

- **One-call end-to-end:** `POST /api/v1/test/payments {"amount": 100, "customer": {"reference": "user_88"}}` creates a session, pays it and fires webhooks. Add `"outcome": "failed"` for the failure path.
- **Webhook ping:** `POST /api/v1/webhook_endpoints/{id}/test {"type": "payment.succeeded"}`.
- Locally, expose the webhook with a tunnel (e.g. `ngrok http 3000`) and register that URL as a **test** endpoint.

---

## 10. Error codes to handle

| Code | HTTP | Do this |
|---|---|---|
| `amount_below_minimum` / `amount_above_maximum` | 400 | show `message` |
| `external_id_already_paid` | 409 | the order is already paid: show success / go to the order |
| `site_paused` | 423 | show `message` ("payments paused"); retry later |
| `customer_blocked`, `risk_blocked`, `route_blocked` | 403 | show a neutral "can't pay right now" (route_blocked `message` is safe to show) |
| `channel_closed`, `channel_not_available_here` | 400 / 403 | show `message`; let them pick another method |
| `no_gateway`, `platform_maintenance` | 503 | "try again shortly"; retry with backoff |
| `url_not_allowed` | 400 | `return_url` domain isn't registered on the website; tell the human |
| `origin_not_allowed` | 403 | the browser page's domain isn't registered; tell the human |
| `invalid_api_key`, `secret_key_required`, `insufficient_scope`, `site_required` | 401/403 | wrong key or key type; fix the config |
| `idempotency_key_reused` | 409 | you reused an Idempotency-Key with a different body; generate a new one per logical request |
| `embed_disabled`, `role_not_found`, `feature_disabled` | 403/404 | feature or role not set up; tell the human |
| `rate_limited` | 429 | wait `Retry-After` seconds |

---

## 11. Pitfalls agents commonly hit

1. **Putting `sk_` in frontend code**, or in `NEXT_PUBLIC_*` / `VITE_*` env vars. Only `pk_` may reach the browser.
2. **Crediting on `return_url` or a JS success callback.** Credit only on a verified webhook or a server-side GET.
3. **Parsing the webhook body before verifying.** Express `json()` middleware and Next.js `req.json()` both destroy the raw body.
4. **CSRF middleware** (Laravel, Django, Rails) blocking the webhook route. Exempt only that route.
5. **Sending minor units.** `150` means 150.00, not 1.50.
6. **Computing the price in the browser.** Compute the amount on the server, from your database.
7. **Missing `external_id`.** Without it, double-clicks can create double payments.
8. **Unregistered domains.** `return_url`, `cancel_url` and the page using `pk_` must be on the website's registered domains.
9. **Logging the embedded dashboard URL**, or caching the admin page that contains it. It is a bearer credential.
10. **Using test keys in production**, or live keys in CI.

---

## 12. Definition of done (verify each)

- [ ] Secrets in env vars / secret store; `.env` is git-ignored; `pk_` only in the browser.
- [ ] Checkout creates a session server-side with `amount` from the database, `external_id`, and `customer.reference`.
- [ ] Webhook route verifies `Conduit-Signature` against the raw body, dedupes on `event.id`, and fulfils idempotently.
- [ ] Return page shows the status from a server-side GET, not query params.
- [ ] Test run: success (any number), decline (`…000`) and OTP (`…111`) all behave; `POST /test/payments` triggers your webhook and marks an order paid exactly once even if replayed.
- [ ] Error codes from section 10 render friendly messages.
- [ ] (If C) Dashboard shows for an admin and refuses for non-admins; the session URL never appears in logs.
- [ ] Tell the human the steps only they can do: register domains, create the webhook endpoint and paste `whsec_`, create embed roles and framing origins, switch to live keys.
