# Conduit — Platform Integration Guide

> Everything you need to integrate Conduit into your product: accepting payments, identifying customers, crediting partners and staff, refunds, webhooks, and building your own admin panel on top of the Conduit API. This guide covers integration only. For the console, see the in-app help.

**API base URL:** `http://localhost:8000/api/v1` · **API version:** `2026-11-01` · **Format:** JSON over HTTPS

> **Integrating with an AI coding assistant?** Give it [`/docs/ai.md`](http://localhost:8000/docs/ai.md) (also at `/llms.txt`). It is a single self-contained brief written for AI agents.

---

## 1. The mental model

```
Your organisation (client)
 ├── Websites (site_…)           each has its own keys, domains, limits, channels, look
 │    ├── Checkout sessions (cs_…)   one purchase attempt; hosted page or in-page modal
 │    │    └── Payments (pay_…)      the actual charge(s); reference e.g. BX-K7QX-LZ9F2K1A8Q
 │    ├── Payment links             reusable URLs
 │    └── Referral codes            per-site codes with their own min/max, owned by a partner
 ├── Customers (cus_…)            your payers, keyed by YOUR user id, shared across websites
 ├── Partners (ptn_…)             affiliates / agents / staff / influencers / resellers, with an upline
 ├── Commission rules (cr_…)      who earns what, on which payments
 ├── Commission ledger (com_…)    immutable lines: pending → available → paid (or reversed)
 ├── Refunds (re_…)
 └── Events (evt_…)               every state change, stored; delivered to your webhook endpoints
```

Three rules that make integrations simple:

1. **Everything is site-bound.** A payment belongs to exactly one website. A key for website A can never see or create anything on website B.
2. **Your ids travel with everything.** Pass your order id as `external_id`, your user id as `customer.reference` and your partners' user ids as `reference`. You never have to store Conduit ids if you don't want to — every retrieve endpoint also accepts your id.
3. **Events are the source of truth.** Every change is stored as an event (`GET /events`) and pushed to your endpoints. If your server was down, you catch up. Nothing is lost.

---

## 2. Choose your integration

| You want… | Use | Effort |
|---|---|---|
| A "Pay" button that opens a modal **inside your page**, no redirect | Native embed: `<script src="…/js/v1/conduit.js" data-key="pk_…">` + `data-conduit-pay` | 2 lines of HTML |
| Your server decides the amount, the customer is redirected to a hosted checkout | `POST /checkout/sessions` → redirect to `url` | ~20 lines |
| The same, but shown in the modal | `POST /checkout/sessions` → `Conduit.pay({ session: id })` | ~25 lines |
| A link to share (WhatsApp, email, bio) | Payment links (console or `POST /links`) | none |
| Pre-filled, tamper-proof links from your server | `POST /links/sign` | ~10 lines |
| Your **admin panel** to show payments, customers, partners and reports | Organisation or restricted key + the Management API (sections 9–11) | your UI |
| The **whole Conduit dashboard inside your admin panel**, per-staff access | `POST /embed/dashboard_sessions` + `Conduit.dashboard()` (section 17) | ~15 lines |
| Customers pay **straight into your own account**, no gateway | Direct payment options (section 15) | console only |

All of them produce the same payment object, the same webhooks and the same ledger.

---

## 3. Keys and authentication

Send keys as a bearer token:

```http
Authorization: Bearer sk_test_51…
```

| Key | Prefix | Where | Sees | Notes |
|---|---|---|---|---|
| Website secret | `sk_live_` / `sk_test_` | your server | one website | full access to that website |
| Website publishable | `pk_live_` / `pk_test_` | browser | one website | origin-checked against the website's domains; only `/public/*` and `POST /embed/sessions` (the checkout modal) |
| **Organisation** secret | `sk_…` created in *Developers → Org & restricted keys* | your server / back-office | **all websites** | pass `site=site_…` on site-specific calls (creating sessions, links, referral codes) |
| **Restricted** | `rk_live_` / `rk_test_` | any internal tool | one website or all | only the **scopes** you tick |

**Scopes** (restricted keys): `sessions:read|write`, `payments:read|write`, `refunds:read|write`, `customers:read|write`, `partners:read|write`, `commissions:read|write`, `referrals:read|write`, `links:read|write`, `sites:read|write`, `webhooks:read|write`, `events:read`, `reports:read`, `balance:read`, `embed:read|write` (dashboard sessions). A `:write` scope implies the matching `:read`. `GET /api/v1/scopes` lists every scope and the endpoints it unlocks.

Suggested keys for a typical stack:

- **Checkout backend:** website secret key (or restricted with `sessions:write`, `payments:read`).
- **Admin panel:** organisation restricted key with every `:read` plus `payments:write`, `refunds:write`, `customers:write`, `partners:write` and `commissions:write`.
- **Support desk:** restricted with `payments:read`, `customers:read`, `refunds:read|write` and `events:read`.
- **Partner portal (your affiliates log in to your site):** restricted with `partners:read`, `commissions:read`, `referrals:read` and `reports:read`.

**Discover a key:** `GET /me` returns the key kind, scopes, reach (website or organisation), mode, enabled features and the websites it can see. Call it on boot.

**Test vs live:** test keys only see test data and only move sandbox money. Test and live are completely separate worlds: customers, commissions and events are per mode.

**Rotation:** roll a key in the console; the old one keeps working for the grace period you choose. Revoking is immediate.

---

## 4. API conventions

### Responses and errors

Every response carries `Conduit-Version` and `X-Request-Id` headers. Errors look like this:

```json
{
  "error": {
    "type": "invalid_request_error",
    "code": "amount_below_minimum",
    "message": "The minimum deposit is GHS 20.00.",
    "param": "amount",
    "doc_url": "http://localhost:8000/docs/api#errors"
  },
  "request_id": "req_8Kq2…"
}
```

Branch on `error.code`, never on `message`. HTTP status families:

- `400`: bad input.
- `401`: key missing or invalid.
- `403`: scope, feature, origin or account problem.
- `404`: not found.
- `409`: conflict (already paid, idempotency reuse).
- `410`: gone.
- `423`: website paused.
- `429`: rate limited.
- `5xx`: our side, safe to retry.

### Idempotency

Send `Idempotency-Key: <uuid>` on every `POST`. A retry with the same key and body returns the original response, with `Idempotent-Replayed: true`. The same key with a different body returns `409 idempotency_key_reused`. Keys are kept for 24 hours.

For checkouts there is a second, business-level guard: **`external_id`**. One open checkout per order id per website. A second create returns the same open session. Once paid, a create returns `409 external_id_already_paid`, so a customer can never pay the same order twice.

### Pagination

Lists return an envelope:

```json
{ "object": "list", "url": "/api/v1/payments", "data": [ … ], "has_more": true, "next_cursor": "pay_9fK2…" }
```

- Use `limit` (1–100, default 25).
- Pass `starting_after=<next_cursor>` for the next page, or `ending_before=<id>` for the previous one.
- Add `include_total=1` for a `total_count`. It's slower, so request it only when you show it.

### Filtering by time

Every list accepts:

- `created[gte|gt|lte|lt]` and `updated[gte|gt|lte|lt]`, as ISO-8601 or unix seconds.
- `timeframe`: `today`, `yesterday`, `3d`, `7d`, `14d`, `30d`, `90d`, `this_month`, `last_month`, `this_year`, `1y` or `all`.
- `timeframe=custom&from=…&to=…`.

**Incremental sync:** `GET /payments?sort=updated&updated[gte]=<last sync time>` returns everything that changed. See section 11.

### Expanding related objects

`GET /payments/{id}?expand[]=customer&expand[]=partner&expand[]=commissions&expand[]=refunds&expand[]=events&expand[]=session`. One call, one round-trip.

### Metadata

`metadata` is a free JSON object up to 4 KB, echoed in webhooks. On update it **merges**: a key set to `null` is deleted, and `"metadata": ""` clears everything.

### Rate limits

Every key has a per-minute budget, shown in `X-RateLimit-Limit` and `X-RateLimit-Remaining`. A `429` carries `Retry-After`. Use backoff, and spread bulk syncs.

### Your ids work everywhere

| Endpoint | Accepts |
|---|---|
| `GET /payments/{id}` | `pay_…`, the payment `reference`, or your `external_id` |
| `GET /checkout/sessions/{id}` | `cs_…` or your `external_id` |
| `GET /customers/{id}` | `cus_…` or your user id (`reference`) |
| `GET /partners/{id}` | `ptn_…` or the partner's user id |

---

## 5. Accepting a payment

### 5.1 Create a checkout session (server)

```bash
curl http://localhost:8000/api/v1/checkout/sessions \
  -H "Authorization: Bearer $CONDUIT_SECRET" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 150,
    "external_id": "order_1042",
    "customer": { "reference": "user_88", "phone": "0241234567", "name": "Ama Mensah" },
    "referral": "KOFI10",
    "attribution": {
      "staff": [ { "reference": "agent_7", "share": 60 }, { "reference": "agent_9", "share": 40 } ],
      "campaign": "black-friday", "source": "instagram"
    },
    "line_items": [ { "name": "Gold plan", "quantity": 1, "unit_amount": 150, "sku": "GOLD" } ],
    "tags": ["subscription"],
    "metadata": { "cart_id": "c_77" },
    "return_url": "https://shop.example.com/thanks"
  }'
```

| Field | Meaning |
|---|---|
| `amount` | Major units. Omit it and the customer chooses an amount within your limits. With `line_items` it's computed. |
| `external_id` | Your order id. Gives dedupe and safe retries, and works as a lookup id. |
| `customer.reference` | **Your user id.** It creates or links a Customer (`cus_…`), which carries lifetime value, the sticky referrer and blocks. |
| `referral` | Referral code. It applies that code's minimum and maximum and credits its partner. |
| `attribution.partner` | Credit a partner directly (`ptn_…` or their user id) when there's no code. |
| `attribution.staff[]` | **Several people on one payment.** Each gets their `share` % of the staff commission. Unknown references are created as staff partners automatically. |
| `attribution.campaign/source/medium/utm` | Stored on the payment and filterable. Useful for marketing reports. |
| `channels` | Restrict to some channel codes. |
| `expires_in` | Seconds (300 – 604800). |

The response includes `url` (the hosted checkout) and `id`.

### 5.2 Send the customer to pay

- **Redirect:** `302` to `session.url`. The customer returns to `return_url?session=cs_…`.
- **In-page modal:**

```html
<script src="http://localhost:8000/js/v1/conduit.js" data-key="pk_live_…" async></script>
<script>
  const payment = await Conduit.pay({ session: "cs_…" });   // resolves when paid, rejects on close/fail
</script>
```

- **No server at all (native embed):** `<button data-conduit-pay data-amount="50" data-customer="user_88">Deposit</button>`. The browser can't set staff attribution, and amounts are only a prefill unless your website allows browser-set amounts.

### 5.3 Confirm on your server — never trust the browser

Credit the order when **either** of these arrives (dedupe by `reference`):

1. the signed webhook `payment.succeeded` (section 8), or
2. `GET /payments/{reference}` returning `"status": "succeeded"`.

```js
// Express: idempotent fulfilment
async function fulfil(payment) {
  const done = await db.orders.findOne({ paymentRef: payment.reference });
  if (done) return;                                   // already credited — webhooks can repeat
  await db.orders.update({ id: payment.external_id }, { paid: true, paymentRef: payment.reference });
}
```

Check `amount_paid` against what you expected. `underpaid: true` flags short payments.

### 5.4 Payment methods (channel kinds)

| `channel_kind` | What the customer does | Processed by |
|---|---|---|
| `momo` | Approves a prompt / OTP / PIN on their phone | Paystack, PHP bridges, HTTP bridges |
| `card`, `bank` | Card page or bank flow (redirect) | Paystack, HTTP bridges |
| `direct` | Sends money **straight to a collection account**, then enters the transaction ID | Direct collection accounts |
| `ussd`, `qr`, `wallet` | Dial a code / scan / approve in an app | HTTP bridges |

**Direct deposits in your own UI.** When `next_action` is `direct_transfer`, the payment carries a `direct` object:

```json
"direct": { "account_kind": "momo", "provider": "MTN MoMo", "account_number": "0551234987",
            "account_name": "LUMEN STORE LTD", "amount": "250.00", "currency": "GHS",
            "memo": "K7Q2LX", "instructions": "Dial *170# › Transfer…", "txid": null, "confirmed": false }
```

Show the account details and the **memo**, and ask the customer to put the memo in the transfer's reference field. Conduit's SMS inbox confirms the payment by itself, usually within a minute. If the customer gives you the transaction ID, submit it with `kind: "submit_txid"`. The hosted checkout and `conduit.js` already do all of this.

### 5.5 Payment statuses

`initiated` → `action_required` (OTP/PIN/redirect/direct transfer) → `pending` (waiting for the network) → **`succeeded`** | `failed` | `expired`.

Every payment carries `risk: {score, held}`. A **held** payment is a normal success for the customer (fulfil it), but the platform has put it under review, so the money stays out of your payroll until it's approved. You receive `payment.held` and later `payment.released`.

A refund changes `refund_status` (`none` / `partial` / `full`) and `amount_refunded`, not `status`.

---

## 6. Customers

A **Customer** is created automatically the first time someone pays, matched by `customer.reference` (your user id) or else by phone. You can also create customers up front.

```bash
POST /customers   { "reference": "user_88", "name": "Ama", "phone": "0241234567", "partner": "user_kofi" }
```

- **Upsert:** posting an existing `reference` updates and returns it (`200` instead of `201`).
- **Sticky referrer:** the first partner to bring a customer (via code, `attribution.partner` or `partner` on create) is remembered for life. With a *sticky* commission rule, that partner earns on the customer's future payments too, even without a code.
- **Lifetime value:** `payments_count`, `lifetime_value`, `first_paid_at` and `last_paid_at` update on every settlement.
- **Blocking:** `POST /customers/{id}/block`. Checkouts for that customer, on any website, fail with `403 customer_blocked`. The phone number is blocked too.
- `GET /customers/{id}/payments` gives the customer's history. `GET /customers?q=…&partner=…&min_ltv=…` searches.

---

## 7. Partners, referrals and commissions

This is how money gets **credited to the people involved**: affiliates who sent the customer, the agent who closed the sale, the cashier who took it, and their uplines.

### 7.1 Partners

```bash
POST /partners
{ "reference": "user_kofi", "name": "Kofi Boateng", "kind": "agent",
  "parent": "user_ama", "code": "KOFI10", "site": "site_…" }
```

- `kind` is one of `affiliate`, `agent`, `staff`, `influencer` or `reseller`.
- `parent` builds a multi-level tree. `GET /partners/{id}/downline?depth=3` returns the tree.
- `code` issues a referral code for them in the same call. You can also use `POST /partners/{id}/codes`.
- Upserts by `reference`, so you can call it whenever a user becomes a partner on your platform.

### 7.2 How a payment finds its people

When a payment succeeds, Conduit resolves the people involved:

1. **Referrer**, in priority order:
   1. the **referral code**'s partner
   2. `attribution.partner`
   3. the customer's **sticky referrer**
2. **Upline**: the referrer's parent, grandparent and so on (levels 2, 3, …).
3. **Staff**: everyone in `attribution.staff[]`, split by `share`. Shares are normalised: missing shares split the remainder equally, and totals over 100 are scaled down.

### 7.3 Commission rules

```bash
POST /commission_rules
{ "name": "Agents 3-tier", "applies_to": "referrer", "levels": [10, 3, 1],
  "trigger": "every", "attribution": "sticky", "basis": "net",
  "min_payment": 20, "cap": 500, "hold_days": 7, "is_default": true }
```

| Field | Values |
|---|---|
| `applies_to` | `referrer` (+ upline), `staff`, `both` |
| `levels` | percent per level: `[10, 3, 1]` means the direct referrer gets 10%, their upline 3%, the next 1% |
| `flat` | flat bonus added to level 1 |
| `trigger` | `every`, `first` (first payment only), `first_n` (with `first_n`) |
| `attribution` | `sticky` (customer's referrer for life) or `payment` (only when the code/partner is on this payment) |
| `basis` | `net` (after fees) or `gross` |
| `min_payment`, `cap`, `hold_days`, `site`, `channels` | guards and scope |

- **Staff rule:** `levels[0]` is the pool percentage that is split among the staff by share.
- **Overrides:** give a partner `rule: "cr_…"` to override the default rule for them.
- **Dry run:** `POST /commissions/simulate { "amount": 200, "partner": "user_kofi", "staff": [...] }` returns the lines that *would* be written. Use it to show partners their potential earnings, or to test a rule change.

### 7.4 The ledger

Every credit is an immutable **commission line**:

`pending` (hold period) → `available` → `paid`, with `reversed` or `void` as side exits.

- A line can never be written twice for the same partner, payment, level and role, so settlement re-runs are harmless.
- **Refund → claw-back.** When a payment is refunded, its unpaid lines are reversed. Already-paid lines get a negative `adjustment` line that nets off the partner's next payout.
- **Release early:** `POST /commissions/{id}/approve`. **Void:** `POST /commissions/{id}/void`.
- **Bonus or deduction:** `POST /commissions { "partner": "user_kofi", "amount": 50, "reason": "November target" }`.
- **Late attribution:** the agent was entered after the fact? `POST /payments/{id}/attribution { "partner": "user_kofi", "staff": [...] }` runs the rules on a settled payment.

### 7.5 Paying partners

You pay partners yourself (bank, MoMo, or credit on your own platform), then record it:

```bash
POST /partners/user_kofi/payouts   { "method": "MoMo", "reference": "TX-88123" }
```

This marks every available line as paid (or only the `commissions: [ids]` you pass) and emits `commission.paid`. `GET /partners/{id}/balance` returns pending, available, paid and lifetime totals. `GET /reports/partners` is the leaderboard.

### 7.6 Recipes

**Affiliate link → lifetime commission**

1. Create the partner with `code: "AMA5"`.
2. Share `https://yourshop.com/?ref=AMA5` and pass `referral: "AMA5"` when you create the session.
3. Use a sticky rule.

The customer's later purchases keep crediting Ama, even without the code.

**A sale closed by two agents and a cashier**

Send `attribution.staff = [{agent_7, 50}, {agent_9, 30}, {cashier_3, 20}]` and use a staff rule with `levels: [5]`. The 5% pool is split 50/30/20.

**MLM / reseller tree**

Give each reseller a `parent`, and set `levels: [8, 4, 2, 1]`.

---

## 8. Webhooks and events

### 8.1 Endpoints

```bash
POST /webhook_endpoints
{ "url": "https://admin.example.com/hooks/conduit", "events": ["payment.*", "refund.*", "commission.*"] }
```

- **Website endpoint:** pass `site`, or use a website key. It receives that website's events.
- **Organisation endpoint:** use an organisation key and omit `site`. It receives events from **every** website plus organisation-level events: partners, commissions and payroll.
- The `secret` (`whsec_…`) is returned once. Rotate it with `POST /webhook_endpoints/{id}/roll_secret`.
- `POST /webhook_endpoints/{id}/test { "type": "payment.succeeded" }` sends a realistic sample now.

### 8.2 Envelope

```json
{
  "id": "evt_3kQ…", "object": "event", "api_version": "2026-11-01",
  "type": "payment.succeeded", "created": 1763560000, "livemode": true,
  "client": "cl_…", "site": "site_…",
  "data": { "object": { "object": "payment", "id": "pay_…", "reference": "BX-…", "status": "succeeded", … } }
}
```

### 8.3 Event types

| Area | Events |
|---|---|
| Payments | `payment.succeeded`, `payment.failed`, `payment.pending`, `payment.action_required`, `payment.expired`, `payment.updated`, `payment.refunded`, `payment.held`, `payment.released` |
| Sessions | `session.completed`, `session.expired`, `session.abandoned` (with `recovery_url`) |
| Refunds | `refund.created`, `refund.succeeded`, `refund.failed` |
| Customers | `customer.created`, `customer.updated` |
| Partners | `partner.created`, `partner.updated` |
| Commissions | `commission.created`, `commission.available`, `commission.paid`, `commission.reversed` |
| Payroll | `payout.paid` |
| Websites | `site.paused`, `site.resumed` |

Subscribe with exact types or wildcards (`payment.*`). An empty list means all events.

### 8.4 Verify the signature

The `Conduit-Signature` header looks like `t=<unix>,v1=<hex>`, where `v1 = HMAC_SHA256(secret, "<t>.<raw body>")`. Reject anything older than 5 minutes, and compare in constant time.

```python
import hmac, hashlib, time
def verify(raw_body: bytes, header: str, secret: str, tolerance=300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    t, sig = int(parts["t"]), parts["v1"]
    if abs(time.time() - t) > tolerance:
        return False
    mac = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(mac, sig)
```

```js
const crypto = require("crypto");
function verify(rawBody, header, secret, tolerance = 300) {
  const p = Object.fromEntries(header.split(",").map(s => s.split("=")));
  if (Math.abs(Date.now() / 1000 - Number(p.t)) > tolerance) return false;
  const mac = crypto.createHmac("sha256", secret).update(`${p.t}.`).update(rawBody).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(p.v1));
}
```

```php
function conduit_verify(string $raw, string $header, string $secret, int $tol = 300): bool {
  parse_str(str_replace(',', '&', $header), $p);
  if (abs(time() - (int)$p['t']) > $tol) return false;
  return hash_equals(hash_hmac('sha256', $p['t'] . '.' . $raw, $secret), $p['v1']);
}
```

Use the **raw** request body. Re-serialising the JSON breaks the signature.

### 8.5 Delivery semantics

- **At-least-once.** The same event can arrive twice, so dedupe on `id`. Ordering is not guaranteed, so use `created` or re-fetch the object.
- Return `2xx` within 10 seconds and do the slow work after.
- **Retries:** 1 min, 5 min, 15 min, 1 h, 3 h, 6 h, 12 h, 24 h. An endpoint is disabled after 50 consecutive failures, and you are notified.
- `GET /webhook_deliveries` is the delivery log. `POST /webhook_deliveries/{id}/retry` retries one delivery, and `POST /events/{id}/redeliver` resends an event.

### 8.6 The event log: never miss anything

Every event is stored, even with no endpoints. A small cron job makes you immune to webhook outages:

```python
cursor = load("last_event_time")
for ev in conduit.list("/events", params={"created[gt]": cursor, "type": "payment.*"}):
    handle(ev)                 # same handler as your webhook, same dedupe on ev["id"]
    save("last_event_time", ev["created"])
```

---

## 9. Refunds

```bash
POST /payments/BX-K7QX-LZ9F2K1A8Q/refunds   { "amount": 20, "reason": "requested_by_customer", "note": "size swap" }
```

- Omit `amount` for a full refund. Partial refunds can repeat up to the refundable amount (`GET /payments/{id}/refunds` returns `refundable`).
- **Paystack** payments are refunded through the processor automatically. **Mobile-money bridge** payments become `requires_action`: send the money back, then `POST /refunds/{id}/confirm`. `POST /refunds/{id}/cancel` abandons a refund.
- On success:
  - the payment's `amount_refunded` and `refund_status` update
  - partner commissions are clawed back
  - `refund.succeeded` and `payment.refunded` fire
  - if the platform collected the money, the refund is deducted from your next payroll

---

## 10. Building your admin panel on Conduit

Conduit is designed to be the backend of **your** back-office. One organisation restricted key and the endpoints below power a complete admin.

| Screen in your admin | Calls |
|---|---|
| Dashboard KPIs with "vs last period" | `GET /reports/summary?timeframe=30d` |
| Revenue chart | `GET /reports/timeseries?timeframe=30d` (zero-filled buckets) |
| Split by channel / website / partner / referral | `GET /reports/breakdown?by=channel` |
| Conversion funnel | `GET /reports/funnel` |
| Payments table with search, filters, totals | `GET /payments?q=&status=&timeframe=&include_summary=1&expand[]=customer` |
| Payment drawer: timeline, notes, refunds, commissions | `GET /payments/{id}?expand[]=events&expand[]=refunds&expand[]=commissions`; `POST /payments/{id}/notes` |
| Customers CRM | `GET /customers?q=&min_ltv=`, `GET /customers/{id}/payments`, block/unblock |
| Partner directory and tree | `GET /partners?with_balance=1`, `GET /partners/{id}/downline` |
| Partner portal (for your affiliates) | `GET /partners/{id}/stats?timeframe=this_month`, `/balance`, `GET /commissions?partner=…` |
| Commission approvals and payouts | `GET /commissions?status=pending`, `POST /commissions/{id}/approve`, `POST /partners/{id}/payouts` |
| Top customers, new vs returning | `GET /reports/customers` |
| Finance exports | `GET /exports/payments?timeframe=last_month` (CSV), plus `refunds`, `customers` and `commissions` |
| Platform balance and payroll | `GET /balance`, `GET /payouts` |
| Maintenance switch | `POST /sites/{id} { "status": "paused", "paused_reason": "…" }` |

**Multiple staff working on the same payment:**

- Notes (`POST /payments/{id}/notes` with `author`) are visible to everyone in the console and the API.
- `payment.updated` events let every admin screen refresh.
- Metadata merges instead of overwriting, so two staff members editing different keys never clobber each other.

---

## 11. Making your platform resilient when it depends on Conduit

Design so that your product keeps working even when networks misbehave.

1. **Idempotency everywhere.**
   - Send `Idempotency-Key` on every POST, and generate it once per user action, not per HTTP attempt.
   - Pass `external_id` on every checkout, so retries and double-clicks resolve to the same session.
2. **Timeouts and retries.**
   - Use a 10–15 s timeout.
   - Retry `429`, `5xx` and network errors with exponential backoff and jitter (0.5 s, 1 s, 2 s, 4 s; 4 tries).
   - Never retry `4xx` other than `409 idempotency` replays and `429`. The SDKs do all of this for you.
3. **Two confirmation paths.** Fulfil from webhooks *and* run the events catch-up cron (section 8.6). Either one alone is enough. Both together make you immune to a missed delivery.
4. **Local mirror for reads.** Sync with `sort=updated&updated[gte]=<last>` every minute, or on each webhook, into your own tables. Your admin then reads locally, stays fast, and keeps working if Conduit is unreachable.
5. **Degrade gracefully.**
   - `423 site_paused`: show the `message` and hide pay buttons. Scheduled pauses (maintenance windows) return the same code, with your scheduled message.
   - `403 risk_blocked` / `route_blocked`: show the message as-is. It is written for customers and reveals nothing about your rules.
   - `503 no_gateway`: show "payments temporarily unavailable" and keep the cart.
   - Watch `GET /health` (no auth) from your status page.
6. **Reconcile.** Nightly, run `GET /payments?timeframe=yesterday&status=succeeded` against your orders, and alert on mismatches. `GET /exports/payments` gives finance the same as CSV.
7. **Key hygiene.**
   - Use restricted keys per service.
   - Give organisation keys only to back-office systems.
   - Use publishable keys only in browsers.
   - Rotate with overlap.
   - Use the website IP allow-list for secret keys.
8. **Version pinning.** Read `api_version` in webhooks and the `Conduit-Version` header. Additive changes (new fields, new events) can appear at any time, so ignore unknown fields.

---

## 12. Testing

- Use `sk_test_` / `pk_test_` keys. Sandbox phone numbers:

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

- `POST /test/payments` runs a **complete payment in one call**: session → payment → settlement → customer → commissions → webhooks. It's ideal for CI.

```bash
curl -X POST http://localhost:8000/api/v1/test/payments -H "Authorization: Bearer sk_test_…" \
  -d '{"amount":100,"customer":{"reference":"user_88"},"referral":"KOFI10",
       "attribution":{"staff":[{"reference":"agent_7","share":100}]}}'
```

  Pass `"outcome": "failed"` to exercise failure paths.

- `POST /test/events { "type": "commission.created" }` fires a sample to your test endpoints.
- Import the **Postman collection** (`GET /api/v1/postman.json`) or the **OpenAPI 3.1** spec (`GET /api/v1/openapi.json`) to generate a typed client in any language.

---

## 13. Abandoned checkout recovery

When a checkout that has the customer's phone or email sits unpaid for the platform's recovery delay (default 30 minutes), you get **one** `session.abandoned` event. It includes `recovery_url`, a link that resumes the same checkout. Send it by SMS, email or WhatsApp. If they pay, the session is marked `recovered`, and the platform reports your recovery rate.

## 14. Go-live checklist

- [ ] Live website created, domains verified, `enforce_origin` on.
- [ ] Live secret key in your server's secret store, not in the repo. Publishable key in the page.
- [ ] Webhook endpoint on `https://`, signature verified with the raw body, dedupe on `event.id`.
- [ ] Fulfilment is idempotent (keyed on `reference` or `external_id`).
- [ ] Events catch-up cron running.
- [ ] `external_id` sent on every checkout; `customer.reference` sent where you have a user.
- [ ] Commission rules reviewed with `/commissions/simulate`; hold days set to cover your refund window.
- [ ] Restricted keys for admin, support and partner portals; IP allow-list for secret keys.
- [ ] Error UI for `site_paused`, `amount_below_minimum`, `customer_blocked` and `no_gateway`.
- [ ] Nightly reconciliation alert.

---

## 15. Direct payment options (no bridge)

Besides the platform's processors and bridges, you can add your **own** payment options. Customers pay straight into your MoMo wallet, bank account or crypto address. No gateway or bridge sits in between, and the money is yours the moment it lands. Bridges and platform channels keep working alongside: a direct option is just one more method in the same checkout.

**Set it up** in *Console → Payment options → Add a direct option*:

| Field | What it does |
|---|---|
| Type | `momo`, `bank`, `crypto` or `other` |
| Provider / number / account name | Shown to the customer exactly as typed |
| Instructions | One line, e.g. "Dial *170# › Transfer Money › MoMo User" |
| Ask for the transaction ID | The customer types the transfer's ID after paying. It gives faster, safer matching |
| Websites | All of them, or only the ones you tick |
| Locations | Anywhere by default, or targeted (section 16) |
| SMS matching | Optional regexes for your bank's alert format: amount, transaction ID, memo, phone |

**How a direct payment confirms itself.**

1. The customer picks the option and sees your account, the exact amount and a short **memo** (e.g. `K7Q2LX`).
2. They send the money, and may enter the transaction ID.
3. Each option has its own **SMS inbox URL** (`/hooks/direct/ibx_…`). Point an SMS-forwarder app on the phone that receives the alerts at it, or forward bank-alert emails or webhooks to it.
4. Conduit matches the alert to the payment by memo, transaction ID, amount and time window. A unique match succeeds by itself, usually within a minute. Anything uncertain waits in *Direct deposits* for one click.

For your code, nothing changes. The payment has `channel_kind: "direct"` and `next_action: "direct_transfer"`, with a `direct` object (section 5.4). You get the same `payment.succeeded` webhook and the same `GET /payments/{reference}` check. In `GET /public/site` and `GET /sites/{id}`, these channels show `"direct": true`.

> **Money flow.** Money paid to your own direct option never passes through the platform, so it is **not** part of your payroll balance. Platform-owned direct channels (created by the operator) are collected by the platform and are paid out in payroll as usual.

---

## 16. Location targeting (optional)

Payments are **cross-border by default**: every channel and bridge works for payers anywhere. You can target any of the following to particular places:

- a direct option (*Payment options › Display & where*);
- a channel on one website (*Websites › Channels › Locations*);
- a bridge (*Gateways › bridge › Control & lock*).

| Setting | Values |
|---|---|
| Mode | **Anywhere** (default) · **Only these places** · **Everywhere except these places** |
| Countries / regions / cities | ISO country codes (`GH`, `NG`, `CI`…), region names, city names |
| Unknown location | Allow (default) or deny payers whose location can't be determined |
| Use the phone's country | On by default. For mobile money, the payer's number (`+233…` → GH) beats their IP, so a Ghanaian abroad can still pay a GH wallet |

**Where the location comes from**, in order:

1. Your CDN's headers: Cloudflare `CF-IPCountry`, Vercel, CloudFront, Fastly, App Engine, or `X-Country-Code`.
2. A GeoIP2 City database, if the platform has configured one.
3. The phone number's country code.

**What happens at checkout.** Channels targeted elsewhere are hidden. A bridge targeted elsewhere is skipped by routing, and the next bridge that fits takes the payment. If a payer tries a hidden channel anyway (for example by typing a foreign number into a GH-only wallet), the call fails with `403 channel_not_available_here`. The message is safe to show the customer.

Every payment records `country` and `region`, so you can filter and report by them. `GET /sites/{id}` lists each channel's `locations` label (e.g. `"Only Ghana"`).

> Server-side lists (the console, `GET /sites/{id}`) always show every channel. Filtering only happens for a real payer at checkout.

---

## 17. Embedding your dashboard

Put the Conduit dashboard **inside your own admin panel**: payments, analytics, customers, partners, direct deposits and more. Your staff never need a Conduit account. You decide who sees what, within the ceiling the platform operator allows.

**1. Set it up once** in *Developers → Embedded dashboard*:

- **Sites allowed to frame it:** your admin's origin, e.g. `https://admin.example.com`. Browsers refuse to show the dashboard anywhere else.
- **Roles:** e.g. *Finance*, *Support* or *Agent*. Each role has:
  - **pages:** any of Overview, Payments, Analytics, Customers, Partners, Payment links, Referral rules, Direct deposits, Payouts, Audit log;
  - **can act or read-only;**
  - **websites:** all, or some;
  - **data scope:** *everything*, *only payments this staff member worked on* (their id in `attribution.staff`), or *only payments this person referred* (their id as a partner).
- **Look:** title, theme (light / dark / match the visitor), sidebar or top-tabs layout, brand colour.

What a role can reach is always role ∩ platform ceiling ∩ your plan. Settings, API keys, team management and the super-admin area are never embeddable.

**2. On your server, mint a session** each time a staff member opens the page:

```bash
curl http://localhost:8000/api/v1/embed/dashboard_sessions \
  -H "Authorization: Bearer $CONDUIT_SECRET" -H "Content-Type: application/json" \
  -d '{ "user": { "id": "staff_42", "name": "Esi Owusu", "email": "esi@shop.example" },
        "role": "Support", "expires_in": 3600, "theme": "auto", "page": "payments" }'
```

```json
{ "object": "embed_session", "id": "es_…", "user": { "id": "staff_42", … }, "role": "er_…", "url": "http://localhost:8000/embed/emb_…/payments?theme=auto",
  "expires_at": "…", "pages": [ { "code": "page.payments", "label": "Payments" }, … ], "can_write": false }
```

Use a website or organisation secret key, or a restricted key with `embed:write`. The **`url` is a bearer credential**: render it only into the page of the staff member it was minted for, and never log it.

**3. In your admin 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 step 2
    refresh: () => fetch("/admin/conduit-session").then(r => r.json()).then(d => d.url),  // new URL when it expires
    theme: "auto",
    onNavigate: (path) => console.log("now on", path),
  });
</script>
```

The iframe resizes itself to its content. When a session expires, `refresh()` is called, and the iframe switches to the new URL without a reload of your page. A plain `<iframe src="…">` also works if you don't want the script.

**Manage sessions:**

- `GET /embed/dashboard_sessions?active=1` lists sessions.
- `POST /embed/dashboard_sessions/{id}/revoke` ends one session.
- `POST /embed/dashboard_sessions/revoke_user {"user":"staff_42"}` ends every session of one staff member. Call it when someone leaves.
- `GET /embed/roles` lists your roles.

Every action taken inside the embed is in your audit log as `embed:<user id>`.

**Security model:**

- The token lives in the URL path, not a cookie, so it works even where browsers block third-party cookies.
- Pages are served with `Content-Security-Policy: frame-ancestors <your origins>`, `Referrer-Policy: no-referrer` and `Cache-Control: no-store`.
- Sessions last 5 minutes to the platform maximum (12 hours by default).

---

## 18. SDKs

Thin official clients live in `sdks/`. Each has retries with backoff, automatic idempotency keys, auto-pagination and webhook verification. They're dependency-free, so copy them into your project.

```js
const Conduit = require("./conduit");            // sdks/node/conduit.js
const c = new Conduit(process.env.CONDUIT_SECRET);
const s = await c.post("/checkout/sessions", { amount: 50, external_id: "order_1" });
for await (const p of c.list("/payments", { status: "succeeded", timeframe: "7d" })) console.log(p.reference);
const event = Conduit.verifyWebhook(rawBody, req.headers["conduit-signature"], process.env.CONDUIT_WHSEC);
```

```python
from conduit import Conduit                      # sdks/python/conduit.py
c = Conduit(os.environ["CONDUIT_SECRET"])
s = c.post("/checkout/sessions", {"amount": 50, "external_id": "order_1"})
for p in c.list("/payments", status="succeeded", timeframe="7d"): print(p["reference"])
event = Conduit.verify_webhook(raw_body, headers["Conduit-Signature"], WHSEC)
```

```php
require 'Conduit.php';                           // sdks/php/Conduit.php
$c = new Conduit\Client(getenv('CONDUIT_SECRET'));
$s = $c->post('/checkout/sessions', ['amount' => 50, 'external_id' => 'order_1']);
foreach ($c->each('/payments', ['status' => 'succeeded']) as $p) echo $p['reference'];
$event = Conduit\Client::verifyWebhook($raw, $_SERVER['HTTP_CONDUIT_SIGNATURE'], getenv('CONDUIT_WHSEC'));
```

---

## 19. Endpoint index

<!-- ENDPOINT_INDEX -->
All endpoints are relative to `/api/v1`. **Scope** applies to restricted keys; website and organisation secret keys can call everything. Generated from the live registry.

### Account & keys

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/health` | Liveness & version | `none` |
| `GET` | `/openapi.json` | OpenAPI 3.1 spec (generated) | `none` |
| `GET` | `/postman.json` | Postman collection (generated) | `none` |
| `GET` | `/scopes` | All scopes and what they grant | `none` |
| `GET` | `/me` | Who am I — key, account, websites, scopes | `any key` |

### Checkout sessions

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/checkout/sessions` | Create a checkout session | `sessions:write` |
| `GET` | `/checkout/sessions` | List checkout sessions | `sessions:read` |
| `GET` | `/checkout/sessions/{id}` | Retrieve a session (by id or your external_id) | `sessions:read` |
| `POST` | `/checkout/sessions/{id}/expire` | Expire an unpaid session now | `sessions:write` |

### Payments

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/payments` | List & search payments | `payments:read` |
| `GET` | `/payments/{id}` | Retrieve a payment (id, reference or external_id) | `payments:read` |
| `POST` | `/payments/{id}` | Update a payment | `payments:write` |
| `POST` | `/payments/{id}/attribution` | Credit a settled payment after the fact | `commissions:write` |
| `POST` | `/payments/{id}/verify` | Re-check status with the processor now | `payments:write` |
| `GET` | `/payments/{id}/events` | Payment timeline (every status change, note and check) | `payments:read` |
| `POST` | `/payments/{id}/notes` | Add an internal note (staff collaboration) | `payments:write` |

### Refunds

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/payments/{id}/refunds` | Refund a payment (full or partial) | `refunds:write` |
| `POST` | `/refunds` | Create a refund | `refunds:write` |
| `GET` | `/refunds` | List refunds | `refunds:read` |
| `GET` | `/payments/{id}/refunds` | Refunds of a payment | `refunds:read` |
| `GET` | `/refunds/{id}` | Retrieve a refund | `refunds:read` |
| `POST` | `/refunds/{id}/confirm` | Confirm a manual refund was sent | `refunds:write` |
| `POST` | `/refunds/{id}/cancel` | Cancel a pending refund | `refunds:write` |

### Customers

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/customers` | Create (or upsert) a customer | `customers:write` |
| `GET` | `/customers` | List & search customers | `customers:read` |
| `GET` | `/customers/{id}` | Retrieve a customer (cus_… or your reference) | `customers:read` |
| `POST` | `/customers/{id}` | Update a customer | `customers:write` |
| `DELETE` | `/customers/{id}` | Delete a customer with no payments | `customers:write` |
| `POST` | `/customers/{id}/block` | Block a customer from paying | `customers:write` |
| `POST` | `/customers/{id}/unblock` | Unblock a customer | `customers:write` |
| `GET` | `/customers/{id}/payments` | A customer's payments | `payments:read` |

### Partners

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/partners` | Create (or upsert) a partner | `partners:write` |
| `GET` | `/partners` | List partners | `partners:read` |
| `GET` | `/partners/{id}` | Retrieve a partner with balance | `partners:read` |
| `POST` | `/partners/{id}` | Update a partner | `partners:write` |
| `GET` | `/partners/{id}/balance` | Pending / available / paid commission balance | `commissions:read` |
| `GET` | `/partners/{id}/downline` | Partner tree below this partner | `partners:read` |
| `GET` | `/partners/{id}/stats` | Referred volume, customers and earnings | `partners:read` |
| `POST` | `/partners/{id}/codes` | Issue a referral code for this partner | `referrals:write` |

### Commissions

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/partners/{id}/payouts` | Pay a partner's available commissions | `commissions:write` |
| `POST` | `/commission_rules` | Create a commission rule | `commissions:write` |
| `GET` | `/commission_rules` | List commission rules | `commissions:read` |
| `GET` | `/commission_rules/{id}` | Retrieve a rule | `commissions:read` |
| `POST` | `/commission_rules/{id}` | Update a rule (applies to future payments) | `commissions:write` |
| `DELETE` | `/commission_rules/{id}` | Delete a rule (ledger lines keep their history) | `commissions:write` |
| `POST` | `/commissions/simulate` | Dry-run: who would earn what | `commissions:read` |
| `GET` | `/commissions` | Commission ledger | `commissions:read` |
| `GET` | `/commissions/{id}` | Retrieve a commission line | `commissions:read` |
| `POST` | `/commissions` | Manual adjustment (bonus or deduction) | `commissions:write` |
| `POST` | `/commissions/{id}/approve` | Release a held (pending) line now | `commissions:write` |
| `POST` | `/commissions/{id}/void` | Void an unpaid line | `commissions:write` |
| `GET` | `/commission_payouts` | Partner payouts | `commissions:read` |
| `GET` | `/commission_payouts/{id}` | Retrieve a partner payout with its lines | `commissions:read` |

### Referral codes

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/referrals` | Create a referral code | `referrals:write` |
| `GET` | `/referrals` | List referral codes | `referrals:read` |
| `GET` | `/referrals/{code}` | Retrieve a referral code | `referrals:read` |
| `POST` | `/referrals/{code}` | Update a referral code | `referrals:write` |

### Payment links

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/links` | Create a payment link | `links:write` |
| `GET` | `/links` | List payment links | `links:read` |
| `GET` | `/links/{id}` | Retrieve a payment link | `links:read` |
| `POST` | `/links/{id}` | Update a payment link | `links:write` |
| `POST` | `/links/sign` | Build a signed, pre-filled link | `links:write` |

### Websites

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/site` | This key's website (site keys) | `sites:read` |
| `GET` | `/sites` | List websites | `sites:read` |
| `GET` | `/sites/{id}` | Retrieve a website | `sites:read` |
| `POST` | `/sites/{id}` | Pause / resume a website, tune limits | `sites:write` |

### Webhooks

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/webhook_endpoints` | Create a webhook endpoint | `webhooks:write` |
| `GET` | `/webhook_endpoints` | List webhook endpoints | `webhooks:read` |
| `GET` | `/webhook_endpoints/{id}` | Retrieve an endpoint | `webhooks:read` |
| `POST` | `/webhook_endpoints/{id}` | Update an endpoint | `webhooks:write` |
| `DELETE` | `/webhook_endpoints/{id}` | Delete an endpoint | `webhooks:write` |
| `POST` | `/webhook_endpoints/{id}/roll_secret` | Rotate the signing secret (returned once) | `webhooks:write` |
| `POST` | `/webhook_endpoints/{id}/test` | Send a sample event to this endpoint now | `webhooks:write` |
| `POST` | `/webhooks/test` | Ping every active endpoint | `webhooks:write` |
| `GET` | `/webhook_deliveries` | Delivery log | `webhooks:read` |
| `GET` | `/webhook_deliveries/{id}` | A delivery with payload and response | `webhooks:read` |
| `POST` | `/webhook_deliveries/{id}/retry` | Retry a delivery now | `webhooks:write` |

### Events

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/events` | Event log (catch up on missed webhooks) | `events:read` |
| `GET` | `/events/{id}` | Retrieve an event | `events:read` |
| `POST` | `/events/{id}/redeliver` | Re-send an event to your endpoints | `webhooks:write` |

### Balance & payouts

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/balance` | What the platform owes you (platform-collected payments) | `balance:read` |
| `GET` | `/payouts` | Payroll payouts to you | `balance:read` |
| `GET` | `/payouts/{id}` | A payout with its payments | `balance:read` |

### Reports & exports

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/reports/summary` | KPIs with period-over-period change | `reports:read` |
| `GET` | `/reports/timeseries` | Volume & counts per bucket | `reports:read` |
| `GET` | `/reports/breakdown` | Volume split by a dimension | `reports:read` |
| `GET` | `/reports/funnel` | Checkout conversion funnel | `reports:read` |
| `GET` | `/reports/partners` | Partner leaderboard (volume referred & commission) | `reports:read` |
| `GET` | `/reports/customers` | New vs returning customers and top payers | `reports:read` |
| `GET` | `/exports/{resource}` | CSV export (payments, refunds, customers, commissions) | `any key` |

### Embedded dashboard

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/embed/dashboard_sessions` | Mint a dashboard session for one of your staff | `embed:write` |
| `GET` | `/embed/dashboard_sessions` | List dashboard sessions | `embed:read` |
| `POST` | `/embed/dashboard_sessions/{id}/revoke` | End a session now (e.g. the staff member left) | `embed:write` |
| `POST` | `/embed/dashboard_sessions/revoke_user` | End every session of one staff member | `embed:write` |
| `GET` | `/embed/roles` | Embed roles you defined | `embed:read` |

### Test helpers

| Method | Path | What it does | Scope |
|---|---|---|---|
| `POST` | `/test/payments` | Simulate a full payment (test mode) *(test keys only)* | `payments:write` |
| `POST` | `/test/events` | Fire a sample event to your test endpoints *(test keys only)* | `webhooks:write` |

### Browser (publishable key)

| Method | Path | What it does | Scope |
|---|---|---|---|
| `GET` | `/public/site` | Website config for your UI | `publishable key` |
| `POST` | `/public/sessions` | Create a hosted session from the browser | `publishable key` |
| `POST` | `/embed/sessions` | Open the in-page modal (used by conduit.js) | `publishable key` |
| `GET` | `/public/payments/{reference}` | Minimal payment status for the browser | `publishable key` |

<!-- /ENDPOINT_INDEX -->