# Swichi Payments Swichi Payments is Swichi's payments API: ask a customer's phone to pay (a USSD push), pay out to mobile money and banks, move money to another Swichi business, and make hosted checkout links. Customers see Swichi; the API never names a mobile money provider. Every request goes to `https://gateway.swichi.cc/v1` with `Authorization: Bearer $SWICHI_KEY`. Amounts are whole Tanzanian shillings (`"currency": "TZS"`). ## Your first payment Open **Swichi Gateway → Developers → API keys** in your [Swichi dashboard](https://dashboard.swichi.cc/admin/gateway/developers). Your sandbox is already there, with test money: press **Get my sandbox key** ([API keys](/api-keys)). Set it in your shell: ```bash export SWICHI_KEY=YOUR_SANDBOX_KEY # a sandbox key: test money only ``` **1. See your test money.** ```bash file=examples/pay-balance.sh # Your sandbox wallet: it starts with test money. curl https://gateway.swichi.cc/v1/balance \ -H "Authorization: Bearer $SWICHI_KEY" ``` **2. Ask a phone to pay.** Every request that moves money needs an `Idempotency-Key`: send the same key again when you retry, and the money moves once. The answer comes at once with `status: "pending"`. ```bash file=examples/pay-collect.sh # Ask a phone to pay: a USSD push. Numbers ending in 005 wait for you to decide. save: COLLECTION_ID=id curl https://gateway.swichi.cc/v1/collections \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042" \ -d '{"amount": 25000, "currency": "TZS", "phone": "0754 000 005", "reference": "order-1042", "description": "Two kitenge dresses"}' ``` **3. The payer approves.** In the sandbox you decide what the payer does. With a real phone, this is the customer entering their PIN. ```bash file=examples/pay-simulate.sh # Sandbox only: the payer approves on their phone. curl https://gateway.swichi.cc/v1/sandbox/collections/$COLLECTION_ID/simulate \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -d '{"outcome": "succeeded"}' ``` **4. Read it back.** A collection is `succeeded` only once Swichi has confirmed the money with the network. It shows the fee, what reached your wallet (`net`) and the signed Swichi receipt. ```bash file=examples/pay-get-collection.sh # The collection is succeeded, with its fee, what reached you and its receipt. curl https://gateway.swichi.cc/v1/collections/$COLLECTION_ID \ -H "Authorization: Bearer $SWICHI_KEY" ``` In production you don't poll: add a [webhook](/webhooks) and Swichi tells your server when a payment succeeds or fails. Then [go live](/go-live). ## In this section - [API keys](/api-keys): sandbox and live keys, scopes and IP allow lists. - [Collections](/collections): ask a phone to pay, in your code. - [Payouts: mobile money](/payouts-mobile-money) and [Payouts: bank](/payouts-bank). - [Transfers](/transfers) to another Swichi business, and [Checkout links](/checkout-links). - [Webhooks](/webhooks), [Sandbox](/sandbox), [Go live](/go-live) and [Errors](/errors). - Every operation is in the [API reference](/api-reference). Retries are safe with an `Idempotency-Key` ([Idempotency](/idempotency)). # Secure integration guide This page is the path every Swichi Payments integration should follow, from the first key to live money. Each step says what to do and what never to do. The other pages go deeper; this one keeps the order and the safety rules in one place. ## The flow at a glance 1. Sign up and read the docs. 2. Get a sandbox key, scoped to what you need. 3. Build: collect money with an idempotency key, the amount decided by your server. 4. Add a webhook endpoint and keep its signing secret safe. 5. Verify every webhook before acting on it. 6. Test every outcome in the sandbox. 7. Go live: finish verification, then swap in live credentials. 8. Run it: watch, rotate and revoke. ## 1. Sign up and read the docs Make a [Swichi account](https://dashboard.swichi.cc). Your sandbox is there from the start, with test money. Read, in this order: [Sandbox](/sandbox), [Collections](/collections), [Webhooks](/webhooks), [Go live](/go-live). The API is plain HTTPS and JSON at `https://gateway.swichi.cc/v1`. There is nothing to install. ## 2. Get a sandbox key On **Swichi Gateway → Developers → API keys**, with **Test mode** on, press **Get my sandbox key**. **Do** - Give the key only the scopes it needs (`collections`, `payouts`, `transfers`, `read`). A shop that only takes payments needs `collections` and `read`, not `payouts`. - Add an IP allow list with your servers' addresses. - Keep the key in an environment variable or your secret manager, and send it as `Authorization: Bearer `. **Never** - Put a key in a mobile app, a browser, JavaScript sent to customers, or a public repository. Calls to Swichi come from your server only. - Share one key between unrelated systems. Make one per system, so you can revoke one without stopping the others. See [API keys](/api-keys). ## 3. Collect money safely ```bash curl https://gateway.swichi.cc/v1/collections \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042" \ -d '{"amount": 25000, "currency": "TZS", "phone": "0754 000 001", "reference": "order-1042"}' ``` **Do** - Send an `Idempotency-Key` on every POST, made from your own record (`order-1042`). If the network fails, retry with the **same** key: Swichi returns the first result instead of charging twice. The same key with a different body is refused. See [Idempotency](/idempotency). - Take the amount from your own database (the order's total), on your server. - Put your order id in `reference`, so every event leads back to your order. - Treat a new collection as **waiting**. It is paid only when Swichi says so (step 5), never when your request returns. **Never** - Take the amount, currency or account from the browser or the customer's request. Anyone can change those. - Mark an order paid because the customer came back to your "thank you" page. - Retry a POST with a new key after a timeout. Read the object instead, or retry with the same key. ## 4. Add a webhook endpoint On **Swichi Gateway → Developers → Webhooks**, add your HTTPS URL, for example `https://shop.example/swichi/webhook`. Sandbox and live have separate endpoints. Swichi shows the endpoint's signing secret once, starting with `whsec_`. **Do** - Store the secret like a password: an environment variable such as `SWICHI_WEBHOOK_SECRET`, or your secret manager. - Use HTTPS only. - Press **Send test event** and check that a signed `webhook.test` arrives and passes your check. **Never** - Commit the secret, log it, or send it to the browser. - Reuse the sandbox secret in live: live has its own endpoint and its own secret. ## 5. Verify every webhook before acting on it Events follow the Standard Webhooks specification. Each request carries `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Your handler must, in this order: 1. **Read the raw body** as bytes or a string, before any JSON parsing. A parsed and re-encoded body does not match the signature. 2. **Check the timestamp**: refuse it if it is more than 5 minutes from your clock. 3. **Check the signature**: `v1,` + base64(HMAC-SHA256(key, `id.timestamp.body`)), where the key is the part of your secret after `whsec_`, base64-decoded. Compare with a constant-time function (`crypto.timingSafeEqual`, `hash_equals`). If it doesn't match, answer `401` and do nothing. 4. **Skip duplicates**: keep the `webhook-id`s you have handled. The same event can arrive more than once; handle it once. 5. **Match it to your order** by `data.reference`, and check that `data.amount` and `data.currency` are what the order expects. 6. **Act**, for example mark the order paid on `collection.succeeded`, then **answer 2xx within 10 seconds**. Do slow work (emails, stock) after answering, from a queue. Code for Node.js, PHP, Laravel and Next.js is on [Webhooks](/webhooks#verify-a-webhook-in-your-code). **Do** - Treat a webhook as a reminder and the API as the truth: when in doubt, read `GET /v1/collections/{id}` with your key. - Run a small job that reads any order still waiting after a few minutes, in case a webhook was missed. **Never** - Act on a webhook whose signature you did not check, or one that is too old. - Trust an event because it came from a known IP address or has the right shape. - Let one failing order stop your endpoint from answering the others. If your endpoint is down, Swichi retries for 3 days (after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, then every 12 h), then turns the endpoint off and tells you. You can resend any event from the endpoint's deliveries. ## 6. Test every outcome in the sandbox Nothing real moves in the sandbox. Use the magic numbers or force an outcome: - A phone ending in `001` pays at once; one ending in `002` declines. - `POST /v1/sandbox/collections/{id}/simulate` with `{"outcome": "succeeded"}` (or `failed`, `expired`) settles a collection on demand. Before going live, check that your integration: - [ ] marks an order paid only after a verified `collection.succeeded`; - [ ] leaves it unpaid on `collection.failed` and `collection.expired`, and lets the customer try again; - [ ] charges once when you send the same request twice (same `Idempotency-Key`); - [ ] refuses a webhook with a wrong signature, and one older than 5 minutes; - [ ] handles the same webhook twice without doing the work twice; - [ ] finds a paid order even when its webhook never arrives (reading the API); - [ ] keeps working when Swichi answers slowly or with an error. See [Sandbox](/sandbox). ## 7. Go live 1. Finish every line of **Developers → Verification**: your identity, your business, Swichi's checks, a settlement account and the terms. See [Go live](/go-live). 2. Turn **Test mode** off. Make a **live key** with the same narrow scopes and IP allow list. 3. Add a **live webhook endpoint**. It gets its own `whsec_` secret. 4. Put the live key and the live secret in your production environment. The code does not change. 5. Make one small real payment end to end, and check the order, the webhook and your records agree. **Never** use a live key in development or tests, or a sandbox key in production. ## 8. Run it safely - **Watch** the endpoint's deliveries for failures, and alert on orders stuck waiting. - **Rotate** keys and the webhook secret on a schedule, and at once when someone with access leaves. Make the new key first, deploy it, then revoke the old one: nothing stops. - **If a key leaks**, revoke it on **API keys** (it stops working at once), check its last use, and make a new one. - **If the webhook secret leaks**, rotate it on the endpoint and deploy the new one. - **Read errors by code**: every error has a `code`, a `doc_url` and a `request_id`. Send the `request_id` when you ask Swichi for help. See [Errors](/errors). - **Limits grow with trust.** A new business starts low; over a limit you get `limit_exceeded`. ## Before you launch - [ ] Keys and secrets live only on your servers, in environment variables or a secret manager. - [ ] Each key has only the scopes it needs and an IP allow list. - [ ] Every POST sends an `Idempotency-Key` from your own record. - [ ] Amounts come from your database, never from the browser. - [ ] Webhooks are verified on the raw body, with a 5-minute window and a constant-time compare. - [ ] Duplicate webhooks are skipped by `webhook-id`. - [ ] An order is paid only after a verified `collection.succeeded` (or reading the API). - [ ] A job catches orders whose webhook never came. - [ ] Sandbox and live have separate keys, endpoints and secrets. - [ ] You know how to revoke a key and rotate the secret today. --- title: API keys description: Swichi Payments keys are separate from messages keys, with scopes, an IP allow list and their own limits. --- # API keys Swichi Payments has its own keys. Make them on **Swichi Gateway → Developers → API keys** in your Swichi dashboard. Keys of other products do not work here: the wrong kind of key is refused with [`key_product_mismatch`](/errors#key_product_mismatch). ## Sandbox and live - **Sandbox keys** reach only your sandbox: test money, magic numbers, nothing real moves. Your sandbox is there from the moment you sign up; press **Get my sandbox key**. See [Sandbox](/sandbox). - **Live keys** are free and move real money. You make them with Test mode off, once your business is verified. See [Go live](/go-live). Sandbox and live never share an id, a key or a wallet. ## Scopes, IP allow list and limits Give each key only what it needs: - **Scopes**: `collections`, `payouts`, `transfers` and `read`. A request outside the key's scopes gets [`missing_scope`](/errors#missing_scope). - **An IP allow list**: requests from other addresses get [`ip_not_allowed`](/errors#ip_not_allowed). - **Its own limits**, which can only be tighter than your business's ([`key_limit_exceeded`](/errors#key_limit_exceeded)). ## Send the key ``` Authorization: Bearer YOUR_SANDBOX_KEY ``` Keep every key on your server. Never put one in a mobile app or a web page. # Sandbox Every Swichi account has a sandbox from the moment it signs up: its own Swichi business, a wallet with TZS 1,000,000 of test money, and a Test Shop to transfer to. Your sandbox keys reach only the sandbox and your live keys only live: they never share an id, a key or a wallet. Nothing real moves: collections go to made-up pushes, payouts to nobody. Webhooks really fire, signed like live ones, so you can build your whole integration here. ## Magic numbers A sandbox payment's outcome is set by how the number ends (collections: the payer's number; payouts: the phone or account number). Use any Tanzanian mobile money prefix, for example `0754 000 001` (M-Pesa) or `0688 000 001` (Airtel Money). | Number ends in | What happens | |---|---| | `001` | Approved (or paid out) at once | | `002` | The payer declines (`failure.code: payer_declined`) | | `003` | Not enough money (`payer_insufficient_funds`) | | `004` | Nobody answers; the collection expires (`payer_no_answer`) | | `005` | Waits: you decide it | | anything else | Waits: you decide it | ## Decide a payment yourself `POST /v1/sandbox/collections/{id}/simulate` with `{"outcome": "succeeded"}`, `"failed"` or `"expired"` settles a waiting collection as if the payer had answered; `POST /v1/sandbox/payouts/{id}/simulate` with `"succeeded"`, `"failed"` or `"reversed"` settles a sent payout. These work with sandbox keys only (`sandbox_only` otherwise). You can do the same without code on **Developers → Sandbox**: send a test payment, then approve, decline or expire it. **Add test money** tops the wallet up again. ## What is the same as live Fees, limits, idempotency, errors, receipts and webhooks behave as they do live. Two things do not: the sandbox has no merchant review (live businesses are reviewed, and new ones start with lower limits and next-day payouts), and payouts are never really sent. # Go live Live keys are free. You make them on **Developers → API keys** (with Test mode off) once every line of the go-live checklist on **Developers → Verification** is done: 1. **Your identity**: your own Swichi account on WhatsApp, verified with your ID and a selfie, connected to your account. 2. **Your business**: tell Swichi what you sell, where (a shop, a WhatsApp or Instagram handle, a website) and how much you expect each month. Swichi verifies sole proprietors first; your BRELA business-name number and TIN are welcome but not required. A reviewer, then a second person, approve it, usually within a working day. 3. **Swichi's checks** of your business are clear. 4. **A settlement account**: the mobile money or bank account your money is paid out to. 5. **The terms**, including what Swichi does not allow. ## What Swichi does not allow Adult content, unlicensed betting and gambling, "investment" and money-doubling schemes, pyramid, forex or crypto signal schemes, lending, drugs, weapons, counterfeit goods, money transfer or float resale, and collecting for other businesses with your key (each business that collects needs its own account). Phone and electronics resale, event tickets, travel and donations are reviewed before you go live. ## Limits grow with trust A new business starts with lower limits on money in and out, its payouts wait until the next day, and it pays out to a few destinations. After 30 quiet days with volume close to what you declared, the limits rise. Payouts above your approval threshold wait for Finance (`pending_approval`). Over a limit, the API answers `limit_exceeded`; try a smaller amount or wait. Swichi watches payments for fraud with plain rules. If your account is under review, collections keep working and payouts wait; if it is on hold, nothing moves (`account_under_review`). Swichi contacts you either way. ## Your code Nothing changes but the key: the same requests, objects, errors and webhooks. Keep the live key on your server only, and give each key only the scopes it needs (`collections`, `payouts`, `transfers`, `read`), an IP allow list and its own limits if you like. # Collections A collection asks a customer's phone to pay: Swichi sends a USSD push, and the customer approves it with their PIN. Send `POST /v1/collections` with the `amount`, `"currency": "TZS"`, the payer's `phone`, your `reference` and an `Idempotency-Key`. The answer comes at once with `status: "pending"`. ## Supported networks Swichi picks the network from the payer's number; you only send the `phone`. | Network | Country | |---|---| | Airtel Money | TZ | | M-Pesa (Vodacom) | TZ | | Mixx by Yas | TZ | | HaloPesa (Halotel) | TZ | The smallest collection is set by Swichi (TZS 500 by default). A smaller `amount` is refused at once with [`amount_too_small`](/errors#amount_too_small); nothing is sent to the phone. ## What happens next | Status | Meaning | |---|---| | `pending` | The push was sent; the payer has not answered yet | | `succeeded` | Swichi confirmed the money with the network; the collection has its fee, `net` and signed receipt | | `failed` | The payer declined or had too little; `failure.code` says why | | `expired` | Nobody approved it in time | Swichi tells your server with the `collection.succeeded`, `collection.failed` and `collection.expired` [webhooks](/webhooks). Try each outcome with the [sandbox's magic numbers](/sandbox). ## List collections Lists page with `limit` and `starting_after`, newest first: ```bash file=examples/pay-list.sh # The last five collections, newest first. curl "https://gateway.swichi.cc/v1/collections?limit=5" \ -H "Authorization: Bearer $SWICHI_KEY" ``` ## Collect a payment in your code Plain HTTP is enough; there is nothing to install. Use your sandbox key while you build (these examples read it from `SWICHI_KEY`) and keep every key on your server. ```bash tab="curl" curl https://gateway.swichi.cc/v1/collections \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042" \ -d '{"amount": 25000, "currency": "TZS", "phone": "0754 000 001", "reference": "order-1042"}' ``` ```js tab="Node.js" const res = await fetch("https://gateway.swichi.cc/v1/collections", { method: "POST", headers: { Authorization: `Bearer ${process.env.SWICHI_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `order-${order.id}`, // the same key when you retry }, body: JSON.stringify({ amount: order.total, currency: "TZS", phone: order.phone, reference: `order-${order.id}` }), }) const collection = await res.json() if (!res.ok) throw new Error(collection.error.message) ``` ```php tab="PHP" $ch = curl_init("https://gateway.swichi.cc/v1/collections"); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer " . getenv("SWICHI_KEY"), "Content-Type: application/json", "Idempotency-Key: order-" . $order["id"], ], CURLOPT_POSTFIELDS => json_encode([ "amount" => $order["total"], "currency" => "TZS", "phone" => $order["phone"], "reference" => "order-" . $order["id"], ]), ]); $collection = json_decode(curl_exec($ch), true); ``` ```php tab="Laravel" use Illuminate\Support\Facades\Http; $collection = Http::withToken(config('services.swichi.key')) ->withHeaders(['Idempotency-Key' => "order-{$order->id}"]) ->post('https://gateway.swichi.cc/v1/collections', [ 'amount' => $order->total, 'currency' => 'TZS', 'phone' => $order->phone, 'reference' => "order-{$order->id}", ]) ->throw() ->json(); ``` ```ts tab="Next.js" // app/api/pay/route.ts: the key stays on the server. export async function POST(req: Request) { const { orderId, amount, phone } = await req.json() const res = await fetch("https://gateway.swichi.cc/v1/collections", { method: "POST", headers: { Authorization: `Bearer ${process.env.SWICHI_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `order-${orderId}`, }, body: JSON.stringify({ amount, currency: "TZS", phone, reference: `order-${orderId}` }), }) return Response.json(await res.json(), { status: res.status }) } ``` Retry a failed request with the same `Idempotency-Key`: the money moves once ([Idempotency](/idempotency)). Errors are on [Errors](/errors). # Checkout links A checkout link is a Swichi page your customer opens to pay. A fixed `amount` is paid once and opens an order; give `min_amount` and `max_amount` instead for the payer to choose. ```bash file=examples/pay-link.sh # A hosted checkout link for one order. Keep the url: it is shown only now. curl https://gateway.swichi.cc/v1/checkout/links \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: link-order-1043" \ -d '{"amount": 15000, "description": "Order 1043", "order_reference": "1043", "expires_in_days": 3}' ``` When a link is paid, Swichi sends a `link.paid` [webhook](/webhooks) with the link, the payment's amount and its receipt. Read a link with `GET /v1/checkout/links/{id}`, and stop it taking payments with `POST /v1/checkout/links/{id}/disable`. ## Next steps - [Webhooks](/webhooks) # Payouts: mobile money Pay out to Airtel Money, Mixx by Yas and HaloPesa (M-Pesa payouts open later). Send `POST /v1/payouts` with the `amount`, `"currency": "TZS"`, your `reference`, an `Idempotency-Key` and a `destination` of type `mobile_money` with the `phone` and `name`. ```bash file=examples/pay-payout.sh # Pay out to mobile money. Numbers ending in 001 are paid at once in the sandbox. save: PAYOUT_ID=id curl https://gateway.swichi.cc/v1/payouts \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: supplier-77" \ -d '{"amount": 10000, "currency": "TZS", "reference": "supplier-77", "destination": {"type": "mobile_money", "phone": "0688 000 001", "name": "Juma Ali"}}' ``` ## Supported networks Swichi picks the network from the number in `destination.phone`. | Network | Payouts | |---|---| | Airtel Money | Yes | | Mixx by Yas | Yes | | HaloPesa | Yes | | M-Pesa (Vodacom) | Not yet: the request is refused at once with [`method_not_available`](/errors#method_not_available) | The smallest payout is set by Swichi (TZS 500 by default). A smaller `amount` is refused at once with [`amount_too_small`](/errors#amount_too_small); no money is held. ## What happens next | Status | Meaning | |---|---| | `pending` | It is being sent | | `pending_approval` | It is over your approval threshold and waits for Finance | | `in_cooldown` | It waits, for example until the next day for a new business | | `succeeded` | The money reached the account | | `failed` | It could not be sent; the money and fee are back in your wallet | Until it is sent, `POST /v1/payouts/{id}/cancel` gives the money back. Swichi tells your server with the `payout.succeeded`, `payout.failed` and `payout.pending_approval` [webhooks](/webhooks). The payout and its fee come out of your wallet: with too little, the request fails with [`insufficient_funds`](/errors#insufficient_funds). Over a limit it answers [`limit_exceeded`](/errors#limit_exceeded). Retry with the same `Idempotency-Key`: the money moves once ([Idempotency](/idempotency)). ## Next steps - [Payouts: bank](/payouts-bank) # Payouts: bank A bank payout is the same `POST /v1/payouts` as a [mobile money payout](/payouts-mobile-money), with a `destination` of type `bank`: the `bank_code`, the `account_number` and the account holder's `name`. ```bash file=examples/pay-bank-payout.sh # Pay out to a bank account, with a code from GET /v1/banks. curl https://gateway.swichi.cc/v1/payouts \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: rent-2026-10" \ -d '{"amount": 50000, "currency": "TZS", "destination": {"type": "bank", "bank_code": "crdb", "account_number": "0150000000001", "name": "Neema Mushi"}}' ``` ## Bank codes Send Swichi's `bank_code`, not a SWIFT code. `GET /v1/banks` lists the banks Swichi can pay out to right now, with the same codes: | `bank_code` | Bank | SWIFT | |---|---|---| | `absa` | Absa Bank Tanzania | BARCTZTZ | | `access` | Access Bank Tanzania | ACTZTZTZ | | `bancabc` | African Banking Corporation Tanzania (BancABC) | FMBZTZTX | | `akiba` | Akiba Commercial Bank | AKCOTZTZ | | `amana` | Amana Bank | AMNNTZTZ | | `azania` | Azania Bank | AZANTZTZ | | `bank_of_africa` | Bank of Africa Tanzania | EUAFTZTZ | | `bank_of_baroda` | Bank of Baroda Tanzania | BARBTZTZ | | `bank_of_india` | Bank of India Tanzania | BKIDTZTZ | | `canara` | Canara Bank Tanzania | - | | `china_dasheng` | China Dasheng Bank | CDSHTZTZ | | `citi` | Citibank Tanzania | CITITZTZ | | `crdb` | CRDB Bank | CORUTZTZ | | `dcb` | DCB Commercial Bank | DASUTZTZ | | `diamond_trust` | Diamond Trust Bank Tanzania | DTKETZTZ | | `ecobank` | Ecobank Tanzania | ECOCTZTZ | | `equity` | Equity Bank Tanzania | EQBLTZTZ | | `exim` | Exim Bank Tanzania | EXTNTZTZ | | `first_national` | First National Bank Tanzania | FIRNTZTX | | `guaranty_trust` | Guaranty Trust Bank Tanzania | GTBITZTZ | | `habib` | Habib African Bank | HABLTZTZ | | `i_and_m` | I&M Bank Tanzania | IMBLTZTZ | | `icb` | International Commercial Bank Tanzania | BKMYTZTZ | | `kcb` | KCB Bank Tanzania | KCBLTZTZ | | `kilimanjaro` | Kilimanjaro Co-operative Bank | KLMJTZTZ | | `maendeleo` | Maendeleo Bank | MBTLTZTZ | | `mkombozi` | Mkombozi Commercial Bank | MKCBTZTZ | | `mwalimu` | Mwalimu Commercial Bank | MWCOTZTZ | | `mwanga_hakika` | Mwanga Hakika Microfinance Bank | MWCBTZTZ | | `nbc` | National Bank of Commerce | NLCBTZTX | | `ncba` | NCBA Bank Tanzania | CBAFTZTZ | | `nmb` | NMB Bank | NMIBTZTZ | | `people_s_bank_of_zanzibar` | People's Bank of Zanzibar | PBZATZTZ | | `selcompesa` | SelcomPesa Bank | ACTZTZTZ | | `stanbic` | Stanbic Bank Tanzania | SBICTZTX | | `standard_chartered` | Standard Chartered Bank Tanzania | SCBLTZTX | | `tcb` | Tanzania Commercial Bank | TAPBTZTZ | | `uchumi` | Uchumi Commercial Bank | UCCTTZTZ | | `uba` | United Bank for Africa Tanzania | UNAFTZTZ | | `yetu` | Yetu Microfinance Bank | YETMTZTZ | A code that is not in the list is refused at once with [`invalid_request`](/errors#invalid_request); no money is held. ```bash file=examples/pay-banks.sh # Bank codes for bank payouts. curl https://gateway.swichi.cc/v1/banks \ -H "Authorization: Bearer $SWICHI_KEY" ``` ## What happens next A bank payout moves through the same statuses as a mobile money one (`pending`, `pending_approval`, `in_cooldown`, then `succeeded` or `failed`), can be canceled with `POST /v1/payouts/{id}/cancel` until it is sent, and sends the same `payout.*` [webhooks](/webhooks). In the sandbox, the account number's last digits set the outcome ([Sandbox](/sandbox)). ## Next steps - [Transfers](/transfers) # Transfers A transfer moves money at once to another Swichi business, by its account id (`account` in `GET /v1/balance`). Your sandbox has a Test Shop to try it with (its id is on the Sandbox page). ```bash file=examples/pay-transfer.sh # Move money at once to another Swichi business, by its account id. curl https://gateway.swichi.cc/v1/transfers \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: stock-9" \ -d '{"amount": 3000, "currency": "TZS", "destination_account": "$TEST_SHOP", "description": "Stock"}' ``` A transfer your key made sends a `transfer.succeeded` [webhook](/webhooks). Read one with `GET /v1/transfers/{id}`, or list them with `GET /v1/transfers`. An account id that does not exist answers [`destination_not_found`](/errors#destination_not_found). ## Next steps - [Checkout links](/checkout-links) # Webhooks Add an endpoint on **Swichi Gateway → Developers → Webhooks**. Sandbox and live have their own endpoints: the header's Test mode switch picks which you are looking at. Press **Send test event** to see a signed `webhook.test` arrive. ## Events | Event | When | |---|---| | `collection.succeeded` | Swichi confirmed the money with the network; `data.receipt` is the signed receipt | | `collection.failed` | The payer declined or had too little; `data.failure` says why | | `collection.expired` | Nobody approved it in time | | `payout.succeeded` | The money reached the mobile money account or bank | | `payout.failed` | It could not be sent; the money and fee are back in your wallet | | `payout.pending_approval` | It is over your approval threshold and waits for Finance | | `transfer.succeeded` | A transfer your key made went through | | `link.paid` | A checkout link of your business was paid | | `balance.low` | Money leaving took your balance under your alert (Developers → Settings), once a day | The body is JSON: `{"type": "...", "livemode": false, "timestamp": "...", "data": {...}}`, where `data` is the object as the API returns it (a collection, a payout, a transfer; for `link.paid` the link with the payment's amount and receipt). Each event is sent once per change of state, from Swichi's own records: never forwarded from a network. If your server misses one, it is retried; you can also read the object with the API at any time. ## Verify the signature Events follow the Standard Webhooks specification: `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, the signature being `v1,` + base64(HMAC-SHA256(secret, id + "." + timestamp + "." + body)) with the part of your secret after `whsec_`, base64-decoded. Refuse timestamps older than 5 minutes, and act on an event only after checking its signature. Code for Node.js, PHP, Laravel and Next.js is below. ## Verify a webhook in your code ```js tab="Node.js" import crypto from "node:crypto" // secret: the endpoint's whsec_… secret; body: the raw request body as a string. export function verify(secret, headers, body) { const id = headers["webhook-id"], ts = headers["webhook-timestamp"] if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64") const want = "v1," + crypto.createHmac("sha256", key).update(`${id}.${ts}.${body}`).digest("base64") return headers["webhook-signature"].split(" ").some((sig) => sig.length === want.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) } ``` ```php tab="PHP" function swichi_verify(string $secret, array $h, string $body): bool { if (abs(time() - (int) $h['webhook-timestamp']) > 300) return false; $key = base64_decode(preg_replace('/^whsec_/', '', $secret)); $want = 'v1,' . base64_encode(hash_hmac('sha256', "{$h['webhook-id']}.{$h['webhook-timestamp']}.$body", $key, true)); foreach (explode(' ', $h['webhook-signature']) as $sig) { if (hash_equals($want, $sig)) return true; } return false; } ``` ```php tab="Laravel" Route::post('/swichi/webhook', function (Request $request) { $h = ['webhook-id' => $request->header('webhook-id'), 'webhook-timestamp' => $request->header('webhook-timestamp'), 'webhook-signature' => $request->header('webhook-signature')]; abort_unless(swichi_verify(config('services.swichi.webhook_secret'), $h, $request->getContent()), 401); $event = $request->json()->all(); if ($event['type'] === 'collection.succeeded') { Order::where('reference', $event['data']['reference'])->update(['paid' => true]); } return response()->noContent(); }); ``` ```ts tab="Next.js" // app/api/swichi/webhook/route.ts import { verify } from "@/lib/swichi" // the Node.js function above export async function POST(req: Request) { const body = await req.text() const headers = Object.fromEntries(req.headers) if (!verify(process.env.SWICHI_WEBHOOK_SECRET!, headers, body)) return new Response(null, { status: 401 }) const event = JSON.parse(body) if (event.type === "collection.succeeded") { // mark the order paid, by event.data.reference } return new Response(null, { status: 204 }) } ``` ## Retries and replay Answer with any 2xx within 10 seconds. Otherwise Swichi retries after 5 seconds, 5 minutes, 30 minutes, 2, 5 and 10 hours, then every 12 hours for 3 days; then the endpoint is turned off and the owner gets an e-mail. Every delivery is on the endpoint's page, with **Resend**. Use the event's `webhook-id` to skip one you already handled. ## Next steps - [Sandbox](/sandbox): send test events that fire real webhooks. - [Errors](/errors) # API reference The reference is generated from [payments.yaml](/payments.yaml), the same contract the API is tested against. Base URL: `https://gateway.swichi.cc/v1`. **Try it** runs a real request from your browser. Paste a **sandbox** key only: the sandbox uses test money and nothing real moves. Live keys are for your server; never paste one here. - Authenticate with `Authorization: Bearer ` ([API keys](/api-keys)). - Send `Idempotency-Key` on every POST that moves money ([Idempotency](/idempotency)). - Amounts are whole Tanzanian shillings (`"currency": "TZS"`). - Errors have one shape, with `retryable` and a `doc_url` to [Errors](/errors). # Idempotency Networks fail. To retry without moving money twice, every POST that moves money (a collection, a payout, a transfer, a checkout link) needs an `Idempotency-Key` header: any string up to 255 characters that names the thing you want to happen once. ```bash curl https://gateway.swichi.cc/v1/collections \ -H "Authorization: Bearer $SWICHI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042" \ -d '{"amount": 25000, "currency": "TZS", "phone": "0754 000 005", "reference": "order-1042"}' ``` - A retry with the same key and the same body returns the first answer, with the same status code, and moves nothing again. - The same key with a **different** body is refused: [`idempotency_conflict`](/errors#idempotency_conflict). - A retry while the first request is still running gets [`idempotency_in_progress`](/errors#idempotency_in_progress): wait a moment and retry with the same key. ## Retrying Every error says whether a retry can help (`retryable`). Retry network errors, `429` and `5xx` with the same key; never retry other `4xx` unchanged. ```js tab="Node.js" for (let attempt = 0; attempt < 4; attempt++) { const res = await fetch("https://gateway.swichi.cc/v1/collections", { method: "POST", headers, body }) if (res.status !== 429 && res.status < 500) return res.json() const wait = Number(res.headers.get("Retry-After") ?? 2 ** attempt) await new Promise((r) => setTimeout(r, wait * 1000)) } ``` ```php tab="PHP" $response = Http::withToken($key) ->withHeaders(['Idempotency-Key' => "order-{$order->id}"]) ->retry(4, fn ($attempt, $e) => ($e->response?->header('Retry-After') ?: 2 ** $attempt) * 1000, fn ($e) => $e instanceof ConnectionException || $e->response->status() === 429 || $e->response->serverError()) ->post('https://gateway.swichi.cc/v1/collections', $collection); ``` ```python tab="Python" for attempt in range(4): res = requests.post("https://gateway.swichi.cc/v1/collections", json=collection, headers={"Authorization": f"Bearer {key}", "Idempotency-Key": f"order-{order_id}"}) if res.status_code != 429 and res.status_code < 500: break time.sleep(int(res.headers.get("Retry-After", 2 ** attempt))) ``` ## Choosing keys Use your own ids: `order-1042`, `payout-supplier-77-march`. Do not use a random value made per attempt; it defeats the point. Keys belong to your account and mode: sandbox and live never collide. ## Next steps - [Webhooks](/webhooks): hear when money moves instead of polling. - [Errors](/errors): every code and whether it is safe to retry. # Rate limits ## Requests Send requests faster than your key allows and you get `429` with [`rate_limited`](/errors#rate_limited) and a `Retry-After` header in seconds. Wait that long, then retry with the **same** `Idempotency-Key`: no money moves twice ([Idempotency](/idempotency)). Don't poll for status in a loop: add a [webhook](/webhooks) and Swichi tells your server when a payment succeeds or fails. ## Money Swichi also limits how much money moves, per business and, if you like, per key: - Your business has limits per payment, per day and per month. Going over is refused with [`limit_exceeded`](/errors#limit_exceeded). The limits grow as Swichi gets to know your business: see [Go live](/go-live#limits-grow-with-trust). - A key can carry tighter limits of its own, set when you make it. Going over is refused with [`key_limit_exceeded`](/errors#key_limit_exceeded). See [API keys](/api-keys). ## Next steps - [API keys](/api-keys) - [Go live](/go-live) Every error has the same shape. `code` is stable and has a section on this page (its `doc_url` points here); `message` says what happened in plain words; `retryable` says whether the same request may succeed if you send it again later (with the same `Idempotency-Key`); `param` names the field at fault; `request_id` finds the request in your logs. ```json { "error": { "type": "payment_error", "code": "insufficient_funds", "message": "Your Swichi balance is too low for this payout and its fee.", "retryable": false, "doc_url": "https://docs.swichi.cc/errors#insufficient_funds", "request_id": "req_01J…" } } ``` Why a collection or payout failed later is on the object itself (`failure.code` and `failure.message`, which you may show the payer) and in its `collection.failed` or `payout.failed` webhook. Swichi never shows a network's or a provider's own error text. ## authentication_required Send your payments key as `Authorization: Bearer `. ## invalid_api_key The key is not valid: it may be revoked, rolled more than 24 hours ago, or mistyped. Make a new one under Swichi Gateway → Developers → API keys. ## invalid_request The request is malformed; `message` says what to fix and `param` which field. Do not retry unchanged. ## amount_too_small The amount is under Swichi's smallest collection or payout for that method; `message` says the minimum (for example "The smallest withdrawal is TZS 5,000.") and `param` is `amount`. Nothing was held or sent. Retry with at least the minimum. ## amount_too_large The amount is over Swichi's largest collection or payout for that method; `message` says the maximum (for example "The largest payment is TZS 5,000,000.") and `param` is `amount`. Nothing was held or sent. Split it into smaller payments. ## not_found There is no such object for your business in this mode. Sandbox and live never share an id: a sandbox id is never found with a live key, or the reverse. ## idempotency_conflict This `Idempotency-Key` was used with a different request. Use a new key for a new request. ## idempotency_in_progress A request with this `Idempotency-Key` is still running. Retry in a moment with the same key. ## rate_limited You are sending requests faster than your limit. Wait `Retry-After` seconds and retry. ## key_product_mismatch This key cannot move money. Use a payments key from Swichi Gateway → Developers → API keys. ## missing_scope The key lacks the scope this request needs (`collections`, `payouts`, `transfers` or `read`). Add it to the key on the API keys page, or use another key. ## ip_not_allowed The request came from an address that is not on the key's own IP allow list. Add the address or range to the key. ## currency_not_supported Swichi Gateway moves Tanzanian shillings only: send `"currency": "TZS"` and amounts in whole shillings. ## network_not_supported This number's network is not one Swichi collects from or pays out to, or it does not match the `network` you sent. Collections work from M-Pesa, Airtel Money, Mixx by Yas and HaloPesa numbers. ## method_not_available This way of paying is not available now: payouts to M-Pesa are not open yet, or the network is not answering. Try another network or bank, or retry later when `retryable` is true. ## collection_not_paid Only a paid (`succeeded`) collection can be refunded. A pending, failed or expired collection took no money from the payer. ## refund_exceeds_payment The refund is more than is left on the collection: what it paid, less refunds already made or on their way. Read the collection's refunds, then refund what is left, or nothing. ## insufficient_funds Your Swichi balance is too low for this payout or transfer and its fee. Collect first, or wait for money on its way in (`incoming` in `GET /balance`). ## limit_exceeded This is over one of your business's Swichi limits (per payment, per day, per month, the balance cap, or how many payout destinations a new business may have). Limits grow with your history; new businesses start low. Try a smaller amount or wait for the day or month to turn. ## key_limit_exceeded This is over a limit you set on this key (per payment, or payouts per day). Change it on the API keys page, or use another key. ## payee_blocked Swichi cannot send money to this number or account, or take money from it. ## account_under_review Swichi is reviewing your business. While it reviews, collections keep working and payouts wait; if your account is on hold, nothing moves. We contact you; you do not need to do anything. ## payouts_paused Swichi paused payouts for a check. Your money is safe; retry later. ## account_not_ready Your business is not ready for live payments: finish the go-live checklist under Swichi Gateway → Developers → Verification. Your test key keeps working in the sandbox. Every live request checks the whole checklist again (an active business account, an approved review, a merchant profile with the current terms, screening with no open case, and a settlement account). When one lapses, live requests answer this code and the message says what to fix; the Developers page shows the same item. ## live_not_open Swichi Gateway live payments are not open yet. Keep building in the sandbox; your integration works the same when live opens. ## payout_not_cancellable Only a payout that has not been sent (`pending_approval` or `in_cooldown`) can be cancelled. ## sandbox_only This request works with a test key only (the sandbox's simulate endpoints). ## destination_not_found There is no Swichi business with this account id in this mode, or it cannot receive money now. ## internal_error Something went wrong on our side. Retry with the same `Idempotency-Key`; if it persists, send us the `request_id`. --- title: Changelog description: What changed in the Swichi Payments API. Also as RSS at /changelog.xml. --- # Changelog Every change to the API is listed here, newest first. Breaking changes get a new version and at least six months of notice. ## 2026-10-01: Swichi docs at docs.swichi.cc - The Swichi Payments docs have their own site; the pages live at the root (`/collections`, `/webhooks`, ...), and old `/payments/...` addresses redirect there. ## 2026-09-29: Swichi Gateway payments API (sandbox) - A payments API on `https://gateway.swichi.cc/v1`: collections by mobile money, payouts to mobile money and banks, transfers between Swichi businesses, checkout links, balance, transactions, receipts and banks, with payments keys (scopes, IP allow lists, their own limits) kept apart from other keys. See the [quickstart](/). - A sandbox for every account, with test money and magic numbers; live payments open later. - Every error says whether to retry (`retryable`); new codes `key_product_mismatch`, `missing_scope` and `ip_not_allowed`. # Use with AI The fastest way to integrate Swichi is to let your editor's AI read the docs for you. ## Give an AI the docs - [`llms.txt`](/llms.txt): the index of every page, as links to Markdown. - [`llms-full.txt`](/llms-full.txt): every page and the API contract in one file. Paste it into any chat. - Every page is Markdown: add `.md` to its address, or use **Copy page** at the top of the page. - [`payments.yaml`](/payments.yaml): the whole API contract (OpenAPI 3.1). Then ask, for example: "Add a mobile money checkout to my Laravel order page with Swichi. Use the sandbox key from my .env and verify the webhook signature." Your AI should only ever see a **sandbox** key. Live keys belong on your server; see [Secure integration](/secure-integration). ```yaml openapi: 3.1.0 info: title: Swichi Gateway API version: "1.0.0" summary: Collect money by mobile money, pay out to mobile money and banks, and move money between Swichi businesses. description: | Swichi Gateway is the payments API of Swichi (docs/multichannel/16). Ask a customer's phone to pay (a USSD push), pay out to mobile money and banks, move money to another Swichi business, make checkout links, and read your balance and every movement of it. Authenticate with `Authorization: Bearer `, a key made under Swichi Gateway → Developers → API keys. A test key works in the sandbox (test money, magic phone numbers, nothing real moves); a live key moves real money once your business is verified. Sandbox and live never share an id, a key or a wallet. Amounts are whole Tanzanian shillings (`TZS`, integers). Every POST that moves money needs an `Idempotency-Key` header: a retry with the same key and body returns the first answer and moves nothing again; the same key with another body is refused. Errors always have the same shape, with `retryable` and a `doc_url` explaining the fix. Status changes arrive as signed webhooks (collection.succeeded, payout.failed, …); a collection is `succeeded` only after Swichi confirmed the money with the network. This file is the contract: handlers and docs follow it, and contract tests check every response against it. contact: name: Swichi developers servers: - url: https://gateway.swichi.cc/v1 security: - apiKey: [] tags: - name: Collections - name: Payouts - name: Transfers - name: Checkout links - name: Balance - name: Receipts - name: Capabilities - name: Sandbox paths: /collections: post: tags: [Collections] operationId: createCollection summary: Ask a phone to pay description: | Sends a USSD push to the payer's phone and answers at once with the collection, `pending`. It becomes `succeeded` when Swichi has confirmed the money with the network, `failed` when the payer refuses or has too little, or `expired` when nobody answers in time. Needs the `collections` scope. parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreateCollection" } responses: "201": { $ref: "#/components/responses/Collection" } "200": { $ref: "#/components/responses/Collection" } default: { $ref: "#/components/responses/Error" } get: tags: [Collections] operationId: listCollections summary: List collections parameters: - { $ref: "#/components/parameters/Limit" } - { $ref: "#/components/parameters/StartingAfter" } - { name: status, in: query, schema: { $ref: "#/components/schemas/CollectionStatus" } } - { name: reference, in: query, schema: { type: string, maxLength: 100 } } - { $ref: "#/components/parameters/CreatedFrom" } - { $ref: "#/components/parameters/CreatedTo" } responses: "200": description: A page of collections, newest first. content: application/json: schema: allOf: - $ref: "#/components/schemas/ListBase" - properties: data: { type: array, items: { $ref: "#/components/schemas/Collection" } } default: { $ref: "#/components/responses/Error" } /collections/{id}: get: tags: [Collections] operationId: getCollection summary: Get a collection parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/Collection" } default: { $ref: "#/components/responses/Error" } /collections/{id}/refund: post: tags: [Collections] operationId: refundCollection summary: Refund a collection description: | Pays a paid collection back to the phone that paid it, in full (no body) or in part (`amount`). Refunds of one collection never add up to more than it paid; a refund still on its way counts. The money and the payout fee come from your wallet. `collection.refunded` fires when the payer has it. Needs the `collections` scope. parameters: [{ $ref: "#/components/parameters/ID" }, { $ref: "#/components/parameters/IdempotencyKey" }] requestBody: required: false content: application/json: schema: type: object properties: amount: { type: integer, minimum: 1, description: Whole shillings; the rest of the collection when left out. } responses: "201": { $ref: "#/components/responses/Refund" } "200": { $ref: "#/components/responses/Refund" } default: { $ref: "#/components/responses/Error" } /refunds/{id}: get: tags: [Collections] operationId: getRefund summary: Get a refund parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/Refund" } default: { $ref: "#/components/responses/Error" } /payouts: post: tags: [Payouts] operationId: createPayout summary: Pay out description: | Holds the amount and the fee on your wallet and sends it to mobile money or a bank. It answers `pending`, or `pending_approval` above your approval threshold (Finance approves it), or `in_cooldown` while it waits (a new merchant's payouts wait until the next day; a first large payout to a new destination waits too). Until it is sent it can be cancelled. Needs the `payouts` scope. parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreatePayout" } responses: "201": { $ref: "#/components/responses/Payout" } "200": { $ref: "#/components/responses/Payout" } default: { $ref: "#/components/responses/Error" } get: tags: [Payouts] operationId: listPayouts summary: List payouts parameters: - { $ref: "#/components/parameters/Limit" } - { $ref: "#/components/parameters/StartingAfter" } - { name: status, in: query, schema: { $ref: "#/components/schemas/PayoutStatus" } } - { name: reference, in: query, schema: { type: string, maxLength: 100 } } - { $ref: "#/components/parameters/CreatedFrom" } - { $ref: "#/components/parameters/CreatedTo" } responses: "200": description: A page of payouts, newest first. content: application/json: schema: allOf: - $ref: "#/components/schemas/ListBase" - properties: data: { type: array, items: { $ref: "#/components/schemas/Payout" } } default: { $ref: "#/components/responses/Error" } /payouts/{id}: get: tags: [Payouts] operationId: getPayout summary: Get a payout parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/Payout" } default: { $ref: "#/components/responses/Error" } /payouts/{id}/cancel: post: tags: [Payouts] operationId: cancelPayout summary: Cancel a payout not yet sent description: Cancels a payout that is `pending_approval` or `in_cooldown`; the money goes back to your wallet. parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/Payout" } default: { $ref: "#/components/responses/Error" } /transfers: post: tags: [Transfers] operationId: createTransfer summary: Move money to another Swichi business description: Instant, between Swichi wallets; no network is involved. Needs the `transfers` scope. parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreateTransfer" } responses: "201": { $ref: "#/components/responses/Transfer" } "200": { $ref: "#/components/responses/Transfer" } default: { $ref: "#/components/responses/Error" } get: tags: [Transfers] operationId: listTransfers summary: List transfers parameters: - { $ref: "#/components/parameters/Limit" } - { $ref: "#/components/parameters/StartingAfter" } - { name: reference, in: query, schema: { type: string, maxLength: 100 } } - { $ref: "#/components/parameters/CreatedFrom" } - { $ref: "#/components/parameters/CreatedTo" } responses: "200": description: A page of transfers, newest first. content: application/json: schema: allOf: - $ref: "#/components/schemas/ListBase" - properties: data: { type: array, items: { $ref: "#/components/schemas/Transfer" } } default: { $ref: "#/components/responses/Error" } /transfers/{id}: get: tags: [Transfers] operationId: getTransfer summary: Get a transfer parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/Transfer" } default: { $ref: "#/components/responses/Error" } /checkout/links: post: tags: [Checkout links] operationId: createCheckoutLink summary: Make a checkout link description: | A hosted Swichi Checkout page your customer opens to pay by mobile money. A fixed amount is paid once and opens an order; with no amount the payer chooses between the minimum and the maximum, as many times as they like. The `url` is returned only now: keep it. Needs the `collections` scope. parameters: [{ $ref: "#/components/parameters/IdempotencyKey" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/CreateCheckoutLink" } responses: "201": { $ref: "#/components/responses/CheckoutLink" } "200": { $ref: "#/components/responses/CheckoutLink" } default: { $ref: "#/components/responses/Error" } /checkout/links/{id}: get: tags: [Checkout links] operationId: getCheckoutLink summary: Get a checkout link parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/CheckoutLink" } default: { $ref: "#/components/responses/Error" } /checkout/links/{id}/disable: post: tags: [Checkout links] operationId: disableCheckoutLink summary: Stop a checkout link parameters: [{ $ref: "#/components/parameters/ID" }] responses: "200": { $ref: "#/components/responses/CheckoutLink" } default: { $ref: "#/components/responses/Error" } /balance: get: tags: [Balance] operationId: getBalance summary: Get your balance responses: "200": description: Your wallets. content: application/json: schema: { $ref: "#/components/schemas/Balance" } default: { $ref: "#/components/responses/Error" } /transactions: get: tags: [Balance] operationId: listTransactions summary: List your wallet's movements description: The ledger's lines on your wallet, the same figures Swichi's reconciliation uses. parameters: - { $ref: "#/components/parameters/Limit" } - { $ref: "#/components/parameters/StartingAfter" } responses: "200": description: A page of movements, newest first. content: application/json: schema: allOf: - $ref: "#/components/schemas/ListBase" - properties: data: { type: array, items: { $ref: "#/components/schemas/Transaction" } } default: { $ref: "#/components/responses/Error" } /receipts/{code}: get: tags: [Receipts] operationId: getReceipt summary: Check a receipt description: A signed Swichi receipt for a payment to your business, and whether it is genuine. parameters: - { name: code, in: path, required: true, schema: { type: string, minLength: 10, maxLength: 12 } } responses: "200": description: The receipt. content: application/json: schema: { $ref: "#/components/schemas/Receipt" } default: { $ref: "#/components/responses/Error" } /banks: get: tags: [Payouts] operationId: listBanks summary: List banks you can pay out to responses: "200": description: Bank codes for bank payouts. content: application/json: schema: type: object required: [object, data] properties: object: { const: list } data: { type: array, items: { $ref: "#/components/schemas/Bank" } } default: { $ref: "#/components/responses/Error" } /capabilities: get: tags: [Capabilities] operationId: listCapabilities summary: What you can do now description: | Every feature with its state: `live` when the API has it and Swichi serves it now, `soon` otherwise (bills, airtime, name lookups and cash-out come to the API after they are stable in Swichi). A live feature lists the networks, banks or billers it serves. responses: "200": description: The features. content: application/json: schema: type: object required: [object, data] properties: object: { const: list } data: { type: array, items: { $ref: "#/components/schemas/Capability" } } default: { $ref: "#/components/responses/Error" } /sandbox/collections/{id}/simulate: post: tags: [Sandbox] operationId: simulateCollection summary: Decide a sandbox collection description: Test keys only. Settles a pending sandbox collection as if the payer had answered. parameters: [{ $ref: "#/components/parameters/ID" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/Simulate" } responses: "200": { $ref: "#/components/responses/Collection" } default: { $ref: "#/components/responses/Error" } /sandbox/payouts/{id}/simulate: post: tags: [Sandbox] operationId: simulatePayout summary: Decide a sandbox payout description: Test keys only. Settles a sent sandbox payout as if the network had answered. parameters: [{ $ref: "#/components/parameters/ID" }] requestBody: required: true content: application/json: schema: { $ref: "#/components/schemas/Simulate" } responses: "200": { $ref: "#/components/responses/Payout" } default: { $ref: "#/components/responses/Error" } components: securitySchemes: apiKey: type: http scheme: bearer description: A Swichi Gateway payments key. parameters: IdempotencyKey: name: Idempotency-Key in: header required: true description: A unique value you keep and send again when you retry (up to 255 characters). schema: { type: string, maxLength: 255 } ID: name: id in: path required: true schema: { type: string } Limit: name: limit in: query schema: { type: integer, minimum: 1, maximum: 100, default: 20 } StartingAfter: name: starting_after in: query description: The id of the last object of the previous page. schema: { type: string } CreatedFrom: name: created_from in: query description: Only objects made on or after this day (YYYY-MM-DD, East Africa Time). schema: { type: string, format: date } CreatedTo: name: created_to in: query description: Only objects made on or before this day (YYYY-MM-DD, East Africa Time). schema: { type: string, format: date } responses: Collection: description: A collection. content: application/json: schema: { $ref: "#/components/schemas/Collection" } Refund: description: A refund. content: application/json: schema: { $ref: "#/components/schemas/Refund" } Payout: description: A payout. content: application/json: schema: { $ref: "#/components/schemas/Payout" } Transfer: description: A transfer. content: application/json: schema: { $ref: "#/components/schemas/Transfer" } CheckoutLink: description: A checkout link. content: application/json: schema: { $ref: "#/components/schemas/CheckoutLink" } Error: description: An error. content: application/json: schema: { $ref: "#/components/schemas/ErrorResponse" } schemas: Amount: { type: integer, minimum: 1, maximum: 1000000000000 } Currency: { type: string, enum: [TZS] } Network: { type: string, enum: [mpesa, airtel, mixx, halopesa] } Metadata: type: object description: Your own keys and values (up to 20), returned as sent. maxProperties: 20 additionalProperties: { type: [string, number, boolean] } Failure: type: [object, "null"] required: [code, message] properties: code: { type: string, description: A stable code, for example payer_declined. } message: { type: string, description: Words you can show the payer. } ListBase: type: object required: [object, data, has_more] properties: object: { const: list } data: { type: array } has_more: { type: boolean } CreateCollection: type: object additionalProperties: false required: [amount, currency, phone] properties: amount: { $ref: "#/components/schemas/Amount" } currency: { $ref: "#/components/schemas/Currency" } phone: { type: string, description: "The payer's number: +255712345678 or 0712 345 678." } network: { $ref: "#/components/schemas/Network" } reference: { type: string, maxLength: 100, description: Your own reference, such as an order number. } description: { type: string, maxLength: 200 } metadata: { $ref: "#/components/schemas/Metadata" } CollectionStatus: { type: string, enum: [pending, succeeded, failed, expired] } Collection: type: object required: [id, object, livemode, amount, fee, net, currency, status, network, phone, reference, description, metadata, failure, receipt, created_at, expires_at] properties: id: { type: string, pattern: "^col_[0-9a-f]{32}$" } object: { const: collection } livemode: { type: boolean } amount: { type: integer } fee: { type: integer, description: Swichi's fee, taken from the amount. } net: { type: integer, description: What reaches your wallet. } currency: { $ref: "#/components/schemas/Currency" } status: { $ref: "#/components/schemas/CollectionStatus" } network: { $ref: "#/components/schemas/Network" } phone: { type: string, description: The payer's number, masked. } reference: { type: string } description: { type: string } metadata: { $ref: "#/components/schemas/Metadata" } failure: { $ref: "#/components/schemas/Failure" } receipt: { type: [string, "null"], description: The Swichi receipt code once paid. } created_at: { type: string, format: date-time } expires_at: { type: string, format: date-time } PayoutDestinationRequest: type: object additionalProperties: false required: [type] properties: type: { type: string, enum: [mobile_money, bank] } phone: { type: string, description: Mobile money number. } network: { $ref: "#/components/schemas/Network" } bank_code: { type: string, description: From GET /banks. } account_number: { type: string, maxLength: 40 } name: { type: string, maxLength: 200, description: The recipient's name (required for banks). } CreatePayout: type: object additionalProperties: false required: [amount, currency, destination] properties: amount: { $ref: "#/components/schemas/Amount" } currency: { $ref: "#/components/schemas/Currency" } destination: { $ref: "#/components/schemas/PayoutDestinationRequest" } reference: { type: string, maxLength: 100 } description: { type: string, maxLength: 200 } metadata: { $ref: "#/components/schemas/Metadata" } PayoutStatus: { type: string, enum: [pending, pending_approval, in_cooldown, succeeded, failed, cancelled, reversed] } Payout: type: object required: [id, object, livemode, amount, fee, currency, status, destination, reference, description, metadata, failure, release_at, created_at] properties: id: { type: string, pattern: "^po_[0-9a-f]{32}$" } object: { const: payout } livemode: { type: boolean } amount: { type: integer } fee: { type: integer, description: Swichi's fee, held with the amount. } currency: { $ref: "#/components/schemas/Currency" } status: { $ref: "#/components/schemas/PayoutStatus" } destination: type: object required: [type, hint, name] properties: type: { type: string, enum: [mobile_money, bank] } hint: { type: string, description: "Where it goes, masked: Airtel Money ••• 001." } name: { type: string } reference: { type: string } description: { type: string } metadata: { $ref: "#/components/schemas/Metadata" } failure: { $ref: "#/components/schemas/Failure" } release_at: { type: [string, "null"], format: date-time, description: When an in_cooldown payout goes. } created_at: { type: string, format: date-time } CreateTransfer: type: object additionalProperties: false required: [amount, currency, destination_account] properties: amount: { $ref: "#/components/schemas/Amount" } currency: { $ref: "#/components/schemas/Currency" } destination_account: { type: string, description: "The other business's Swichi account id (acct_…)." } reference: { type: string, maxLength: 100 } description: { type: string, maxLength: 200 } metadata: { $ref: "#/components/schemas/Metadata" } Transfer: type: object required: [id, object, livemode, amount, fee, currency, status, destination_account, reference, description, metadata, created_at] properties: id: { type: string, pattern: "^tr_[0-9a-f]{32}$" } object: { const: transfer } livemode: { type: boolean } amount: { type: integer } fee: { type: integer } currency: { $ref: "#/components/schemas/Currency" } status: { const: succeeded } destination_account: { type: string, pattern: "^acct_[0-9a-f]{32}$" } reference: { type: string } description: { type: string } metadata: { $ref: "#/components/schemas/Metadata" } created_at: { type: string, format: date-time } CreateCheckoutLink: type: object additionalProperties: false properties: amount: { $ref: "#/components/schemas/Amount" } min_amount: { $ref: "#/components/schemas/Amount" } max_amount: { $ref: "#/components/schemas/Amount" } description: { type: string, maxLength: 120 } order_reference: { type: string, maxLength: 60, description: Your order number (fixed amounts only). } expires_in_days: { type: integer, minimum: 1, maximum: 90, default: 7 } CheckoutLink: type: object required: [id, object, livemode, url, amount, min_amount, max_amount, currency, description, status, uses, order_number, expires_at, created_at] properties: id: { type: string, pattern: "^lnk_[0-9a-f]{32}$" } object: { const: checkout_link } livemode: { type: boolean } url: { type: [string, "null"], description: Only when the link is made. } amount: { type: [integer, "null"] } min_amount: { type: [integer, "null"] } max_amount: { type: [integer, "null"] } currency: { $ref: "#/components/schemas/Currency" } description: { type: string } status: { type: string, enum: [active, paid, expired, disabled] } uses: { type: integer } order_number: { type: [integer, "null"] } expires_at: { type: string, format: date-time } created_at: { type: string, format: date-time } Balance: type: object required: [object, livemode, account, wallets] properties: object: { const: balance } livemode: { type: boolean } account: { type: string, pattern: "^acct_[0-9a-f]{32}$", description: Your Swichi account id (for transfers to you). } wallets: type: array items: type: object required: [currency, available, held, incoming] properties: currency: { $ref: "#/components/schemas/Currency" } available: { type: integer, description: What you can pay out now. } held: { type: integer, description: Payouts on their way or waiting. } incoming: { type: integer, description: Money confirmed and on its way in. } limits: type: object description: Live only. How much may still come in today (midnight to midnight, East Africa time). required: [currency, collect_per_payment, collect_per_day, collected_today, remaining_today] properties: currency: { $ref: "#/components/schemas/Currency" } collect_per_payment: { type: integer } collect_per_day: { type: integer } collected_today: { type: integer } remaining_today: { type: integer } Refund: type: object required: [id, object, livemode, collection, amount, currency, status, created_at] properties: id: { type: string, pattern: "^re_[0-9a-f]{32}$" } object: { const: refund } livemode: { type: boolean } collection: { type: string, pattern: "^col_[0-9a-f]{32}$" } amount: { type: integer } currency: { $ref: "#/components/schemas/Currency" } status: { enum: [pending, succeeded, failed], description: "failed: nothing reached the payer; refund again." } payout: { type: string, pattern: "^po_[0-9a-f]{32}$", description: The payout that carries the money. } created_at: { type: string, format: date-time } Transaction: type: object required: [id, object, type, amount, currency, pending, balance_after, source, created_at] properties: id: { type: string, pattern: "^txn_[0-9]+$" } object: { const: transaction } type: { type: string, description: "collection, payout, payout_settle, payout_reversal, transfer, top_up or fee." } amount: { type: integer, description: Into your wallet positive, out negative. } currency: { $ref: "#/components/schemas/Currency" } pending: { type: boolean, description: A hold that is not final yet. } balance_after: { type: integer } source: type: [object, "null"] required: [object, id] properties: object: { type: string } id: { type: string } created_at: { type: string, format: date-time } Receipt: type: object required: [object, code, status, amount, currency, payer, business, paid_at, url] properties: object: { const: receipt } code: { type: string } status: { type: string, enum: [genuine, voided] } amount: { type: integer } currency: { $ref: "#/components/schemas/Currency" } payer: { type: string, description: The payer's first name and initial, when known. } business: { type: string } paid_at: { type: string, format: date-time } url: { type: string, format: uri } Bank: type: object required: [code, name, swift] properties: code: { type: string, description: Swichi's bank code; send it as bank_code. } name: { type: string } swift: { type: string, description: The bank's SWIFT code; empty when it has none. } Capability: type: object required: [id, parent, name, name_sw, state] properties: id: { type: string, description: "The feature, e.g. payout.wallet or bill.electricity." } parent: { type: string } name: { type: string } name_sw: { type: string, description: The name in Kiswahili. } state: { type: string, enum: [live, soon] } methods: { type: array, items: { type: string }, description: The networks it serves. } banks: { type: array, items: { type: string }, description: The bank codes it serves. } billers: { type: array, items: { type: string }, description: The billers it serves. } Simulate: type: object additionalProperties: false required: [outcome] properties: outcome: { type: string, enum: [succeeded, failed, expired, reversed] } failure_code: { type: string, enum: [payer_declined, payer_insufficient_funds, invalid_number, limit_exceeded, rejected] } ErrorCode: type: string description: Stable codes; each has a section at doc_url. enum: - authentication_required - invalid_api_key - invalid_request - amount_too_small - amount_too_large - not_found - idempotency_conflict - idempotency_in_progress - rate_limited - key_product_mismatch - missing_scope - ip_not_allowed - currency_not_supported - network_not_supported - method_not_available - insufficient_funds - limit_exceeded - key_limit_exceeded - payee_blocked - account_under_review - payouts_paused - account_not_ready - live_not_open - payout_not_cancellable - sandbox_only - destination_not_found - collection_not_paid - refund_exceeds_payment - internal_error ErrorResponse: type: object required: [error] properties: error: type: object required: [type, code, message, retryable, doc_url, request_id] properties: type: type: string enum: [invalid_request_error, authentication_error, permission_error, rate_limit_error, payment_error, api_error] code: { $ref: "#/components/schemas/ErrorCode" } message: { type: string, description: Plain words, with the fix. } retryable: { type: boolean, description: Whether the same request may succeed if sent again later. } param: { type: string, description: The request field at fault. } doc_url: { type: string, format: uri } request_id: { type: string, pattern: "^req_" } ```