The payment model
Read this section before writing any code. Almost every integration bug comes from treating the create call as if it settles the payment.
Collecting mobile money is not a request/response operation. When you create a payment we push a USSD prompt to the customer's handset, and they have to physically enter their PIN. That can take seconds or minutes, and they may never respond at all.
POST /v1/payments returns 202 Accepted,
not 201 Created. A 202 means we have durably recorded your
payment and will attempt it — it does not mean money moved. The payment comes
back with status pending. Never ship goods, credit an account, or
show a success screen on the strength of a 202.
Money is only confirmed when the payment reaches succeeded, which you learn about in one of two ways:
- Webhook — we POST a signed
payment.succeededevent to your endpoint. This is the fast path. - Polling — you
GET /v1/payments/{id}and read the status. This is the reliable path.
Webhooks are an optimization, not the source of truth. Our reconciler polls each provider independently until every pending payment reaches a terminal state, so a payment resolves correctly even if your endpoint is down for hours. Build the webhook path for speed, but make sure your system still converges if no webhook ever arrives.
Amounts are strings
Every monetary value in this API — amount, feeAmount —
is a JSON string with exactly two decimal places, like "250.00".
This is deliberate: binary floats cannot represent decimal currency exactly, and a rounding
error in a payment gateway is a real financial loss. Parse them with a decimal type, never a
float or double.
Authentication
Every request to /v1/* needs two headers. Both are checked, and they must agree.
| Header | Value | Purpose |
|---|---|---|
Authorization |
Bearer sk_live_…Bearer sk_test_… |
Your secret API key. Identifies the merchant and selects live or test mode. |
X-Merchant-Key |
mk_live_…mk_test_… |
Your public merchant identifier, cross-checked against the key's owner and its mode. |
The cross-check exists to catch configuration mistakes — a staging key pointed at a
production merchant, or credentials pasted between environments. If the two disagree you
get 403 merchant_key_mismatch
rather than a payment charged against the wrong account.
The two headers must be the same mode. You have two merchant keys, one per mode, and
each pairs only with API keys of that mode: sk_live_… with
mk_live_…, and sk_test_… with
mk_test_…. Mixing them is also a
merchant_key_mismatch, and the error message says so explicitly
rather than leaving you to guess.
Test mode
A key beginning sk_test_ routes every payment to a built-in simulator
that never touches a real provider and never moves money. Use it to build your entire
integration, including webhook handling.
Test and live are fully separate:
- Payments are stored apart and never appear in each other's lists. Fetching a test payment by id with a live key returns 404, and vice versa.
-
Every payment object carries
liveMode, in API responses and in webhook payloads. Check it in your webhook handler and refuse to fulfil an order on aliveMode: falseevent. - Webhook endpoints belong to one mode. Register separate endpoints for test and live; a simulated payment is never delivered to a live endpoint.
-
Idempotency-Keyvalues are scoped per mode, so replaying your test suite's keys against live will not return stale test responses.
sk_ keys are bearer credentials — anyone holding one can move money
as you. Keep them server-side only. Never put one in a browser, a mobile app binary, a
Postman collection you share, or a git repository. Rotate immediately if exposed; you can
issue and revoke keys independently from the dashboard.
Quickstart
A complete, correct integration in four steps.
-
Create the payment
Send the amount, currency and the customer's mobile number. Generate a fresh idempotency key per attempt.
Requestcurlcurl -X POST https://pay.masnopay.com/v1/payments \ -H "Authorization: Bearer sk_test_YOUR_KEY" \ -H "X-Merchant-Key: mk_test_YOUR_MERCHANT_KEY" \ -H "Idempotency-Key: order-8842-attempt-1" \ -H "Content-Type: application/json" \ -d '{ "amount": "250.00", "currency": "USD", "accountNumber": "25265XXXXXXX", "description": "Order #8842", "reference": "8842" }'
-
Store the id, show a waiting state
You get 202 with the payment resource. Persist
idagainst your order, then tell the customer to check their phone and approve the prompt.202 Acceptedjson{ "id": "pay_3XKQ2M9RTVBN", "status": "pending", "liveMode": false, "provider": "edahab", "accountNumber": "25265XXXXXXX", "amount": "250.00", "currency": "USD", "feeAmount": "3.75", "description": "Order #8842", "reference": "8842", "checkoutUrl": null, "providerTransactionId": null, "failure": null, "metadata": null, "createdAt": "2026-08-15T12:04:11.230Z", "expiresAt": "2026-08-15T12:09:11.230Z", "confirmedAt": null } -
Handle the webhook
Verify the signature, then act on
payment.succeeded. Respond2xxquickly and do slow work asynchronously — we retry anything that isn't a 2xx. -
Reconcile by polling
For any payment still
pendingpast itsexpiresAt, pollGET /v1/payments/{id}. This is what makes your integration correct when webhooks are delayed, lost, or your endpoint was down.
Create a payment
Starts a collection. Returns 202 Accepted with the payment resource.
Body
| Field | Type | Notes | |
|---|---|---|---|
amount | string | required | Decimal string, e.g. "250.00". Must be positive. |
currency | string | required | One of USD, SLSH, SOS, ETB. Must be supported by the resolved provider. |
accountNumber | string | conditional | Customer's mobile number. Required for USSD providers. Accepts E.164 (+252…) or local format; we normalize per provider. |
provider | string | optional | waafi, edahab, or telebirr. Omit to let the gateway route on number and currency. |
description | string | optional | Human-readable label. May be shown to the customer. |
reference | string | optional | Your own order identifier. Returned on the resource and filterable in list queries. |
returnUrl | string | optional | Where to send the customer after a redirect checkout. Used by Telebirr. |
metadata | object | optional | Arbitrary JSON echoed back on the resource and in webhooks. Never send card data or secrets. |
provider
If you omit provider, the gateway picks one from the number prefix and
currency. That is convenient, but it means a number we can't classify fails with
provider_unroutable instead of being attempted. If you already know
which network the customer is on, send it explicitly and get a clearer error surface.
The payment resource
The same shape is returned by every payments endpoint and embedded in every webhook, so you only need one parser.
| Field | Type | Notes |
|---|---|---|
id | string | Gateway identifier, e.g. pay_3XKQ2M9RTVBN. Use this everywhere. |
status | string | See lifecycle. Always lowercase. |
provider | string | Which network actually handled it. |
amount | string | Two decimal places, as a string. |
feeAmount | string | Our fee for this payment, in the same currency. Computed per currency — never sum across currencies. |
checkoutUrl | string · null | Present only for redirect providers. Send the customer here. |
providerTransactionId | string · null | The provider's own reference. Quote this in support tickets. |
failure | object · null | { code, message } when the payment failed. See failure codes. |
expiresAt | timestamp | After this, an unconfirmed payment is expired. |
confirmedAt | timestamp · null | Set only when money was confirmed collected. |
Idempotency
Idempotency-Key is required on
POST /v1/payments. A request without one is rejected before anything happens.
Networks fail in the worst possible place: after we've charged the customer but before you
got the response. The only safe way to retry is to send the identical request with the
identical key, and let us recognise it. Generate one key per logical payment attempt
— a UUID, or something like order-8842-attempt-1 — and reuse it for
every retry of that same attempt. Maximum 256 characters.
| Situation | Response | What to do |
|---|---|---|
| Header missing or empty | 400 idempotency_key_missing |
Add the header. Nothing was created. |
| First time we've seen this key | 202 | Normal path. Store the returned id. |
| Replay, same body | 202 + Idempotency-Replayed: true |
The original response, verbatim. Safe — no second payment was created. |
| Same key, different body | 422 idempotency_key_reuse |
A bug on your side. Keys must not be recycled across different payments. |
| Original request still running | 409 idempotency_key_in_flight |
Retriable. Back off briefly and send the same request again. |
Idempotency records are kept for 24 hours. Retries inside that window are deduplicated; the same key sent later is treated as a brand-new payment. Keep your retry windows comfortably under a day.
Do not issue a fresh idempotency key. Retry with the same key — that is precisely what it is for. If you instead generate a new key you are asking for a second, genuinely separate payment, and the customer may be debited twice.
Retrieve & list
Returns the current payment resource. This is your reconciliation endpoint — it is always authoritative, and it is safe to poll.
Lists your payments, newest first, with cursor pagination.
| Query | Type | Notes |
|---|---|---|
status | string | Filter to one status. |
provider | string | Filter to one provider. |
reference | string | Find payments by your own order reference. |
starting_after | string | Cursor: the last id from the previous page. |
limit | integer | Default 25. |
The response is { "data": [ … ], "hasMore": true }. Keep requesting while hasMore is true, passing the last id as starting_after.
How often to poll
Poll an individual payment every few seconds while the customer is at the checkout, then
back off. Once expiresAt has passed, a sweep every few minutes is
plenty. Don't poll every payment in a tight loop — you'll hit the rate limit and gain nothing,
because our own reconciler is already chasing the provider on your behalf.
Payment lifecycle
Five states. Only these five ever appear in status, always lowercase.
| Status | Terminal | Meaning |
|---|---|---|
| pending | No | Recorded and in flight. The customer has not yet approved, or we're still waiting on the provider. No money has moved. |
| succeeded | Yes | Money confirmed collected. confirmedAt is set. This is the only status you may fulfil an order on. |
| failed | Yes | The provider returned a terminal failure. failure.code says why. |
| expired | Mostly | No answer before the deadline. Treat as not paid — but see the caveat below. |
| reversed | Yes | A previously succeeded payment was reversed or refunded at the provider. If you already fulfilled, you now have a claw-back to handle. |
Mobile-money networks sometimes confirm long after we've stopped waiting. A payment that
went expired can still be corrected to
succeeded if the provider later confirms it, and you will get a
payment.succeeded webhook at that point. Don't treat
expired as permanently immutable: make your fulfilment logic
idempotent so a late success is handled gracefully rather than double-shipping.
When an outcome is genuinely unknowable — a lost response on a provider that carries no
client reference, an unverifiable callback — we refuse to guess. Rather than retry (which
could double-charge) or declare failure (which could lose money), the payment is flagged
for manual review and stays pending until an operator resolves it
against the provider's records. Your integration needs no special handling; just don't
assume every payment resolves within seconds.
Webhooks
Register an HTTPS endpoint in the dashboard and we'll POST signed events as payments resolve.
Events
| Type | Fires when |
|---|---|
payment.succeeded | Money confirmed collected. |
payment.failed | Terminal failure from the provider. |
payment.expired | No answer before the deadline. |
payment.reversed | A succeeded payment was reversed at the provider. |
Subscribe to specific types, or to * for all of them.
Envelope
{
"id": "evt_7QW2M4KX9PDL",
"type": "payment.succeeded",
"apiVersion": "2026-08",
"createdAt": "2026-08-15T12:06:44.019Z",
"data": {
"payment": { /* the full payment resource, frozen at event time */ }
}
}
Headers
| Header | Purpose |
|---|---|
MasnoPay-Signature | t=<unix>,v1=<hex> — verify this before anything else. |
MasnoPay-Event-Id | Stable event id. Use it to deduplicate. |
MasnoPay-Event-Type | Same as type in the body; lets you route without parsing. |
MasnoPay-Delivery-Id | Unique per delivery attempt. Changes on every retry — do not deduplicate on this. |
Retries
Any response that isn't 2xx — or a timeout — is retried on a fixed
ladder: 0s → 30s → 2m → 10m → 1h → 6h → 24h.
After the last attempt the event goes to a dead-letter queue you can inspect and redeliver
from the dashboard. An endpoint that keeps failing trips a circuit breaker so one broken
consumer can't slow down everyone else's deliveries.
Idempotent — the same event can arrive more than once; dedupe on
MasnoPay-Event-Id.
Fast — acknowledge with 2xx immediately and queue slow work; we time out
slow endpoints and retry, which produces duplicates.
Order-independent — retries mean a later event can arrive before an
earlier one. Trust the payment's status, not arrival order.
Verifying signatures
Your webhook URL is public. Anyone can POST to it a fake payment.succeeded
and get free goods. Signature verification is what stops them, and it is not optional.
The scheme is:
MasnoPay-Signature: t=<unixSeconds>,v1=<hex> v1 = HMAC_SHA256(endpointSecret, "{t}.{rawRequestBody}") // lowercase hex
You must HMAC the exact bytes we sent. If your framework parses the JSON and
you re-serialize it, key order and whitespace change and the signature will never match.
In Express, that means express.raw() on the webhook route — not
express.json(). Compare with a constant-time function, never
==.
const crypto = require("crypto"); // raw body, not parsed JSON app.post("/webhooks/masnopay", express.raw({ type: "application/json" }), (req, res) => { const header = req.get("MasnoPay-Signature") || ""; const parts = new Map(header.split(",").map(p => p.split("="))); const t = parts.get("t"), v1 = parts.get("v1"); if (!t || !v1) return res.sendStatus(400); // reject anything older than five minutes if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.sendStatus(400); const expected = crypto .createHmac("sha256", process.env.MASNOPAY_WEBHOOK_SECRET) .update(`${t}.${req.body}`) // req.body is a Buffer here .digest("hex"); const a = Buffer.from(expected), b = Buffer.from(v1); if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.sendStatus(400); const event = JSON.parse(req.body); // ack first, then work — dedupe on event.id res.sendStatus(200); enqueue(event); });
static bool Verify(string header, string rawBody, string secret) { string? t = null, v1 = null; foreach (var part in header.Split(',')) { var kv = part.Split('=', 2); if (kv.Length == 2 && kv[0] == "t") t = kv[1]; if (kv.Length == 2 && kv[0] == "v1") v1 = kv[1]; } if (t is null || v1 is null || !long.TryParse(t, out var ts)) return false; if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > 300) return false; var expected = Convert.ToHexString(HMACSHA256.HashData( Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"{ts}.{rawBody}"))).ToLowerInvariant(); return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(v1.ToLowerInvariant())); }
The t timestamp exists so you can reject replays. Five minutes is a
sensible tolerance. Without that check, an attacker who captures one valid delivery can
replay it forever.
Errors
Errors are RFC 9457 problem documents with a machine-readable code.
Branch on code, never on the prose in detail.
{
"title": "Provider not configured",
"status": 422,
"detail": "Telebirr is not enabled for this merchant.",
"instance": "POST /v1/payments",
"code": "provider_not_configured",
"correlationId": "0HNNQOM3U8ER5:00000001"
}
Always log correlationId — it's what lets us find your exact request.
Request errors
| Code | HTTP | Meaning |
|---|---|---|
validation_failed | 400 | Malformed or missing fields. |
idempotency_key_missing | 400 | The required header was absent. |
authentication_failed | 401 | Unknown, malformed, or revoked API key. |
merchant_key_mismatch | 403 | X-Merchant-Key doesn't belong to this API key, or is the other mode's key. |
merchant_suspended | 403 | The account can't transact. Contact support. |
not_found | 404 | No such payment for this merchant. |
idempotency_key_in_flight | 409 | Original still running. Retriable. |
idempotency_key_reuse | 422 | Key reused with a different body. |
invalid_account_number | 422 | Not a valid number for the provider. |
unsupported_currency | 422 | Provider can't take that currency. |
provider_not_configured | 422 | Provider isn't set up for your account. |
provider_disabled | 422 | Configured but currently switched off. |
provider_unroutable | 422 | Couldn't infer a provider. Send provider explicitly. |
rate_limited | 429 | Slow down and retry after backoff. |
provider_unavailable | 502 | Upstream network problem. Retry with the same idempotency key. |
Failure codes
These appear in failure.code on a failed payment and in payment.failed webhooks. Every provider's vocabulary is normalized onto this set.
| Code | Meaning | Worth retrying? |
|---|---|---|
insufficient_funds | Customer's wallet balance was too low. | Yes, after they top up. |
customer_rejected | They actively declined the prompt. | Only if they ask to try again. |
no_pin_entry_timeout | The prompt was never answered. | Yes — commonly just a missed prompt. |
invalid_account | The number isn't valid on that network. | No. Fix the number first. |
provider_error | The provider failed in a way we couldn't classify. | Yes, with backoff. |
expired | Deadline passed with no answer. | Yes, as a new payment. |
A retry is a new payment with a new idempotency key — never a reuse of the
old one, which would just replay the stored failure. Only retry after a terminal status;
retrying while pending risks charging the customer twice.
Providers & currencies
| Value | Network | Flow | Currencies |
|---|---|---|---|
waafi |
EVC Plus / ZAAD / SAHAL (Hormuud) | USSD push, PIN on handset | USD, SOS |
edahab |
eDahab (Somtel) | USSD push, PIN on handset | USD, SLSH |
telebirr |
Telebirr (Ethio Telecom) | Redirect — send the customer to checkoutUrl |
ETB |
Routing prefixes
When you omit provider, the number's prefix decides. Longest match wins.
The test number 25265XXXXXXX starts 25265, so it
routes to eDahab.
| Prefix | Network | Routes to |
|---|---|---|
25261 | Hormuud | waafi |
25263 | ZAAD / Telesom | waafi |
25262 | Somtel | edahab |
25265 | Somtel | edahab |
2519 | Ethio Telecom | telebirr |
2517 | Ethio Telecom | telebirr |
A number outside every prefix fails with provider_unroutable rather than
being guessed at. This map is server-side configuration, so it can be updated as numbering
plans change without a client release.
USSD providers need accountNumber and return
checkoutUrl: null — the customer approves on their handset and you
wait. Telebirr returns a checkoutUrl you must redirect the customer
to, with returnUrl deciding where they land afterwards. Handle both
by checking whether checkoutUrl is present, rather than branching on
the provider name.
Amounts in different currencies are never summed — not in analytics, not in fees, nowhere. There is no built-in FX conversion. If you sell in one currency and collect in another, that conversion is yours to do and yours to record.
Rate limits
Limits are applied per merchant as a token bucket: a sustained rate with a burst allowance on
top. Defaults are 25 requests/second sustained with a
burst of 50. Exceeding it returns
429 rate_limited.
Back off exponentially with jitter. If you're hitting the limit through polling, poll less
aggressively and lean on webhooks — or batch with
GET /v1/payments?status=pending instead of fetching each payment
individually.
Going live
Work through this before switching from sk_test_ to sk_live_.
- Every
POST /v1/paymentssends a uniqueIdempotency-Key, and network failures retry with the same key. - Nothing is fulfilled on a
202— only onsucceeded. - Webhook signatures are verified against the raw body, with a constant-time compare and a timestamp tolerance.
- The webhook handler is idempotent and dedupes on
MasnoPay-Event-Id. - A reconciliation job sweeps stale
pendingpayments, so you converge even with zero webhooks. - Fulfilment is idempotent, so a late
succeededafterexpireddoesn't ship twice. reversedhas a defined handling path — it will eventually happen.- Amounts are parsed and stored as decimals, never floats.
correlationIdis logged on every error response.- Live keys exist only in server-side secret storage, and a rotation procedure is written down.
- Provider credentials are configured and connection-tested from the dashboard for every provider you intend to use.