MTN MoMo Collections: Request to Pay with the MoMo Open API
Collect MTN Mobile Money payments with the MoMo Open API: subscription key, sandbox API user and key, access token, requesttopay, status checks, callbacks and refunds.
- Provider
- MTN MoMo (MoMo Open API)
- Level
- Intermediate
- Stacks
- Node.js (Express), Python (FastAPI), Java (Spring)
- Code maturity
- Sandbox-ready
- Last verified
- 25 Nov 2026
Introduction
MTN Mobile Money (MoMo) is one of Africa's largest mobile-money services. The MoMo Open API lets your app ask a customer to pay from their MoMo wallet: you send a Request to Pay, the customer approves it on their phone (USSD prompt or MoMo app), and you learn the result by callback or by asking for the status.
This guide uses the Collection product. You will provision a sandbox API user and key, get an access token, create a request to pay, receive the callback, confirm the status with a GET request, and keep your orders consistent. Examples are in Node.js (Express), Python (FastAPI) and Java (Spring Boot).
What Request to Pay does
- Your backend calls
POST /collection/v1_0/requesttopaywith a uniqueX-Reference-Id(a UUID v4 you generate), the amount and the payer's phone number. - MoMo answers
202 Accepted— the request is only queued. Its status isPENDING. - The customer approves or rejects the payment on their own phone.
- The status becomes
SUCCESSFULorFAILED. If you sent anX-Callback-Url, MoMo calls it once. You can always ask withGET /collection/v1_0/requesttopay/{referenceId}.
The official docs describe POST as asynchronous: "The created resource will get status PENDING. Once the request has been processed the status will be updated to SUCCESSFUL or FAILED."
Countries and currencies
Production access is per MTN country ("opco"). The error-code page lists these X-Target-Environment values: mtnuganda, mtnghana, mtnivorycoast, mtnzambia, mtncameroon, mtnbenin, mtncongo, mtnswaziland, mtnguineaconakry, mtnsouthafrica, mtnliberia, mtnsouthsudan, mtnnigeria, mtnrwanda — and sandbox for testing.
Use the local currency of the target country (for example UGX in Uganda, GHS in Ghana). The sandbox only accepts EUR. Which products are live in which country, and onboarding requirements, are decided by each MTN opco.
Warning: Having an environment name in the list does not mean Collection is commercially available to your business type in that country. Confirm with the MTN MoMo team of the country before you build.
Payment methods and products
- Collection → Request to Pay — pull a payment from a customer's MoMo wallet after they approve it. Covered here.
- Collection → Pre-Approval, Invoice, Payments (v2) — other collection flows listed in the API reference. Not covered.
- Disbursement — pay out to wallets (
transfer,deposit) and refund a collection (refund). Refunds are covered briefly. - Remittance — cross-border inbound transfers. Not covered.
Each product (Collection, Disbursement, Remittance) has its own subscription key.
When to use MoMo Collections
- Your customers are in an MTN MoMo market (for example Uganda, Ghana, Rwanda, Zambia, Cameroon, Côte d'Ivoire, Benin).
- You want customers to pay from their wallet with a phone prompt, without cards.
- You can operate a backend with a public HTTPS domain for callbacks, and can poll status as a fallback.
- You are ready to go through MTN's go-live (KYC/business onboarding) in each country you serve.
When not to use it
- You need one integration for many operators and countries (MTN, Airtel, Orange, M-Pesa…). A payment aggregator may save you separate go-lives per opco.
- You need cards or bank transfers — MoMo Open API covers wallets only.
- You cannot host a backend: every call needs secrets that must never live in a browser or mobile app.
- Kenya: MTN does not operate mobile money there; use M-Pesa or Airtel Money instead.
Real-world scenarios
- Online shop in Uganda: the customer types their MTN number at checkout; your page says "approve the payment on your phone" while your server waits for the result.
- Utility or school fees in Ghana: use the bill or student number as
externalIdso the payment is easy to reconcile. - Subscription top-up in a mobile app: the app calls your backend; your backend calls MoMo and tells the app when the order is paid.
Registration and onboarding
From the official Getting Started page:
- Sign up on momodeveloper.mtn.com. The activation link expires in 24 hours.
- Subscribe to products (Collection Widget, Collection, Remittances, Disbursements). Each subscription gives a Primary Key and Secondary Key — either works as your subscription key.
- Provision a sandbox API user and API key with the Sandbox Provisioning API (next sections).
- For production, complete MTN's go-live for the country. After go-live you get access to the partner/accounts portal (the error-code page points to
https://momoapi.mtn.com/profilefor production subscription keys), where API users and keys are created and your callback host is registered.
Warning: Production onboarding documents, fees and timelines differ per country and are not published on the developer portal. Ask the MTN MoMo team in your target country.
Sandbox environment and test numbers
- Sandbox base URL:
https://sandbox.momodeveloper.mtn.com X-Target-Environment:sandbox- Currency:
EUR(the official page: "The currency used in Sandbox is EUR")
The Sandbox Use Cases page publishes predefined payer numbers that force specific outcomes for Request to Pay. Any other number results in success. A selection:
46733123450→ payer failed46733123451→ payer rejected46733123452→ expired46733123453→ ongoing (stays pending)46733123454→ delayed46733123455→ payer not found46733123460→ invalid currency46733123461→ internal processing error;46733123462→ service unavailable
The sandbox needs an API user and key created through the provisioning API; existing partner-portal accounts cannot be used for sandbox use cases.
Credentials you need
The MoMo API uses two layers of credentials:
- Subscription key — sent on every request as the header
Ocp-Apim-Subscription-Key. One per product (Collection, Disbursement…). - API user + API key — the API user is a UUID; together they are sent with HTTP Basic auth to
POST /collection/token/to get an OAuth 2.0 bearer token. In sandbox you create them yourself with the provisioning API; in production they are created in the partner portal.
The access token must also be treated as a secret — the docs warn that "the party that have access to the token will be authenticated as the user that requested the token."
Security: An API key cannot be read back after creation — the docs say you must generate a new one if you lose it. Store it in a secrets manager or your server's environment, never in client code or git.
Environment configuration
Keep everything in environment variables. MOMO_CALLBACK_HOST must be the domain you registered as providerCallbackHost (sandbox) or in the portal (production) — the callback URL's host has to match it exactly, and it must be a hostname, not an IP address. MOMO_CALLBACK_TOKEN is a random value you add to the callback path because MoMo callbacks are not signed.
# MTN MoMo Open API — Collection product
MOMO_BASE_URL=https://sandbox.momodeveloper.mtn.com
MOMO_TARGET_ENV=sandbox # production: e.g. mtnuganda, mtnghana ...
MOMO_CURRENCY=EUR # sandbox only accepts EUR; production: local currency
MOMO_COLLECTION_SUBSCRIPTION_KEY=replace-with-primary-key-from-profile
MOMO_API_USER=replace-with-api-user-uuid
MOMO_API_KEY=replace-with-api-key
# Must equal the providerCallbackHost registered for the API user (hostname, https only)
MOMO_CALLBACK_HOST=payments.example.com
# Long random value, e.g. from: openssl rand -hex 24
MOMO_CALLBACK_TOKEN=replace-with-random-hex
PORT=3000Authentication: sandbox provisioning and access tokens
Sandbox only — create an API user and key (from the API User & Key management page):
POST /v1_0/apiuserwith headersX-Reference-Id: <new UUID v4>andOcp-Apim-Subscription-Key, body{ "providerCallbackHost": "your.domain" }→201 Created. The UUID is your API user id.POST /v1_0/apiuser/{apiUser}/apikeywith the subscription key →201with{ "apiKey": "..." }.GET /v1_0/apiuser/{apiUser}showsproviderCallbackHostandtargetEnvironment.
Every environment — get a token: POST /collection/token/ with Authorization: Basic base64(apiUser:apiKey) and the subscription key, no body. The response is { access_token, token_type, expires_in }. Reuse the token until it expires; request a new one slightly before expiry.
// Run once: node provision-sandbox.mjs (needs MOMO_COLLECTION_SUBSCRIPTION_KEY and MOMO_CALLBACK_HOST)
import crypto from "node:crypto";
const BASE = "https://sandbox.momodeveloper.mtn.com";
const key = process.env.MOMO_COLLECTION_SUBSCRIPTION_KEY;
const apiUser = crypto.randomUUID();
const created = await fetch(BASE + "/v1_0/apiuser", {
method: "POST",
headers: {
"X-Reference-Id": apiUser,
"Ocp-Apim-Subscription-Key": key,
"Content-Type": "application/json",
},
body: JSON.stringify({ providerCallbackHost: process.env.MOMO_CALLBACK_HOST }),
});
if (created.status !== 201) throw new Error("apiuser failed: " + created.status + " " + (await created.text()));
const keyRes = await fetch(BASE + "/v1_0/apiuser/" + apiUser + "/apikey", {
method: "POST",
headers: { "Ocp-Apim-Subscription-Key": key },
});
if (keyRes.status !== 201) throw new Error("apikey failed: " + keyRes.status);
const { apiKey } = await keyRes.json();
// Print once and store in your secrets manager / .env. The key cannot be fetched again later.
console.log("MOMO_API_USER=" + apiUser);
console.log("MOMO_API_KEY=" + apiKey);// momo.mjs — shared helpers for the Collection product.
const BASE = process.env.MOMO_BASE_URL || "https://sandbox.momodeveloper.mtn.com";
let cache = { token: null, expiresAt: 0 };
function baseHeaders() {
return { "Ocp-Apim-Subscription-Key": process.env.MOMO_COLLECTION_SUBSCRIPTION_KEY };
}
export async function getToken() {
if (cache.token && Date.now() < cache.expiresAt) return cache.token;
const basic = Buffer.from(process.env.MOMO_API_USER + ":" + process.env.MOMO_API_KEY).toString("base64");
const res = await fetch(BASE + "/collection/token/", {
method: "POST", // no body: the docs list a body on /token as a cause of 400
headers: { ...baseHeaders(), Authorization: "Basic " + basic },
});
if (!res.ok) throw new Error("MoMo token failed: HTTP " + res.status);
const body = await res.json();
cache = { token: body.access_token, expiresAt: Date.now() + (Number(body.expires_in) - 60) * 1000 };
return cache.token;
}
export async function momo(method, path, { body, headers = {} } = {}) {
const res = await fetch(BASE + path, {
method,
headers: {
...baseHeaders(),
Authorization: "Bearer " + (await getToken()),
"X-Target-Environment": process.env.MOMO_TARGET_ENV || "sandbox",
...(body ? { "Content-Type": "application/json" } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
return { status: res.status, data: text ? JSON.parse(text) : null };
}Warning: Each product has its own token endpoint (/collection/token/, /disbursement/token/ ...) and its own subscription key. A Collection token or key will not work for Disbursement calls.
Backend: request to pay, callback, idempotent update
The backend:
- generates a new UUID v4 per payment attempt and stores it on the order before calling MoMo (a retry with the same id returns
409 RESOURCE_ALREADY_EXIST, which protects you from double-charging); - takes the amount from your order record;
- exposes a callback route that accepts PUT and POST (the docs say to allow both), but does not trust the callback body — it re-reads the status with GET and updates the order only if it is still
PENDING.
The example uses an in-memory Map. In production use a database with a unique index on the reference id and a conditional update (status = 'PENDING').
import "dotenv/config";
import express from "express";
import crypto from "node:crypto";
import { momo } from "./momo.mjs";
const app = express();
app.use(express.json({ limit: "50kb" }));
// Demo store; use a DB with unique(referenceId) in real apps.
const orders = new Map([["order-2001", { id: "order-2001", amount: "5", status: "PENDING" }]]);
app.post("/api/orders/:id/pay", async (req, res) => {
const order = orders.get(req.params.id);
if (!order || order.status !== "PENDING") return res.status(404).json({ error: "Order not payable" });
const msisdn = String(req.body.msisdn || "").replace(/\D/g, "");
if (msisdn.length < 9 || msisdn.length > 15) return res.status(400).json({ error: "Invalid phone number" });
order.referenceId = crypto.randomUUID(); // save BEFORE calling MoMo
const { status, data } = await momo("POST", "/collection/v1_0/requesttopay", {
headers: {
"X-Reference-Id": order.referenceId,
"X-Callback-Url": "https://" + process.env.MOMO_CALLBACK_HOST + "/momo/callback/" + process.env.MOMO_CALLBACK_TOKEN,
},
body: {
amount: order.amount, // string, from YOUR order
currency: process.env.MOMO_CURRENCY || "EUR",
externalId: order.id,
payer: { partyIdType: "MSISDN", partyId: msisdn },
payerMessage: "Payment for " + order.id, // keep under 160 chars, no apostrophes
payeeNote: "Order " + order.id,
},
});
if (status !== 202) return res.status(502).json({ error: data?.message || "MoMo rejected the request" });
res.json({ status: "PENDING", message: "Approve the payment on your phone." });
});
export async function settle(referenceId) {
const order = [...orders.values()].find((o) => o.referenceId === referenceId);
if (!order || order.status !== "PENDING") return; // unknown or already final
const { status, data } = await momo("GET", "/collection/v1_0/requesttopay/" + referenceId);
if (status !== 200 || data.status === "PENDING") return;
if (data.status === "SUCCESSFUL" && String(data.amount) === order.amount) {
order.status = "PAID";
order.financialTransactionId = data.financialTransactionId;
} else {
order.status = data.status === "SUCCESSFUL" ? "REVIEW" : "FAILED";
order.reason = data.reason?.code || null;
}
}
function callback(req, res) {
const expected = Buffer.from(process.env.MOMO_CALLBACK_TOKEN || "");
const given = Buffer.from(req.params.token || "");
if (!expected.length || expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
return res.sendStatus(404);
}
res.sendStatus(200); // acknowledge, then confirm via GET (callbacks are unsigned)
// The payload mirrors the status response, which carries your externalId (= order id).
const order = orders.get(String(req.body?.externalId || ""));
if (order?.referenceId) settle(order.referenceId).catch((e) => console.error("settle failed", e.message));
}
app.put("/momo/callback/:token", callback);
app.post("/momo/callback/:token", callback);
app.get("/api/orders/:id", (req, res) => {
const o = orders.get(req.params.id);
if (!o) return res.sendStatus(404);
res.json({ id: o.id, status: o.status });
});
app.listen(process.env.PORT || 3000);import hmac, os, time, uuid
import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
E = os.environ
BASE = E.get("MOMO_BASE_URL", "https://sandbox.momodeveloper.mtn.com")
app = FastAPI()
orders = {"order-2001": {"id": "order-2001", "amount": "5", "status": "PENDING"}} # use a DB
_tok = {"value": None, "exp": 0.0}
async def token() -> str:
if _tok["value"] and time.time() < _tok["exp"]:
return _tok["value"]
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(f"{BASE}/collection/token/", auth=(E["MOMO_API_USER"], E["MOMO_API_KEY"]),
headers={"Ocp-Apim-Subscription-Key": E["MOMO_COLLECTION_SUBSCRIPTION_KEY"]})
r.raise_for_status()
body = r.json()
_tok.update(value=body["access_token"], exp=time.time() + int(body["expires_in"]) - 60)
return _tok["value"]
async def headers(extra=None) -> dict:
h = {"Authorization": f"Bearer {await token()}",
"Ocp-Apim-Subscription-Key": E["MOMO_COLLECTION_SUBSCRIPTION_KEY"],
"X-Target-Environment": E.get("MOMO_TARGET_ENV", "sandbox")}
return {**h, **(extra or {})}
@app.post("/api/orders/{order_id}/pay")
async def pay(order_id: str, payload: dict):
order = orders.get(order_id)
if not order or order["status"] != "PENDING":
raise HTTPException(404, "Order not payable")
msisdn = "".join(ch for ch in str(payload.get("msisdn", "")) if ch.isdigit())
if not 9 <= len(msisdn) <= 15:
raise HTTPException(400, "Invalid phone number")
order["reference_id"] = str(uuid.uuid4()) # persist before calling MoMo
cb = f"https://{E['MOMO_CALLBACK_HOST']}/momo/callback/{E['MOMO_CALLBACK_TOKEN']}"
body = {"amount": order["amount"], "currency": E.get("MOMO_CURRENCY", "EUR"), "externalId": order_id,
"payer": {"partyIdType": "MSISDN", "partyId": msisdn},
"payerMessage": f"Payment for {order_id}", "payeeNote": f"Order {order_id}"}
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(f"{BASE}/collection/v1_0/requesttopay", json=body,
headers=await headers({"X-Reference-Id": order["reference_id"], "X-Callback-Url": cb}))
if r.status_code != 202:
raise HTTPException(502, "MoMo rejected the request")
return {"status": "PENDING"}
async def settle(reference_id: str):
order = next((o for o in orders.values() if o.get("reference_id") == reference_id), None)
if not order or order["status"] != "PENDING":
return
async with httpx.AsyncClient(timeout=30) as c:
r = await c.get(f"{BASE}/collection/v1_0/requesttopay/{reference_id}", headers=await headers())
if r.status_code != 200:
return
data = r.json()
if data["status"] == "SUCCESSFUL":
order["status"] = "PAID" if str(data["amount"]) == order["amount"] else "REVIEW"
elif data["status"] == "FAILED":
order["status"] = "FAILED"
@app.api_route("/momo/callback/{tok}", methods=["PUT", "POST"])
async def callback(tok: str, request: Request, tasks: BackgroundTasks):
if not hmac.compare_digest(tok, E.get("MOMO_CALLBACK_TOKEN", "")):
raise HTTPException(404)
data = await request.json()
order = orders.get(str(data.get("externalId")))
if order and order.get("reference_id"):
tasks.add_task(settle, order["reference_id"]) # re-check with GET; never trust the body
return {"ok": True}Security: Never let the browser send the amount or decide success. The amount comes from your order; success comes only from MoMo's GET status read by your server.
Frontend
There is no MoMo browser SDK to embed for this flow: your page (or mobile app) collects the customer's MTN number, calls your /api/orders/:id/pay, tells the customer to approve the prompt on their phone (USSD or MoMo app), and polls your /api/orders/:id until it shows PAID or FAILED. The polling pattern is the same as in the M-Pesa STK Push guide's React component.
Show a clear timeout message (for example after two minutes) and keep the order pending on the server — a late approval will still be picked up by your reconciliation job.
Security: Never put the subscription key, API user, API key or access token in frontend code. All MoMo calls happen on your server.
Initiating a request to pay (request reference)
POST {base}/collection/v1_0/requesttopay
Headers (from the API definition): Authorization: Bearer <token>, X-Reference-Id (required, UUID v4), X-Target-Environment (required), X-Callback-Url (optional), Ocp-Apim-Subscription-Key, Content-Type: application/json.
Body fields:
amount— string, in the currency's normal units (for example"1000"UGX).currency— ISO code;EURin sandbox, the country's currency in production.externalId— your reference (order id), returned in status responses.payer—{ "partyIdType": "MSISDN", "partyId": "256..." }(international format, digits only).payerMessage/payeeNote— short texts; the error-code page warns that more than 160 characters or special characters such as an apostrophe cause400.
Response: 202 Accepted with an empty body. A reused X-Reference-Id gives 409 with code RESOURCE_ALREADY_EXIST.
package com.example.momo;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
public class MomoClient {
private final RestClient http;
private final String apiUser, apiKey, targetEnv, currency;
private String token;
private Instant tokenExpiry = Instant.EPOCH;
public MomoClient(@Value("${MOMO_BASE_URL}") String baseUrl,
@Value("${MOMO_COLLECTION_SUBSCRIPTION_KEY}") String subKey,
@Value("${MOMO_API_USER}") String apiUser, @Value("${MOMO_API_KEY}") String apiKey,
@Value("${MOMO_TARGET_ENV:sandbox}") String targetEnv,
@Value("${MOMO_CURRENCY:EUR}") String currency) {
this.http = RestClient.builder().baseUrl(baseUrl)
.defaultHeader("Ocp-Apim-Subscription-Key", subKey).build();
this.apiUser = apiUser; this.apiKey = apiKey; this.targetEnv = targetEnv; this.currency = currency;
}
private synchronized String token() {
if (token != null && Instant.now().isBefore(tokenExpiry)) return token;
Map<?, ?> body = http.post().uri("/collection/token/")
.headers(h -> h.setBasicAuth(apiUser, apiKey))
.retrieve().body(Map.class);
token = (String) body.get("access_token");
long ttl = ((Number) body.get("expires_in")).longValue();
tokenExpiry = Instant.now().plusSeconds(Math.max(30, ttl - 60));
return token;
}
/** Sends a request to pay and returns the reference id (store it on the order first in real code). */
public UUID requestToPay(UUID referenceId, String amount, String msisdn, String orderId, String callbackUrl) {
http.post().uri("/collection/v1_0/requesttopay")
.header("Authorization", "Bearer " + token())
.header("X-Reference-Id", referenceId.toString())
.header("X-Target-Environment", targetEnv)
.header("X-Callback-Url", callbackUrl)
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("amount", amount, "currency", currency, "externalId", orderId,
"payer", Map.of("partyIdType", "MSISDN", "partyId", msisdn),
"payerMessage", "Payment for " + orderId, "payeeNote", "Order " + orderId))
.retrieve().toBodilessEntity(); // 202 Accepted; 4xx/5xx throw RestClientResponseException
return referenceId;
}
public Map<?, ?> status(UUID referenceId) {
return http.get().uri("/collection/v1_0/requesttopay/{id}", referenceId)
.header("Authorization", "Bearer " + token())
.header("X-Target-Environment", targetEnv)
.retrieve().body(Map.class);
}
}Confirming the payment
A payment is confirmed when your server reads GET /collection/v1_0/requesttopay/{referenceId} and gets "status": "SUCCESSFUL". The response (RequestToPayResult) contains amount, currency, financialTransactionId (MoMo's transaction id — store it), externalId, payer, payerMessage, payeeNote, status (PENDING, SUCCESSFUL, FAILED) and, on failure, reason { code, message }.
Note from the API definition: "a failed request to pay will be returned with this status too" — HTTP 200 does not mean paid; read status.
Before fulfilling, check: the order is still pending, the reference id is yours, the amount and currency match the order.
{
"successful": {
"amount": 100, "currency": "UGX", "financialTransactionId": 23503452, "externalId": 947354,
"payer": { "partyIdType": "MSISDN", "partyId": 4656473839 },
"status": "SUCCESSFUL"
},
"payerNotFound": {
"amount": 100, "currency": "UGX", "externalId": 947354,
"payer": { "partyIdType": "MSISDN", "partyId": 4656473839 },
"status": "FAILED",
"reason": { "code": "PAYER_NOT_FOUND", "message": "Payee does not exist" }
}
}Callbacks
What the official Callback page says:
- Register your callback host (
providerCallbackHost) when creating the API user (sandbox) or API keys (production). Send the full URL per request inX-Callback-Url; its host must match, otherwise you getINVALID_CALLBACK_URL_HOST. - Only HTTPS is allowed, in sandbox and production. Your certificate chain must come from one of the intermediate CAs MTN lists as approved, or callbacks "might not work".
- Allow PUT and POST on your callback listener.
- The callback payload is "similar to the response returned by the status check API".
- The callback is sent only once. There is no retry. MTN "strongly recommend[s]" polling the status with GET as a fallback.
MoMo callbacks carry no signature header documented on these pages. So treat a callback only as a hint: protect the route with a secret path token, then re-read the status with GET before changing the order (the examples do exactly this).
package com.example.momo;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class MomoCallbackController {
private final OrderService orders; // your service: findByExternalId, markPaidIfPending, markFailedIfPending
private final MomoClient momo;
private final byte[] secret;
public MomoCallbackController(OrderService orders, MomoClient momo,
@Value("${MOMO_CALLBACK_TOKEN}") String token) {
this.orders = orders; this.momo = momo; this.secret = token.getBytes(StandardCharsets.UTF_8);
}
@RequestMapping(value = "/momo/callback/{token}", method = {RequestMethod.PUT, RequestMethod.POST})
public ResponseEntity<Void> callback(@PathVariable String token, @RequestBody Map<String, Object> body) {
if (!MessageDigest.isEqual(secret, token.getBytes(StandardCharsets.UTF_8))) {
return ResponseEntity.notFound().build();
}
var order = orders.findByExternalId(String.valueOf(body.get("externalId")));
if (order != null && order.isPending()) {
Map<?, ?> s = momo.status(order.getReferenceId()); // never trust the callback body
String status = String.valueOf(s.get("status"));
if ("SUCCESSFUL".equals(status) && order.getAmount().equals(String.valueOf(s.get("amount")))) {
// Implement as: UPDATE orders SET status='PAID', momo_txn=? WHERE id=? AND status='PENDING'
orders.markPaidIfPending(order.getId(), String.valueOf(s.get("financialTransactionId")));
} else if ("FAILED".equals(status)) {
orders.markFailedIfPending(order.getId());
}
}
return ResponseEntity.ok().build();
}
}Warning: Because there is no retry, a single deploy or outage can lose callbacks. A scheduled job that GETs the status of every PENDING order is required, not optional.
Status checks and reconciliation
GET /collection/v1_0/requesttopay/{referenceId} with Authorization, X-Target-Environment and the subscription key. Use it:
- when a callback arrives (to confirm it),
- from a scheduled job for orders still
PENDINGafter a minute or two, with back-off, - when the customer reloads the order page.
A 404 RESOURCE_NOT_FOUND usually means the original POST never returned 202 — check your logs for the initiation response. Stop polling after a sensible window (the payer may let the request expire) and mark the order expired on your side.
Related optional calls in the Collection API: GET /collection/v1_0/accountholder/{accountHolderIdType}/{accountHolderId}/active (validate that a number is an active MoMo account) and POST /collection/v1_0/requesttopay/{referenceId}/deliverynotification (send the payer a notification).
Refunds
Refunds are part of the Disbursement product, not Collection: POST /disbursement/v1_0/refund (or /v2_0/refund) with headers Authorization (a Disbursement token from /disbursement/token/), X-Reference-Id (new UUID), X-Target-Environment, optional X-Callback-Url, and the Disbursement subscription key.
Body (from the API definition): amount, currency, externalId, payerMessage, payeeNote, and referenceIdToRefund — the X-Reference-Id of the original request to pay. Check the result with GET /disbursement/v1_0/refund/{referenceId}.
The sandbox publishes refund test values too (for example referenceIdToRefund values 1–10 map to outcomes such as not found, failed, rejected, expired).
Warning: Refunds draw from your disbursement account balance and need a separate Disbursement subscription and production approval. The v1 vs v2 differences were not documented in prose on the pages we checked; treat this as simplified guidance.
Errors
From the official Common Error Codes page:
409 RESOURCE_ALREADY_EXIST— duplicatedX-Reference-Id. Use a fresh UUID v4 per attempt.401*Access denied due to invalid subscription key* — wrong key or the key of another product. Try the secondary key.404 RESOURCE_NOT_FOUND— reference id unknown on a GET.400bad request — wrong headers, non-UUID-v4 reference id, a body on/token, special characters such as', currency not matching the environment, more than 160 characters in note/message, malformed URL (for example///).403— IP not authorised (Disbursement in production requires whitelisting your public IP).500 NOT_ALLOWED,NOT_ALLOWED_TARGET_ENVIRONMENT,INVALID_CALLBACK_URL_HOST,INVALID_CURRENCY;503 SERVICE_UNAVAILABLE.INTERNAL_PROCESSING_ERROR— generic; the docs say it "predominantly occurs due to insufficient customer funds".
Failed payments come back as status: "FAILED" with reason.code, for example PAYER_NOT_FOUND.
Going to production
- Complete go-live with MTN for each country. Use the production subscription key, API user and API key from the partner portal.
- Production gateway host: our probe on 2026-11-25 shows
https://proxy.momoapi.mtn.comanswering as the MoMo API gateway. Confirm the base URL in your go-live pack. - Set
X-Target-Environmentto the country value (for examplemtnuganda) and the currency to the local currency. - Register your production callback host in the portal; serve it over HTTPS with a certificate from an approved CA.
- Run the status-polling job, alerting on stuck
PENDINGorders and on401/500spikes. - For Disbursement/refunds, share your server's public IP with your MTN account manager.
Tip: The production base URL is not stated on the public documentation pages we checked; it was confirmed only by probing the gateway. Treat it as needing confirmation from MTN.
Security checklist
- Subscription key, API user, API key and tokens live only on the server (environment or secrets manager).
- Generate the reference UUID on the server and store it before the call; unique index on it.
- Amount, currency and order id come from your database.
- Callback route: secret path token, constant-time comparison, body size limit; then verify by GET before changing state.
- Idempotent transitions (
PENDING→PAID/FAILEDonly once). - Mask phone numbers in logs; never log tokens or keys.
- Rate-limit payment initiation per user and per phone number to prevent prompt spam.
Security: A redirect, a customer screenshot, or an app-side 'success' screen is never proof of payment. Only a SUCCESSFUL status read by your server counts.
Testing
- Provision a sandbox API user/key with
provision-sandbox.mjs. - Pay with any ordinary number (for example
46733123499) → expectSUCCESSFUL. - Pay with
46733123451→FAILED(rejected);46733123453→ staysPENDING;46733123460→ invalid currency. - Send the same
X-Reference-Idtwice → expect409. - Expose your server with an HTTPS tunnel whose hostname matches
providerCallbackHost, then check callbacks arrive; also stop the server during a payment and confirm the polling job settles the order.
# 1) Token (no body!)
TOKEN=$(curl -s -X POST "https://sandbox.momodeveloper.mtn.com/collection/token/" \
-u "$MOMO_API_USER:$MOMO_API_KEY" \
-H "Ocp-Apim-Subscription-Key: $MOMO_COLLECTION_SUBSCRIPTION_KEY" \
-H "Content-Length: 0" | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
# 2) Request to pay with a fresh UUID v4
REF=$(python3 -c "import uuid; print(uuid.uuid4())")
curl -s -o /dev/null -w "%{http_code}\n" -X POST \
"https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay" \
-H "Authorization: Bearer $TOKEN" -H "X-Reference-Id: $REF" -H "X-Target-Environment: sandbox" \
-H "Ocp-Apim-Subscription-Key: $MOMO_COLLECTION_SUBSCRIPTION_KEY" -H "Content-Type: application/json" \
-d '{"amount":"5","currency":"EUR","externalId":"order-2001",
"payer":{"partyIdType":"MSISDN","partyId":"46733123451"},
"payerMessage":"Test","payeeNote":"Test"}' # expect 202
# 3) Status (46733123451 is the published 'rejected' test number)
curl -s "https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay/$REF" \
-H "Authorization: Bearer $TOKEN" -H "X-Target-Environment: sandbox" \
-H "Ocp-Apim-Subscription-Key: $MOMO_COLLECTION_SUBSCRIPTION_KEY"Common mistakes
- Using a non-EUR currency in sandbox →
INVALID_CURRENCY/400. - Reusing
X-Reference-Idwhen retrying →409. Generate a new UUID v4 per attempt (and keep the old one to check its status). - Sending a JSON body to
/token/→400(the docs list this explicitly). Some HTTP clients also need an explicitContent-Length: 0. - Wrong subscription key — the Disbursement key on a Collection call, or a sandbox key in production.
- Callback host mismatch —
X-Callback-Urlon a different host fromproviderCallbackHost, an IP address instead of a hostname, or plain HTTP. - Treating
202 Acceptedor HTTP200on GET as paid — always readstatus. - Relying on callbacks only — they are sent once, with no retry.
- Apostrophes or long texts in
payerMessage/payeeNote→400.
Troubleshooting
- 401 'missing subscription key' / 'invalid subscription key': header name must be exactly
Ocp-Apim-Subscription-Key; check the product's key on your profile page. - 401 on
/token/: API user/key pair wrong, or created for a different subscription; re-provision in sandbox. - 500
NOT_ALLOWED_TARGET_ENVIRONMENT:X-Target-Environmentmust besandboxin sandbox and the country value (for examplemtnghana) in production. - No callback: check host match, HTTPS certificate chain (approved CAs), that PUT is allowed, and firewall rules; rely on polling meanwhile.
- Status stays
PENDING: the payer has not acted (or you used the 'ongoing' test number46733123453); keep polling with back-off and expire the order after your timeout. INTERNAL_PROCESSING_ERRORin production: often insufficient funds on the payer side; show a friendly message and allow retry with a new reference id.
Further reading
- Use cases — sequence diagrams for Request to Pay, Pre-Approval, Transfer and more.
- Best practices on the MoMo developer portal.
- MoMo developer community for questions about country onboarding.
- Related Metatron guides: Airtel Money Collections and M-Pesa Daraja STK Push use the same "prompt on phone, confirm on server" pattern.
Official documentation
- MoMo Developer portal
- API User & API Key management
- Sandbox use cases
- Callback
- Common error codes
- API collections
Checked 2026-11-25.
Official documentation
Sources
- MoMo Developer portal home
- MoMo docs: Getting started
- MoMo docs: API User & API Key management
- MoMo docs: Sandbox use cases
- MoMo docs: Callback
- MoMo docs: Common error codes
- MoMo docs: Use cases (Request to Pay)
- MoMo portal API definitions: Collection operations
- MoMo portal API definitions: Disbursement refund (Refund-V2)
More payment guides
- MTN MoMo (MoMo Open API) provider profile
- Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayHero Kenya: M-Pesa STK Push via the PayHero API
- PayPal Checkout with Orders v2, verified webhooks and refunds