Integration reference · API version 2026-08

MasnoPay Payments API

One HTTP API to collect mobile money across EVC Plus, eDahab and Telebirr. You create a payment, the customer approves it on their handset, and we tell you the outcome by signed webhook — with polling as the guaranteed fallback.

Basehttps://pay.masnopay.com AuthBearer sk_… + X-Merchant-Key Mediaapplication/json Errorsapplication/problem+json

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.

The one rule

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.succeeded event to your endpoint. This is the fast path.
  • Polling — you GET /v1/payments/{id} and read the status. This is the reliable path.
Design note

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.

HeaderValuePurpose
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 a liveMode: false event.
  • Webhook endpoints belong to one mode. Register separate endpoints for test and live; a simulated payment is never delivered to a live endpoint.
  • Idempotency-Key values are scoped per mode, so replaying your test suite's keys against live will not return stale test responses.
Secret handling

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.

  1. Create the payment

    Send the amount, currency and the customer's mobile number. Generate a fresh idempotency key per attempt.

    Requestcurl
    curl -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"
      }'
  2. Store the id, show a waiting state

    You get 202 with the payment resource. Persist id against 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
    }
  3. Handle the webhook

    Verify the signature, then act on payment.succeeded. Respond 2xx quickly and do slow work asynchronously — we retry anything that isn't a 2xx.

  4. Reconcile by polling

    For any payment still pending past its expiresAt, poll GET /v1/payments/{id}. This is what makes your integration correct when webhooks are delayed, lost, or your endpoint was down.

Create a payment


POST /v1/payments

Starts a collection. Returns 202 Accepted with the payment resource.

Body

FieldTypeNotes
amountstringrequired Decimal string, e.g. "250.00". Must be positive.
currencystringrequired One of USD, SLSH, SOS, ETB. Must be supported by the resolved provider.
accountNumberstringconditional Customer's mobile number. Required for USSD providers. Accepts E.164 (+252…) or local format; we normalize per provider.
providerstringoptional waafi, edahab, or telebirr. Omit to let the gateway route on number and currency.
descriptionstringoptional Human-readable label. May be shown to the customer.
referencestringoptional Your own order identifier. Returned on the resource and filterable in list queries.
returnUrlstringoptional Where to send the customer after a redirect checkout. Used by Telebirr.
metadataobjectoptional Arbitrary JSON echoed back on the resource and in webhooks. Never send card data or secrets.
Leaving out 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.

FieldTypeNotes
idstringGateway identifier, e.g. pay_3XKQ2M9RTVBN. Use this everywhere.
statusstringSee lifecycle. Always lowercase.
providerstringWhich network actually handled it.
amountstringTwo decimal places, as a string.
feeAmountstringOur fee for this payment, in the same currency. Computed per currency — never sum across currencies.
checkoutUrlstring · nullPresent only for redirect providers. Send the customer here.
providerTransactionIdstring · nullThe provider's own reference. Quote this in support tickets.
failureobject · null{ code, message } when the payment failed. See failure codes.
expiresAttimestampAfter this, an unconfirmed payment is expired.
confirmedAttimestamp · nullSet 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.

SituationResponseWhat 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.
Retention

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.

If a create call times out

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


GET /v1/payments/{id}

Returns the current payment resource. This is your reconciliation endpoint — it is always authoritative, and it is safe to poll.

GET /v1/payments

Lists your payments, newest first, with cursor pagination.

QueryTypeNotes
statusstringFilter to one status.
providerstringFilter to one provider.
referencestringFind payments by your own order reference.
starting_afterstringCursor: the last id from the previous page.
limitintegerDefault 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.

StatusTerminalMeaning
pendingNo Recorded and in flight. The customer has not yet approved, or we're still waiting on the provider. No money has moved.
succeededYes Money confirmed collected. confirmedAt is set. This is the only status you may fulfil an order on.
failedYes The provider returned a terminal failure. failure.code says why.
expiredMostly No answer before the deadline. Treat as not paid — but see the caveat below.
reversedYes A previously succeeded payment was reversed or refunded at the provider. If you already fulfilled, you now have a claw-back to handle.
Expired is not always final

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.

Payments held for review

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

TypeFires when
payment.succeededMoney confirmed collected.
payment.failedTerminal failure from the provider.
payment.expiredNo answer before the deadline.
payment.reversedA succeeded payment was reversed at the provider.

Subscribe to specific types, or to * for all of them.

Envelope

POST to your endpointjson
{
  "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

HeaderPurpose
MasnoPay-Signaturet=<unix>,v1=<hex> — verify this before anything else.
MasnoPay-Event-IdStable event id. Use it to deduplicate.
MasnoPay-Event-TypeSame as type in the body; lets you route without parsing.
MasnoPay-Delivery-IdUnique 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.

Build your handler to be

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:

Signature construction
MasnoPay-Signature: t=<unixSeconds>,v1=<hex>

v1 = HMAC_SHA256(endpointSecret, "{t}.{rawRequestBody}")   // lowercase hex
Use the raw body

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 ==.

Node · Expressjavascript
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);
  });
C# · ASP.NET Corecsharp
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.

Error shapeapplication/problem+json
{
  "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

CodeHTTPMeaning
validation_failed400Malformed or missing fields.
idempotency_key_missing400The required header was absent.
authentication_failed401Unknown, malformed, or revoked API key.
merchant_key_mismatch403X-Merchant-Key doesn't belong to this API key, or is the other mode's key.
merchant_suspended403The account can't transact. Contact support.
not_found404No such payment for this merchant.
idempotency_key_in_flight409Original still running. Retriable.
idempotency_key_reuse422Key reused with a different body.
invalid_account_number422Not a valid number for the provider.
unsupported_currency422Provider can't take that currency.
provider_not_configured422Provider isn't set up for your account.
provider_disabled422Configured but currently switched off.
provider_unroutable422Couldn't infer a provider. Send provider explicitly.
rate_limited429Slow down and retry after backoff.
provider_unavailable502Upstream 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.

CodeMeaningWorth retrying?
insufficient_fundsCustomer's wallet balance was too low.Yes, after they top up.
customer_rejectedThey actively declined the prompt.Only if they ask to try again.
no_pin_entry_timeoutThe prompt was never answered.Yes — commonly just a missed prompt.
invalid_accountThe number isn't valid on that network.No. Fix the number first.
provider_errorThe provider failed in a way we couldn't classify.Yes, with backoff.
expiredDeadline passed with no answer.Yes, as a new payment.
Retrying a failed 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


ValueNetworkFlowCurrencies
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.

PrefixNetworkRoutes to
25261Hormuudwaafi
25263ZAAD / Telesomwaafi
25262Somteledahab
25265Somteledahab
2519Ethio Telecomtelebirr
2517Ethio Telecomtelebirr

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.

Two flows, one API

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.

Currencies never mix

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/payments sends a unique Idempotency-Key, and network failures retry with the same key.
  • Nothing is fulfilled on a 202 — only on succeeded.
  • 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 pending payments, so you converge even with zero webhooks.
  • Fulfilment is idempotent, so a late succeeded after expired doesn't ship twice.
  • reversed has a defined handling path — it will eventually happen.
  • Amounts are parsed and stored as decimals, never floats.
  • correlationId is 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.