# CediLink API

Accept mobile money, card and bank payments in Ghana through one integration.

Base URL: `https://cedilinkweb-production.up.railway.app/v1`

Live checkout: `https://cedilink.vercel.app/checkout/{id}?cs={clientSecret}`

---

## Your credentials

You have three. They do different jobs and only one of them is dangerous.

| Credential | Looks like | Where it goes |
|---|---|---|
| Merchant ID | `mch_7QWv2Kx9Lp` | Identifies you. Safe in logs, URLs, support tickets. |
| Publishable key | `pk_live_...` | Browser and mobile app. Can read a payment intent, cannot create a charge. |
| Secret key | `sk_live_...` | **Your server only.** Full account access. |

The secret key is displayed once, when you create it. We store a hash, so we cannot show it to you again and cannot email it to you — if you lose it, rotate it from the dashboard.

Anyone holding your secret key can charge customers and read every transaction you have ever taken. Put it in your secrets manager, not in your repo, not in a `.env` you commit, not in a screenshot in a support thread.

### Test mode first

You can create test keys the moment you finish signing up, before your business verification
clears — Dashboard → Developers → New test key. Everything behaves identically except no money
moves and no prompts reach real handsets.

```
sk_test_...  →  test mode — the mock rail, fake money
sk_live_...  →  real customers, real GHS
```

A test key cannot read or write live data. This is enforced at the database level, not by convention, so there is no configuration mistake that can cross the boundary.

---

## Authentication

```bash
curl https://cedilinkweb-production.up.railway.app/v1/payment_intents \
  -H "Authorization: Bearer sk_live_..." \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json"
```

Every mutating request needs an `Idempotency-Key`. Send the same key with the same body and you get the stored response back rather than a second charge. Same key with a *different* body returns `409` — that combination almost always means a bug in your retry logic, and we would rather tell you than guess which body you meant.

---

## Collecting a payment

### 1. Create an intent

```http
POST /v1/payment_intents
```

```json
{
  "amount": 5000,
  "currency": "GHS",
  "reference": "order-4471",
  "customer": { "phone": "0244123456", "email": "ama@example.com" },
  "method": "mobile_money",
  "network": "MTN",
  "return_url": "https://yourshop.com/orders/4471",
  "metadata": { "order_id": "4471" }
}
```

**Amounts are integers in pesewas.** GHS 50.00 is `5000`. We do not accept decimals anywhere in the API, because floating-point money is how ledgers drift. If you send `50.00` you will get a `400`.

`reference` must be unique within your account. It is your handle on the payment — put your own order ID in it.

**Response**

```json
{
  "id": "pi_01HXYZ",
  "status": "created",
  "amount": 5100,
  "merchant_amount": 5000,
  "fee_charged_to_customer": 100,
  "next_action": null,
  "client_secret": "cs_...",
  "checkout_url": "https://cedilink.vercel.app/checkout/pi_01HXYZ?cs=cs_..."
}
```

The payment is only *created* — the gateway has not been called yet, so there is no
`next_action`. `amount` is the total the customer will pay (your `5000` plus the 3%
customer fee); `merchant_amount` is what settles to you. Send the customer to
`checkout_url` — the `?cs=` client secret is part of the URL.

### 2. Get the customer to act

Direct MoMo push, by default. The checkout page auto-verifies the number the intent was
created with as soon as it loads and lands straight on the consent screen — the registered
account name, the amount and the total, with your business name on it. One Confirm tap
sends the prompt to the customer's handset; they approve it with their MoMo PIN and the
intent is `processing` while the prompt is out. Nothing is prompted before the customer
confirms, and there is no hosted redirect anywhere on this rail — MTN, Telecel and
AirtelTigo all pay by direct prompt. An intent created without a customer phone falls back
to the manual form on the checkout page instead. Do not create another payment while one
is processing: if a prompt is already on the phone, a second submit answers `409` —
poll instead, never a second charge. If the checkout has expired the answer is `410` and
the customer needs a fresh payment link. Poll the intent no faster than every 5 seconds;
only a verified `succeeded` status authorizes fulfilment. After a recorded failure the
checkout returns the customer to `return_url` after 3 seconds and offers a Return now
link; after a recorded success it stays on the receipt with a Start new payment button —
pending or processing payments never redirect, and the return itself is not proof of
payment. Refreshing after a success starts a fresh payment session.

If you drive your own UI instead of the checkout page, the three calls are
`POST /v1/checkout/{id}/yebeck` (account check), `POST /v1/checkout/{id}/momo`
(send the prompt), and `GET /v1/checkout/{id}` (status) — see [Direct checkout](#direct-checkout)
below. Both POSTs accept an empty body and fall back to the number the intent was
created with.

### How fast it settles

A payment approved on the handset credits the merchant in about 5–7 seconds with the
checkout page open, and within 15–20 seconds with it closed. `GET /v1/checkout/{id}`
re-queries the gateway itself when the charge is still open (throttled to once per 10
seconds per charge), and the worker sweeps open charges every 15 seconds with a
5-minute reconciliation backstop — so the status you poll is provider truth, not a
stale read. A charge is never flipped to paid without the gateway confirming it, and
never credited twice.

If you drive your own UI instead of the checkout page, branch on `next_action.type`:

| `type` | What to do |
|---|---|
| `await_prompt` | Show "check your phone and approve". Display `ussd_fallback` if present — a meaningful share of prompts never arrive, and the USSD string rescues those payments. |
| `redirect` | Send the browser to `next_action.url`. |
| `submit_otp` | Collect the OTP and `POST /v1/payment_intents/{id}/validate` with `{ otp }`. A wrong code answers `402 otp_invalid`. |
| `submit_pin` | Collect the PIN and POST it to the same `/validate` endpoint. |
| `virtual_account` | NGN bank transfer only. Show `accountNumber`, `bankName` and `accountName`, with a countdown to `expiresAt`. |
| `none` | Nothing to do; wait for the webhook. |

Or skip all of that and redirect to `checkout_url`, which handles every branch for you.

## Direct checkout

The checkout page's own calls, for merchants driving their own UI. All three are
authenticated by the intent's client secret (`?cs=`), not by an API key, so they are
safe to call from a browser. The client secret is part of `checkout_url`.

### Get the checkout intent

```http
GET /v1/checkout/{id}?cs={client_secret}
```

Everything the page needs: `amount_minor`, `merchant_name`, `method`, `network`, the
masked `customer_hint`, `next_action`, `expires_at`, and the receipt in GH₵ amounts
only — `merchant_amount` (the requested figure), `fee_charged_to_customer`, and the
grossed total. When the charge is still open this read also re-queries the gateway
(see [How fast it settles](#how-fast-it-settles)).

### Check the account name

```http
POST /v1/checkout/{id}/yebeck?cs={client_secret}
```

```json
{ "phone": "0244123456", "network": "MTN" }
```

Looks the number up and returns the registered account name (`201`), binding the
phone, network and name to the intent server-side. The lookup never refuses: a
lookup that finds no account, answers without a name, or cannot run (gateway down,
no adapter) returns `201` with `account_name: null` — the prompt itself is the
final check. A repeat call returns the stored binding (`200`), never a second
lookup. The body may be empty (`{}` or no body at all): the call then falls back to
the phone and network the intent was created with, and refuses `400 phone_required`
only when the intent has no stored phone. `503 yebeck_unavailable` when Yebeck is
not the active gateway; `410 checkout_expired` when the checkout has expired.

### Send the MoMo prompt

```http
POST /v1/checkout/{id}/momo?cs={client_secret}
```

```json
{ "phone": "0244123456", "network": "MTN" }
```

Sends the prompt to the customer's handset. `201` means `processing` / `await_prompt`
— the prompt is out. Like `/yebeck`, the body may be empty and the call then uses the
number bound by the account check. `409 already_submitted` when a prompt is already
waiting — poll instead, never a second prompt. `410 checkout_expired` when the
checkout has expired. Nothing is charged and no prompt is sent by the account check
above — only this call sends the prompt, and only after the customer confirmed on
the consent screen.

### Validate an OTP at checkout

```http
POST /v1/checkout/{id}/validate?cs={client_secret}
```

```json
{ "otp": "123456" }
```

For the rails that ask for one. A wrong code answers `402 otp_invalid`. The
merchant-API equivalent is `POST /v1/payment_intents/{id}/validate` with your
secret key.

### 3. Wait for the webhook

**The browser coming back to your `return_url` is not proof of payment.** It means the customer's browser finished a redirect. It does not mean money moved, and anyone who reads your JavaScript can hit that URL directly. Ship goods on the webhook, never on the redirect.

---

## Version

```http
GET /version
```

Public, no key. Answers the build the live API is running, so a deploy can be
verified without an API key:

```json
{ "status": "ok", "commit": "1ca77d8..." }
```

## Webhooks

Register an HTTPS endpoint in the dashboard. You get a signing secret (`whsec_...`), shown once.

```http
POST https://yourshop.com/hooks/cedilink
X-CediLink-Signature: t=1754049600,v1=5f3c9a...
X-CediLink-Event-Type: payment_intent.succeeded
X-CediLink-Delivery-Id: dlv_01HXYZ
```

```json
{
  "id": "evt_01HXYZ",
  "type": "payment_intent.succeeded",
  "sequence": 3,
  "data": {
    "intent_id": "pi_01HXYZ",
    "amount": 5000,
    "currency": "GHS",
    "reference": "order-4471",
    "status": "succeeded"
  }
}
```

`data.amount` is the amount you asked for — the figure to settle against. When the customer
was charged more than that (the 3% customer fee), the event also carries `amount_charged` and
`customer_fee` with the grossed total and the fee. Only two events are emitted:
`payment_intent.succeeded` and `payment_intent.failed`.

### Verify before you trust

```js
import crypto from 'node:crypto';

function verify(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
  const age = Math.abs(Math.floor(Date.now() / 1000) - Number(parts.t));
  if (age > 300) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${parts.t}.${rawBody}`)
    .digest('hex');

  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}
```

Three things that are easy to get wrong here:

**Use the raw body.** Compute the HMAC on the bytes you received, before your JSON middleware parses and re-serialises them. Re-serialising changes key order and whitespace, and the signature will never match.

**Reject old timestamps.** The five-minute window is what stops someone replaying a captured `succeeded` event.

**Compare in constant time.** `===` on a signature leaks it a byte at a time.

### Be idempotent

Delivery is at-least-once. You *will* receive the same event twice — on our retry, on a network blip, on your own 500. Key on `event.id` and no-op if you have seen it.

Ordering is not guaranteed either. Each event carries a `sequence` that increases per intent; if you receive a lower sequence than you have already processed, discard it.

### Retries

Any non-2xx, or anything slower than 10 seconds, counts as a failure. We retry at 10s, 1m, 5m, 30m, 2h, 6h, 12h, 24h, then dead-letter it.

Return `200` fast and do your processing afterwards. A webhook handler that writes to three tables and calls two APIs before responding will time out under load and put you in the retry queue for work you already did.

---

## Statuses

```
created → requires_action → processing → succeeded
                                       ↘ failed
                                       ↘ unknown → succeeded / failed
```

On the Yebeck rail (Ghana) create returns `created` and the intent only moves to
`requires_action` once the customer verifies their number on the checkout page. On the Flutterwave rail
(Nigeria) create returns `requires_action` directly, with the `next_action` to branch on.

`unknown` is the one to handle properly. It means we asked a gateway to move money and did not get a clear answer — usually a timeout. The money may or may not have left the customer's wallet.

We never guess and we never re-charge. The intent stays `unknown` while we poll the gateway on a backoff schedule until it resolves, which is normally seconds and occasionally hours.

**Do not treat `unknown` as failure.** Do not ask the customer to pay again. Show them "we're confirming your payment" and wait for the webhook. If you re-charge on `unknown` you will double-debit real people.

---

## Gateways

There is one active gateway at a time. For Ghana it is **Yebeck** — direct mobile money
prompt on MTN, Telecel and AirtelTigo, plus account-name lookup and automatic payouts.
There is no hosted checkout and no card on this rail. For Nigeria it is **Flutterwave** (v3 by default,
v4 when configured) — bank transfer, USSD and card. Other adapters (Nalo, expressPay,
RushPay, Moolre, BluPay, MojoPay) exist in the code but are dormant: they only register
when their credentials are configured, and they are not the live rail.

You do not choose a gateway per charge, and there is no failover between gateways: if the
active gateway is down, the charge fails with `provider_unavailable` rather than silently
moving to another rail. You cannot pin a gateway or connect your own gateway account —
gateway credentials are set by the platform admin, not by merchants.

The gateway never appears in anything the customer sees: the checkout page and the prompt
show your business name, never the gateway's.

---

## Fees

Three numbers, all settled and code-matched:

- **3% on top of each payment, paid by the customer.** You ask for GH₵100; the customer
  is prompted GH₵103. The create response shows both: `amount` is the grossed total,
  `merchant_amount` is what you asked for.
- **1% deducted when a payment settles.** GH₵100 requested → GH₵99 credited to your balance.
- **5% commission on withdrawals only**, taken when you move money into your payout account,
  never at the send.

The 3% is background: every total you see — dashboard, payments list, settlements, the
admin "Made today" figure — is the amount you asked for, never the grossed total. The
customer pays +3%; you are credited the requested amount, then the 1% comes off that.

There is no reserve withholding.

Worked example, GH₵1,000 requested: the customer pays GH₵1,030 → GH₵990 credited at
settlement → GH₵49.50 commission on the payout move → GH₵940.50 reaches your account.

That is the manual move. An automatic withdrawal takes 5% commission **plus** a 2%
platform fee in one stored total (GH₵1,000 → GH₵50.00 + GH₵20.00 → GH₵930.00).
The automatic figure does not appear in the dashboard's "5% commission earned" hero —
that figure is the sum of manual-move commission only, so the 2% platform fee is never
mixed into a "5%" number.

---

## Withdrawals

Withdrawals are automatic. Move money from your balance into your payout account, then send
it from there:

1. `POST /v1/me/payout-account/move` — moves an amount into the payout account. The 5%
   commission is taken here (an admin override can change the rate; the default is 5%).
2. `POST /v1/me/payout-account/disburse` — creates a disbursement from the payout account
   with `amount_minor`, `account`, `account_name` and `network`. `account_name` is
   optional on the Yebeck rail — the lookup below supplies the verified name, and a
   typed name is replaced by it; on rails that do not verify, the typed name is
   required.

A disbursement is created on the `yebeck` provider, and the account name is looked
up first — ADVISORY-ONLY (owner order, 2026-11-27): a lookup that finds no
account, answers without a name, or cannot run never refuses the payout; the
verified name replaces the typed one when it comes back, and the
disbursement itself is the final check. No approval lock (owner order,
2026-11-27 — the ≥ GH₵1,000 approval tier is REMOVED): a disbursement is
created `approved` and sent **instantly at any amount** — it fires through
Yebeck as soon as it is requested, no admin involved. Payouts parked as
`pending` by the old lock are re-driven by the worker sweep.

A legacy `pending` withdrawal still shows as `pending` everywhere —
dashboard, admin queue, and `GET /v1/me/payouts` — never "awaiting approval".
Check status with `GET /v1/me/payouts`.

`POST /v1/me/payouts` is retired and answers `410 withdrawals_replaced` — use the
payout-account endpoints above.

### Admin direct withdrawal

Admin-only — no API key. An admin withdraws straight from the gateway
float (the Yebeck available balance — the same source the auto-sweep
disburses from) to a MoMo number, on demand, with an admin session
(`cedilink_admin` cookie). No merchant is involved.

```http
POST /v1/admin/withdraw
Idempotency-Key: 9f2c1a77-...
Content-Type: application/json

{
  "amount_minor": 500000,
  "account": "0248774213",
  "network": "MTN",
  "account_name": "Danny",
  "narration": "owner draw"
}
```

`account_name` and `narration` are optional. The account name is
looked up first — ADVISORY-ONLY (owner order, 2026-11-27): a lookup
that finds no account, answers without a name, or cannot run never
refuses the withdrawal; the verified name replaces the typed one
when it comes back, and the disbursement itself is the final check.

**Charges — none on this path.** No commission is taken on an
admin withdrawal (owner order, 2026-11-28): the 5% is the
MERCHANT withdrawal commission, and an admin withdrawing from
the gateway float is the platform owner taking their own money,
so commission is always 0 — whatever any per-merchant override
says, this path never reads one. No 2% platform fee rides here
either — that is legacy auto-withdrawal pricing only. The
provider send fee is 0 on the Yebeck rail (Yebeck's own fee is
reported at settlement and stamped on the row, never
pre-deducted). The **actual amount withdrawn** is
net = gross − commission − send fee, which here is just the
gross: GH₵5,000 → GH₵0 commission → **GH₵5,000.00 sent**.

A successful withdraw returns `201` with `{ id, status, currency,
amount_minor, commission_minor: 0, commission_percent: 0,
provider_fee_minor, provider: "yebeck", net_minor, destination:
{ account, name, network }, provider_ref, message }` — `net_minor`
is what lands with the recipient. The payout goes through the same
dispatcher as every merchant payout (atomic claim,
re-query-before-resend, amount guard, two-strike rule). One
withdrawal is at most **GH₵10,000** (`400 amount_too_large`); if
the Yebeck float cannot cover the net, the request is refused
with `400 insufficient_float` and nothing is sent. Send
`Idempotency-Key`: a retry with the same key returns the original
payout (same `id`, live status) and never pays twice. Finance and
owner roles can withdraw; support and reviewer cannot (`403
forbidden`). Needs database migration 041 — before it runs, the
endpoint answers `409 migration_required`.

#### Gateway float balance

Admin-only — no API key. A live read of the Yebeck available
balance — the same float, read the same way, as the withdrawal
float check. No caching: every call reads Yebeck fresh, so the
number the admin sees is the number a withdrawal is judged
against. The Withdraw tab shows it beside the form.

```http
GET /v1/admin/balance
```

`200` returns `{ provider: "yebeck", currency: "GHS",
available_minor: 1495635 }`. If Yebeck cannot be reached the
endpoint answers `503 balance_unavailable` — never a stale or
made-up number. Finance and owner roles can read it; support
and reviewer cannot (`403 forbidden`).

## Refunds

Public — no API key. A refund is matched to a succeeded charge by its provider
reference and the number it was paid with, so it is capability-authenticated: only
someone who knows both can ask for one.

```http
POST /v1/refunds/request
```

```json
{
  "provider_ref": "MVN-261126-CF3D0D56",
  "phone": "0244123456",
  "reason": "Customer requested a refund"
}
```

`201` returns `{ data: { id: "rfd_...", status: "pending" } }`; a second request for
the same payment returns `200` with `already_requested: true`; no matching succeeded
charge returns `404 refund_not_matched`; a bad body returns `400 invalid_input`.
The refund amount is the charge amount minus the PIN fee. An admin approves it
before any money moves.

```http
GET /v1/refunds/status/{id}
```

`200` returns `{ data: { id, status, amount_minor, created_at } }`; unknown id
returns `404`.

---

## Errors

```json
{
  "error": {
    "code": "insufficient_funds",
    "message": "The customer's mobile money wallet does not have enough balance.",
    "retryable_by_customer": true
  }
}
```

| Code | Meaning | What to tell the customer |
|---|---|---|
| `insufficient_funds` | Wallet empty | Top up and try again |
| `customer_declined` | They rejected the prompt | Retry if it was a mistake |
| `customer_timeout` | No response to the prompt | Resend |
| `invalid_number` | Not a valid or registered MSISDN | Check the number |
| `wrong_network` | Number isn't on that MNO | Pick the right network |
| `limit_exceeded` | MNO wallet or transaction cap | Try a smaller amount |
| `provider_unavailable` | Gateway or MNO down | Try again shortly |
| `validation_rejected` | The gateway rejected the request as invalid | Check the number and amount, then retry |
| `payment_failed` | The gateway failed without a more specific reason | Try again shortly |
| `otp_invalid` | Wrong OTP code | Re-enter the code |

A `500 internal_error` carries a `request_id` — quote it to support and it matches
the same id on the server log line. Retry a `500` with backoff; do not retry a `4xx`
other than the two `429`s below.

---

## Rate limits

There is no per-key rate limit. A `429` from this API is always the phone guard, not a
request-count limit: `number_blocked` (a number blockaded after 5 failed payment
initiations in a row — 1 hour the first time, 24 hours after that) or
`payment_in_progress` (a payment for that number is already in flight). Wait it out
rather than retrying.

---

## Going live

- [ ] Business verification approved
- [ ] Settlement account added
- [ ] Webhook endpoint registered and signature verification tested against a real delivery
- [ ] Handler is idempotent on `event.id`
- [ ] `unknown` handled as pending, never as failure
- [ ] Fulfilment triggers on the webhook, not the browser redirect
- [ ] Secret key in a secrets manager, not in the repo
- [ ] Swapped `sk_test_` for `sk_live_` in production config only
