Mobile app: mobile money payments with OTP
Collect a mobile money payment inside your app, without leaving the screen, using direct charges, three routes on your server and polling tuned for mobile networks.
The secret key stays on your server
Section titled “The secret key stays on your server”Mobile app ──HTTPS──▶ Your backend ──X-API-KEY──▶ api.senfenico.com ▲ ▲ │ └── status ───────────┴──────── signed webhook ◀─────┘The life of a charge
Section titled “The life of a charge”pendingsend_otpthe customer types an OTP in the apppay_offlinethe customer approves on their phonesuccessfailedcanceled
The status returned on creation tells you what to show. Drive the screen from the status you receive, not from what you asked for. Depending on your account setup, a Moov charge requested with OTP can, for example, come back as pay_offline.
Operator (provider) |
status on creation |
What the customer does | display_text returned (in French) |
|---|---|---|---|
Orange Burkina (orange_bf) |
send_otp |
Dials *144*4*6*amount# on their phone to generate an OTP, then types it in the app |
“Composez *144*4*6*1000# pour obtenir un code OTP, puis entrez-le sur notre plateforme pour finaliser la transaction.” |
Moov Burkina (moov_bf), confirmation_method: "otp" |
send_otp |
Receives an OTP by SMS and types it in the app | “Veuillez entrer le code OTP reçu sur votre téléphone pour finaliser la transaction.” |
Moov Burkina (moov_bf), confirmation_method: "ussd" |
pay_offline |
Dials *555*6# and approves on their phone |
“Composez *555*6# sur votre téléphone et suivez les instruction pour finaliser la transaction.” |
Coris Money (coris_bf), Sank Money (sank_bf) |
send_otp |
Receives an OTP and types it in the app | “Veuillez entrer le code OTP reçu sur votre téléphone pour finaliser la transaction.” |
MTN and Moov Benin (mtn_bj, moov_bj) |
pay_offline |
Approves the request on their phone | “Veuillez finaliser la transaction sur votre téléphone” |
display_textis always in French. For an app in another language, show your own text based onproviderandstatus.- The Orange USSD code contains the exact amount. On Android, a
tel:link with#encoded as%23opens the pre-filled dialer. iOS rejects*and#intel:links, so show the code large with a “Copy” button. - In Burkina, numbers have 8 digits without
+226(second digit 0 to 3 for Moov, 4 to 7 for Orange). In Benin, they have 10.
1. The backend (Node.js)
Section titled “1. The backend (Node.js)”The backend reuses the senfenico() client and the database from the Node.js guide. The same logic carries over to Laravel, PHP or Django.
// payments-api.js — mounted with app.use('/api', router)import express from 'express';import { db } from './db.js';import { senfenico, SenfenicoError } from './senfenico.js';
export const router = express.Router();
db.exec(`CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, ext_id TEXT NOT NULL, charge_reference TEXT, status TEXT NOT NULL DEFAULT 'creating', display_text TEXT, updated_at INTEGER)`);
const FINAL = ['success', 'failed', 'canceled'];const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Create the paymentrouter.post('/payments', async (req, res) => { const { orderId, phone, provider, method } = req.body; // authenticate the user; the amount comes from YOUR database const order = db.prepare('SELECT * FROM orders WHERE id = ?') .get(orderId); if (!order || order.status !== 'pending') { return res.status(404).json({ error: 'ORDER_NOT_PAYABLE' }); }
const { lastInsertRowid: id } = db.prepare( 'INSERT INTO payments (order_id, ext_id) VALUES (?, ?)', ).run(order.id, `order-${order.id}-${Date.now()}`); const payment = db.prepare('SELECT * FROM payments WHERE id = ?') .get(id);
let charge; try { charge = (await senfenico('POST', '/charges/', { amount: order.amount, ext_id: payment.ext_id, payment_method_details: { phone, // 8 digits in Burkina provider, // e.g. "orange_bf" confirmation_method: method ?? 'otp', }, })).data; } catch (err) { if (err instanceof SenfenicoError && err.http && err.http < 500) { // clear refusal: HTTP 400/403, or HTTP 200 with status false save(id, 'failed'); return res.status(422).json({ error: err.code ?? 'FAILED' }); } // Timeout or 5xx: the charge may exist. await sleep(30_000); const q = new URLSearchParams({ ext_id: payment.ext_id }); const found = (await senfenico('GET', `/charges/?${q}`) .catch(() => ({ data: [] }))).data[0]; if (!found) { save(id, 'failed'); return res.status(504).json({ error: 'TIMEOUT' }); } charge = { ...found, display_text: null }; }
save(id, charge.status, charge.reference, charge.display_text); res.status(201).json({ paymentId: id, status: charge.status, displayText: charge.display_text, });});
// Submit the OTP (Orange, Moov OTP, Coris, Sank)router.post('/payments/:id/otp', async (req, res) => { const p = db.prepare('SELECT * FROM payments WHERE id = ?') .get(req.params.id); if (!p?.charge_reference) return res.sendStatus(404); try { // no trailing "/" on this route const r = await senfenico('POST', '/charges/submit', { charge_reference: p.charge_reference, otp: String(req.body.otp), }); save(p.id, r.data.status, p.charge_reference); res.json({ status: r.data.status }); } catch (err) { // OTP refused: HTTP 200, status false, error_code (e.g. OTP_INVALID) const status = await refresh(p); // already paid? or failed? res.status(422).json({ status, error: err.code ?? 'UNKNOWN' }); }});
// Read the status (polled by the app)router.get('/payments/:id', async (req, res) => { const p = db.prepare('SELECT * FROM payments WHERE id = ?') .get(req.params.id); if (!p) return res.sendStatus(404); let status = p.status; // No webhook for 15 s? Ask Senfenico. if (!FINAL.includes(status) && p.charge_reference && Date.now() - p.updated_at > 15_000) { status = await refresh(p); } res.json({ status, displayText: p.display_text });});
async function refresh(p) { try { const { data } = await senfenico( 'GET', `/charges/${encodeURIComponent(p.charge_reference)}/`, ); save(p.id, data.status, p.charge_reference); return data.status; } catch { return p.status; }}
function save(id, status, ref = null, text = null) { db.prepare(`UPDATE payments SET status = ?, charge_reference = COALESCE(?, charge_reference), display_text = COALESCE(?, display_text), updated_at = ? WHERE id = ?`).run(status, ref, text, Date.now(), id); // if status === 'success': also mark the order paid}After a timeout, the route searches for the charge by ext_id instead of creating another one, because the API has no idempotency key (see Reconciliation and duplicates).
Response from POST /v1/payment/charges/ for Orange (HTTP 201):
{ "status": true, "message": "Charge attempted", "data": { "reference": "CH261126-101502-ORANGE_BF-8b41079ee8", "status": "send_otp", "display_text": "Composez *144*4*6*1000# pour obtenir un code OTP, puis entrez-le sur notre plateforme pour finaliser la transaction.", "live_mode": false }}Response from POST /v1/payment/charges/submit with a wrong OTP (HTTP 200):
{ "status": false, "message": "Charge operation failed. The OTP is invalid. Please try again.", "error_code": "OTP_INVALID"}Also subscribe your backend to the charge.success and charge.failed webhooks and update payments by charge_reference (see Verify webhook signatures). Polling GET /charges/{reference}/ is only a fallback.
2. The app
Section titled “2. The app”The app sends the request, shows displayText, offers OTP entry when status is send_otp, then polls your backend until a final status.
import 'dart:convert';import 'package:http/http.dart' as http;
const api = 'https://shop.example/api';const finalStatuses = {'success', 'failed', 'canceled'};
Future<Map<String, dynamic>> startPayment( int orderId, String phone, String provider) async { final res = await http .post(Uri.parse('$api/payments'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'orderId': orderId, 'phone': phone, 'provider': provider, })) // > the backend's timeout (create + lookup) .timeout(const Duration(seconds: 150)); return jsonDecode(res.body) as Map<String, dynamic>;}
Future<Map<String, dynamic>> submitOtp(int id, String otp) async { final res = await http .post(Uri.parse('$api/payments/$id/otp'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'otp': otp})) .timeout(const Duration(seconds: 120)); return jsonDecode(res.body) as Map<String, dynamic>;}
/// Polls the backend: every 3 s, then 5 s, max 3 min.Future<String> waitForResult(int id) async { final end = DateTime.now().add(const Duration(minutes: 3)); var delay = const Duration(seconds: 3); while (DateTime.now().isBefore(end)) { await Future.delayed(delay); try { final res = await http .get(Uri.parse('$api/payments/$id')) .timeout(const Duration(seconds: 20)); final status = jsonDecode(res.body)['status'] as String; if (finalStatuses.contains(status)) return status; } catch (_) { // flaky network: keep going } delay = const Duration(seconds: 5); } return 'pending'; // show "awaiting confirmation"}const API = 'https://shop.example/api';const FINAL = ['success', 'failed', 'canceled'];
async function call(path, { method = 'GET', body, timeoutMs }) { const res = await fetch(API + path, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(timeoutMs), }); return res.json();}
export const startPayment = (orderId, phone, provider) => call('/payments', { method: 'POST', body: { orderId, phone, provider }, timeoutMs: 150_000, // > the backend's timeout });
export const submitOtp = (id, otp) => call(`/payments/${id}/otp`, { method: 'POST', body: { otp }, timeoutMs: 120_000, });
// Every 3 s, then 5 s, for 3 minutes at most.export async function waitForResult(id) { const end = Date.now() + 3 * 60_000; let delay = 3000; while (Date.now() < end) { await new Promise((r) => setTimeout(r, delay)); try { const { status } = await call(`/payments/${id}`, { timeoutMs: 20_000 }); if (FINAL.includes(status)) return status; } catch { // flaky network: keep going } delay = 5000; } return 'pending'; // show "awaiting confirmation"}AbortSignal.timeout exists in recent React Native versions (Hermes). Otherwise, use an AbortController with setTimeout.
import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.delayimport kotlinx.coroutines.withContextimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.Requestimport okhttp3.RequestBody.Companion.toRequestBodyimport org.json.JSONObjectimport java.util.concurrent.TimeUnit
private const val API = "https://shop.example/api"private val JSON = "application/json".toMediaType()private val FINAL = setOf("success", "failed", "canceled")
// long read timeout: creation waits for the operatorprivate val client = OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(150, TimeUnit.SECONDS) .build()
private suspend fun call(path: String, body: JSONObject? = null) = withContext(Dispatchers.IO) { val req = Request.Builder().url(API + path).apply { if (body != null) post(body.toString().toRequestBody(JSON)) }.build() client.newCall(req).execute().use { JSONObject(it.body!!.string()) } }
suspend fun startPayment(orderId: Int, phone: String, provider: String) = call("/payments", JSONObject() .put("orderId", orderId) .put("phone", phone) .put("provider", provider))
suspend fun submitOtp(id: Int, otp: String) = call("/payments/$id/otp", JSONObject().put("otp", otp))
/** Every 3 s, then 5 s, for 3 minutes at most. */suspend fun waitForResult(id: Int): String { val end = System.currentTimeMillis() + 3 * 60_000 var pause = 3_000L while (System.currentTimeMillis() < end) { delay(pause) val status = runCatching { call("/payments/$id").getString("status") }.getOrNull() if (status in FINAL) return status!! pause = 5_000L } return "pending" // show "awaiting confirmation"}3. What to show at each step
Section titled “3. What to show at each step”| Step | What the app shows |
|---|---|
| Creation (up to several tens of seconds, while the operator is called) | A “Connecting to Orange Money” indicator. Disable the Pay button to avoid a double submission. |
send_otp |
The instruction (displayText or your translation), then a numeric OTP field (numeric keyboard, SMS autofill when available). For Orange, show the *144*4*6*amount# code large with a “Dial” button (Android) or “Copy” (iOS). |
pay_offline |
“Approve the payment on your phone (code *555*6# for Moov), then come back to the app.” Start waitForResult. The customer will probably leave the app to dial the code, so restart polling when the app returns to the foreground. |
success |
A confirmation screen. The backend has already marked the order paid. |
failed |
A message based on error_code (see the error table) and a “Try again” button that creates a new payment. |
| Still pending after 3 minutes | “Payment awaiting confirmation. We’ll notify you as soon as it clears.” Don’t declare a failure, because the webhook may arrive later. We don’t publish an expiry delay for pay_offline requests, which depends on the operator. |
Wrong or expired OTP
Section titled “Wrong or expired OTP”| Code | What to do |
|---|---|
OTP_INVALID |
Let the customer re-enter the code on the same charge, as the hosted payment page does. With Orange in live mode, the charge is already failed and you must create a new one. Limit to 3 attempts in your app, then offer to start over. |
OTP_EXPIRED |
Create a new charge. For Orange, the customer must dial the USSD code again to get a new OTP. |
CHARGE_NOT_FOUND on /charges/submit |
The reference is unknown or the charge is already paid. The backend above re-reads the charge before answering. |
A charge marked failed after a wrong OTP can still succeed if a correct OTP is submitted afterwards. Always let success win.
4. Test
Section titled “4. Test”With an sk_test_ key on the backend, use these numbers with the exact amount and OTP 123456. For Moov with ussd, the test charge moves to success on its own (or failed if the amount doesn’t match) a few moments after creation.
There are no test values for Benin.
Checklist
Section titled “Checklist”- No
sk_key in the app code, and the amount is set by the backend. - The screen depends on the returned
status(send_otporpay_offline), not on the requested method. -
display_textis translated if the app isn’t in French. - The Pay button is disabled during creation, and app timeouts exceed the backend’s.
- After a timeout, the backend searches for the charge by
ext_idbefore creating another. -
POST /charges/submitis called without a trailing/. - The app polls your backend (not Senfenico) and stops after a few minutes without declaring failure.
- The backend receives
charge.successandcharge.failedthrough a signed webhook.