# ChiiPay API reference

ChiiPay lets Nigerian businesses collect naira (NGN) payments through Paystack. Your server creates a checkout session with your secret API key, sends the customer to the hosted Paystack checkout, then confirms the result with a signed webhook and/or the Transactions API.

## Base URL

```
https://uboxdnmmernzlyfyalxm.supabase.co/functions/v1
```

All requests and responses are JSON. Amounts are whole naira (₦), not kobo.

## Authentication

Create an API key in the ChiiPay dashboard under **Developers → API Keys**. The full key is shown once. Send it from your server only — never from a browser or mobile app.

```
Authorization: Bearer chii_live_xxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

Key format: `chii_live_` or `chii_test_`, an 8-character key id, an underscore, then the secret. Note: `chii_test_` keys currently process real payments (there is no sandbox yet).

## Create a checkout session

`POST /v1-checkout-sessions`

Request body:

| Field | Type | Required | Notes |
|---|---|---|---|
| amount_ngn | integer | yes | 100 to 10,000,000 |
| customer_email | string | yes | valid email |
| metadata | object | no | up to 20 keys; keys use letters, digits and underscore (max 40 chars); values string (max 200 chars), number or boolean; returned on the transaction and in the webhook |
| success_url | string | no | where the customer returns after paying (`callback_url` is accepted as an alias); defaults to ChiiPay's payment status page |
| idempotency_key | string | no | 8–80 characters; or send the `Idempotency-Key` header |

Example:

```bash
curl -X POST https://uboxdnmmernzlyfyalxm.supabase.co/functions/v1/v1-checkout-sessions \
  -H "Authorization: Bearer $CHIIPAY_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order_12345" \
  -d '{"amount_ngn": 5000, "customer_email": "buyer@example.com", "metadata": {"order_id": "12345"}, "success_url": "https://yourshop.com/order/12345"}'
```

Response `200`:

```json
{
  "reference": "CHIIPAY-MH1ABC2D-9F3E21",
  "access_code": "xxxxxxxx",
  "authorization_url": "https://checkout.paystack.com/xxxxxxxx",
  "amount_ngn": 5000,
  "status": "pending",
  "fee_bps": 75,
  "estimated_platform_fee_ngn": 37,
  "estimated_paystack_fee_ngn": 175,
  "estimated_net_ngn": 4963,
  "estimated_settlement_ngn": 4788,
  "settlement": "paystack_direct"
}
```

`estimated_paystack_fee_ngn` uses Paystack's local NGN rule (1.5% + ₦100, ₦100 waived under ₦2,500, capped at ₦2,000); `estimated_net_ngn` is the amount after ChiiPay's fee, and `estimated_settlement_ngn` is that amount minus the estimated Paystack fee. With `settlement: "paystack_direct"`, Paystack pays the merchant's share straight to the merchant's verified bank account on its normal settlement cycle (next business day) — ChiiPay does not hold the money.

Redirect the customer to `authorization_url`. Store `reference` against your order.

Idempotency: repeating the same request with the same idempotency key within 10 minutes returns the same pending session with `"reused": true` instead of creating a new one.

## Retrieve a transaction

`GET /v1-transactions?reference=CHIIPAY-...`

```json
{
  "transaction": {
    "reference": "CHIIPAY-MH1ABC2D-9F3E21",
    "amount_ngn": 5000,
    "gross_amount_ngn": 5000,
    "platform_fee_ngn": 37,
    "net_amount_ngn": 4963,
    "fee_bps_applied": 75,
    "status": "paid",
    "customer_email": "buyer@example.com",
    "paid_at": "2026-10-28T12:34:56Z",
    "created_at": "2026-10-28T12:30:00Z",
    "metadata": { "order_id": "12345" },
    "paystack_fee_ngn": 175,
    "settled_to_bank_ngn": 4788,
    "settlement": "paystack_direct"
  }
}
```

`paystack_fee_ngn` is the processing fee Paystack charged (null if Paystack did not report it); `settlement` is `paystack_direct` (paid straight to the merchant's bank by Paystack) or `chiipay_balance` (older payments credited to the ChiiPay balance).

`net_amount_ngn` is the amount after ChiiPay's fee.
`settled_to_bank_ngn` is what Paystack pays to the merchant's bank (after Paystack's fee), null if not reported or when settlement is `chiipay_balance`.

If Paystack does not apply the split for a payment, it is recorded with settlement: chiipay_balance and ChiiPay finance refunds that payment to the customer; ChiiPay does not pay out balances. Paystack pays each business directly into its own bank account.

Statuses: `pending` (not paid yet), `paid` (confirmed by Paystack — fulfil only on this), `failed`, `expired` (abandoned).

List recent transactions: `GET /v1-transactions?limit=20` (1–100, default 20) returns `{ "transactions": [...] }`, newest first, without `metadata`.

## Webhooks

Set your HTTPS webhook URL and generate a signing secret under **Developers → Webhooks**. ChiiPay sends a `POST` with a JSON body:

```json
{
  "event": "payment.success",
  "merchant_code": "M-XXXXXXXX",
  "merchant_id": "6f1c2d3e-...",
  "timestamp": "2026-10-28T12:34:56Z",
  "data": {
    "reference": "CHIIPAY-MH1ABC2D-9F3E21",
    "amount_ngn": 5000,
    "gross_amount_ngn": 5000,
    "platform_fee_ngn": 37,
    "net_amount_ngn": 4963,
    "fee_bps_applied": 75,
    "customer_email": "buyer@example.com",
    "paid_at": "2026-10-28T12:34:56Z",
    "status": "paid",
    "paystack_fee_ngn": 175,
    "settled_to_bank_ngn": 4788,
    "settlement": "paystack_direct",
    "metadata": { "order_id": "12345" }
  }
}
```

Events: `payment.success`, `refund.pending`, `refund.processed`, `refund.failed`, `dispute.created`, `dispute.reminder`, `dispute.won`, `dispute.lost`, `payout.paid`, `payout.failed`, `payout.reversed`.

### Verify the signature

Headers: `X-ChiiPay-Timestamp` (Unix seconds) and `X-ChiiPay-Signature` (`sha256=<hex>`). The signature is HMAC-SHA256 of `<timestamp>.<raw request body>` using your signing secret. Compare in constant time and reject timestamps older than 5 minutes.

```js
import crypto from "node:crypto";
function verifyChiiPay(rawBody, timestamp, signatureHeader, secret) {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
  const a = Buffer.from(expected), b = Buffer.from(signatureHeader || "");
  const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
  return fresh && a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

Delivery: ChiiPay makes one delivery attempt per event (no automatic retries yet). Always confirm with `GET /v1-transactions?reference=...` before fulfilling, and run the same check when the customer returns to your `success_url`.

## Errors

Errors use `{ "error": { "code": "...", "message": "..." } }`. Branch on `code`.

| HTTP | code | Meaning |
|---|---|---|
| 400 | invalid_body | Body failed validation; the message names the field |
| 400 | invalid_idempotency_key | Idempotency key must be 8–80 characters |
| 401 | missing_auth | No `Authorization: Bearer` key |
| 401 | invalid_key_format | Not a ChiiPay key |
| 401 | invalid_key | Unknown key or wrong secret |
| 401 | key_revoked | Key was revoked |
| 401 | key_expired | Key has expired |
| 403 | insufficient_scope | Key lacks the scope for this endpoint |
| 403 | merchant_inactive | The merchant cannot accept payments |
| 404 | not_found | No such transaction for this merchant |
| 405 | method_not_allowed | Wrong HTTP method |
| 409 | payouts_not_configured | The merchant's payout account is not set up or is still under review |
| 429 | rate_limited | Too many requests |
| 500 | internal_error / db_error / config_error | Server problem — retry with backoff |
| 502 | provider_error | Paystack returned an error — retry with backoff |
| 503 | rate_limit_unavailable | Retry shortly |

## Rate limits

60 requests per minute per API key. On `429`, wait and retry with exponential backoff; reuse the same idempotency key so retries never create duplicate sessions.

## Integration checklist

1. Store the secret key in your server's environment (never in client code).
2. Create a checkout session per order with an idempotency key such as `order_<id>`.
3. Redirect the customer to `authorization_url`.
4. On the webhook or the customer's return, call `GET /v1-transactions?reference=...` and fulfil only when `status` is `paid` and `gross_amount_ngn` equals the order total.
5. Make fulfilment idempotent so a repeated webhook or return visit never ships an order twice.
