Mobile development · Advanced · 32 min
Handle pending, failed and timed-out mobile money payments in the app
By Padding · Updated 18 Nov 2026
Expo SDK 58 · React Native 0.88 · Jest 30.5 · React Native Testing Library 14.1 · Node.js 26 (node:26 image)
You will have an Expo screen that takes a mobile money payment through your own server, shows the right words for every state from prompt sent to timed out, survives the app being closed mid-payment, never charges twice on a retry and offers a receipt, with Jest tests for each part.
On this page
A mobile money payment is not a request that succeeds or fails. When the customer taps Pay, your server asks the provider to send a prompt to their phone: an STK push for M-Pesa, a request to pay for MTN MoMo, a charge for Paystack or Flutterwave. Then nothing happens for a while. The customer reads the prompt, finds their PIN, maybe has too little money, maybe cancels, maybe puts the phone down. The answer reaches your server through a callback or a status query, seconds or minutes later, or not at all.
The app has to show something sensible the whole time, and it must never do the one thing that loses customers' trust: take their money twice. This tutorial builds the client half of that flow in Expo SDK 58. The server half, where your server holds the provider keys and handles callbacks, is in accept mobile money in an app through your own server; here a small stand-in plays that server so you can build and test the app on its own.
You will model the payment as a state machine with a reducer, call your server with an idempotency key, poll with backoff and stop at a deadline, save the payment so it survives the app being closed, and test every state with Jest and React Native Testing Library.
Step 1 · Create the app and a stand-in for your payment server
Create a new Expo app from the SDK 58 template and add the two native modules the payment code uses: AsyncStorage, to remember a payment across restarts, and expo-crypto, to make idempotency keys. Then add Jest with the Expo preset and React Native Testing Library. When npx asks to download create-expo-app, answer y:
cd ~
npx create-expo-app@5.0.0 momo-app-demo --template default@sdk-58
cd ~/momo-app-demo
npx expo install @react-native-async-storage/async-storage expo-crypto
npx expo install jest-expo jest @types/jest -- --save-dev
npm install --save-dev @testing-library/react-native@14.1.0 test-renderer@1.3.1
npm pkg set scripts.test=jestGive Jest a config file, and replace AsyncStorage with its official in-memory mock in every test:
cat > jest.config.js <<'JS'
/** @type {import('jest').Config} */
module.exports = {
preset: 'jest-expo',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/.expo/'],
clearMocks: true,
}
JS
cat > jest.setup.ts <<'TS'
// AsyncStorage needs a phone. Its package ships an in-memory mock for tests.
jest.mock('@react-native-async-storage/async-storage', () =>
require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
)
TSThe app talks to your server, never to the provider: provider keys on a phone can be pulled out of the app by anyone who downloads it. The server this tutorial assumes has two routes:
POST /paymentswith anIdempotency-Keyheader starts a payment and returns it withstatus: "prompt_sent"and anexpiresAttime. The same key sent again returns the same payment instead of creating a second one.GET /payments/:idreturns the payment as your server knows it:prompt_sent,succeededwith a receipt number, orfailedwith a reason.
The stand-in below keeps payments in memory. Like a provider sandbox's test numbers, the last digit of the phone number picks the outcome, and it answers on the second status check so tests are repeatable. Create mock-server/payments.js:
mkdir -p mock-server
cat > mock-server/payments.js <<'JS'
// A stand-in for your payment server: the two routes the app calls, kept in memory.
// The last digit of the phone number picks what the "customer" does.
const OUTCOMES = {
0: { status: 'succeeded' },
1: { status: 'failed', reason: 'wrong_pin' },
2: { status: 'failed', reason: 'insufficient_funds' },
3: { status: 'failed', reason: 'cancelled' },
4: { status: 'failed', reason: 'unreachable' },
// 5 to 9: the customer never answers, so the payment stays at prompt_sent.
}
function createPaymentsApi({ checksBeforeAnswer = 2, promptLifetimeMs = 120_000, now = () => Date.now() } = {}) {
const payments = new Map()
const byKey = new Map()
let seq = 0
function view(p) {
return {
id: p.id,
orderId: p.orderId,
amount: p.amount,
currency: p.currency,
status: p.status,
reason: p.reason ?? null,
receipt: p.receipt ?? null,
paidAt: p.paidAt ?? null,
expiresAt: new Date(p.expiresAt).toISOString(),
}
}
function startPayment(key, body) {
if (!key) return { status: 400, body: { error: 'Idempotency-Key header is required' } }
const { orderId, amount, phone } = body ?? {}
if (typeof orderId !== 'string' || !Number.isInteger(amount) || amount <= 0 || !/^\+?\d{9,15}$/.test(phone ?? '')) {
return { status: 400, body: { error: 'orderId, a whole-number amount and a phone number are required' } }
}
const fingerprint = JSON.stringify([orderId, amount, phone])
const seen = byKey.get(key)
if (seen) {
if (seen.fingerprint !== fingerprint) {
return { status: 422, body: { error: 'This Idempotency-Key was used for a different payment' } }
}
return { status: 200, body: view(seen) } // the same payment, not a second charge
}
seq += 1
const p = {
id: `pay_${seq}`, orderId, amount, currency: 'KES', phone, fingerprint,
status: 'prompt_sent', checks: 0, expiresAt: now() + promptLifetimeMs,
}
payments.set(p.id, p)
byKey.set(key, p)
return { status: 201, body: view(p) }
}
function getPayment(id) {
const p = payments.get(id)
if (!p) return { status: 404, body: { error: 'No such payment' } }
p.checks += 1
const outcome = OUTCOMES[p.phone.slice(-1)]
if (p.status === 'prompt_sent' && outcome && p.checks >= checksBeforeAnswer) {
p.status = outcome.status
p.reason = outcome.reason
if (outcome.status === 'succeeded') {
p.receipt = `MK${p.id.slice(4).padStart(8, '0')}`
p.paidAt = new Date(now()).toISOString()
}
}
return { status: 200, body: view(p) }
}
function handle({ method, path, headers = {}, body }) {
if (method === 'GET' && path === '/health') return { status: 200, body: { ok: true } }
if (method === 'POST' && path === '/payments') return startPayment(headers['idempotency-key'], body)
const match = /^\/payments\/([\w-]+)$/.exec(path)
if (method === 'GET' && match) return getPayment(match[1])
return { status: 404, body: { error: 'Not found' } }
}
return { handle, count: () => payments.size }
}
module.exports = { createPaymentsApi }
JSTwo small files use it. server.js serves it over HTTP for the app on your phone. fetch.js gives tests a fetch that calls it in memory, so tests need no network and work with Jest's fake clock:
cat > mock-server/server.js <<'JS'
const http = require('node:http')
const { createPaymentsApi } = require('./payments')
const api = createPaymentsApi()
const port = Number(process.env.PORT ?? 4020)
http
.createServer((req, res) => {
let raw = ''
req.on('data', (chunk) => (raw += chunk))
req.on('end', () => {
let body = null
try {
body = raw ? JSON.parse(raw) : undefined
} catch {}
const out = api.handle({ method: req.method, path: req.url.split('?')[0], headers: req.headers, body })
console.log(req.method, req.url, out.status, out.body.status ?? out.body.error ?? '')
res.writeHead(out.status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(out.body))
})
})
// 0.0.0.0 so a phone on your Wi-Fi can reach it. It is a stand-in: never expose it to the internet.
.listen(port, '0.0.0.0', () => console.log(`payment stand-in on port ${port}`))
JS
cat > mock-server/fetch.js <<'JS'
// For tests: a fetch that sends each request to the in-memory stand-in.
function fetchFor(api) {
return async (url, init = {}) => {
const path = url.replace(/^https?:\/\/[^/]+/, '')
const headers = {}
for (const [name, value] of Object.entries(init.headers ?? {})) headers[name.toLowerCase()] = value
const out = api.handle({
method: init.method ?? 'GET',
path,
headers,
body: init.body ? JSON.parse(init.body) : undefined,
})
return { ok: out.status >= 200 && out.status < 300, status: out.status, json: async () => out.body }
}
}
module.exports = { fetchFor }
JSStart the stand-in in a second terminal, from ~/momo-app-demo, and leave it running:
node mock-server/server.jsCheck it worked
Back in the first terminal, start the same payment twice with one key, then ask for it twice:
curl -s -w ' %{http_code}\n' -X POST http://127.0.0.1:4020/payments \
-H 'Content-Type: application/json' -H 'Idempotency-Key: demo-key-1' \
-d '{"orderId":"order-1001","amount":1200,"phone":"+254708374150"}'
curl -s -w ' %{http_code}\n' -X POST http://127.0.0.1:4020/payments \
-H 'Content-Type: application/json' -H 'Idempotency-Key: demo-key-1' \
-d '{"orderId":"order-1001","amount":1200,"phone":"+254708374150"}'
curl -s -w '\n' http://127.0.0.1:4020/payments/pay_1
curl -s -w '\n' http://127.0.0.1:4020/payments/pay_1The first POST ends 201 and the second 200, and both bodies have "id":"pay_1" and "status":"prompt_sent": the second request did not create a second payment. The first GET still says prompt_sent; the second says "status":"succeeded" with "receipt":"MK00000001". The second terminal logs each request.
Step 2 · Model the payment as a state machine
Before any screen, write down every state a payment can be in and which events move it between them. A reducer is a good fit: one pure function, (state, event) => state, that you can test without React, a phone or a network.
The states, and what each means for the customer:
idle: nothing sent yet.starting: the request to your server is on its way.start_failed: the request did not get an answer. It may or may not have reached your server, so a retry must reuse the same idempotency key.prompt_sent: your server accepted the payment and the provider sent the prompt.waiting: the prompt has been out for 20 seconds with no answer. Same payment, gentler words.succeededandfailed: the provider gave a final answer. A failure carries a reason: wrong PIN, not enough money, cancelled, phone unreachable.unknown: the deadline passed with no answer. This is not a failure. The money may have moved and the callback may arrive late, so the app must not offer to pay again.
M-Pesa's result codes show where the reasons come from: 0 is success, 1 not enough money, 1032 cancelled by the customer, 1037 phone unreachable and 2001 a wrong PIN. MTN MoMo reports PENDING, SUCCESSFUL or FAILED. Your server translates the provider's codes into these few reasons, so the app does not change when you add a provider.
Create src/payments/machine.ts:
mkdir -p src/payments
cat > src/payments/machine.ts <<'TS'
export type FailureReason = 'wrong_pin' | 'insufficient_funds' | 'cancelled' | 'unreachable' | 'declined'
// A payment as your server returns it.
export type ServerPayment = {
id: string
orderId: string
amount: number
currency: string
status: 'prompt_sent' | 'succeeded' | 'failed'
reason: FailureReason | null
receipt: string | null
paidAt: string | null
expiresAt: string
}
export type Order = { orderId: string; amount: number; currency: string; phone: string }
type Base = { order: Order; key: string }
// deadline: when the app stops asking, in milliseconds since 1970.
type InFlight = Base & { payment: ServerPayment; deadline: number }
export type PaymentState =
| (Base & { phase: 'idle' | 'starting' | 'start_failed' })
| (InFlight & { phase: 'prompt_sent' | 'waiting' | 'unknown' })
| (Base & { phase: 'succeeded' | 'failed'; payment: ServerPayment })
export type PaymentEvent =
| { type: 'PAY' }
| { type: 'START_FAILED' }
| { type: 'CREATED'; payment: ServerPayment }
| { type: 'STATUS'; payment: ServerPayment; elapsedMs: number }
| { type: 'TIMED_OUT' }
| { type: 'CHECK_AGAIN'; until: number }
| { type: 'TRY_AGAIN'; key: string }
// After this long with no answer, the screen changes from "check your phone" to "still waiting".
export const WAITING_AFTER_MS = 20_000
export function initialState(order: Order, key: string): PaymentState {
return { phase: 'idle', order, key }
}
export function paymentReducer(state: PaymentState, event: PaymentEvent): PaymentState {
const { order, key } = state
switch (event.type) {
case 'PAY':
// Only a payment that has not reached your server can be sent. A resend keeps the key.
if (state.phase === 'idle' || state.phase === 'start_failed') return { phase: 'starting', order, key }
return state
case 'START_FAILED':
return state.phase === 'starting' ? { phase: 'start_failed', order, key } : state
case 'CREATED':
if (state.phase !== 'starting') return state
return {
phase: 'prompt_sent',
order,
key,
payment: event.payment,
deadline: Date.parse(event.payment.expiresAt),
}
case 'STATUS': {
if (state.phase !== 'prompt_sent' && state.phase !== 'waiting' && state.phase !== 'unknown') return state
const { payment } = event
if (payment.status === 'succeeded') return { phase: 'succeeded', order, key, payment }
if (payment.status === 'failed') return { phase: 'failed', order, key, payment }
if (state.phase === 'prompt_sent' && event.elapsedMs >= WAITING_AFTER_MS) {
return { ...state, phase: 'waiting', payment }
}
return { ...state, payment }
}
case 'TIMED_OUT':
if (state.phase === 'prompt_sent' || state.phase === 'waiting') return { ...state, phase: 'unknown' }
return state
case 'CHECK_AGAIN':
return state.phase === 'unknown' ? { ...state, phase: 'waiting', deadline: event.until } : state
case 'TRY_AGAIN':
// Only after a final failure: that payment is closed and took no money, so a new key is safe.
return state.phase === 'failed' ? { phase: 'idle', order, key: event.key } : state
}
}
TSThe reducer is the only place that decides what can happen next, and it refuses anything out of order. PAY does nothing once a payment is in flight, so a double tap cannot start a second one. TRY_AGAIN only works after a final failure, and it is the only event that brings a new key. unknown has no way back to idle at all.
Now pin those rules down with tests. Create src/payments/machine.test.ts:
cat > src/payments/machine.test.ts <<'TS'
import {
initialState,
paymentReducer,
WAITING_AFTER_MS,
type PaymentEvent,
type PaymentState,
type ServerPayment,
} from './machine'
const order = { orderId: 'order-1001', amount: 1200, currency: 'KES', phone: '+254708374150' }
function payment(changes: Partial<ServerPayment> = {}): ServerPayment {
return {
id: 'pay_1', orderId: 'order-1001', amount: 1200, currency: 'KES', status: 'prompt_sent',
reason: null, receipt: null, paidAt: null, expiresAt: '2026-12-01T08:02:00.000Z', ...changes,
}
}
function phases(events: PaymentEvent[], from = initialState(order, 'key-1')) {
const seen: string[] = []
let state: PaymentState = from
for (const event of events) {
state = paymentReducer(state, event)
seen.push(state.phase)
}
return { seen, state }
}
const created: PaymentEvent[] = [{ type: 'PAY' }, { type: 'CREATED', payment: payment() }]
test('a payment goes from idle to succeeded', () => {
const paid = payment({ status: 'succeeded', receipt: 'MK00000001', paidAt: '2026-12-01T08:00:05.000Z' })
const { seen, state } = phases([
...created,
{ type: 'STATUS', payment: payment(), elapsedMs: 2_000 },
{ type: 'STATUS', payment: paid, elapsedMs: 5_000 },
])
expect(seen).toEqual(['starting', 'prompt_sent', 'prompt_sent', 'succeeded'])
expect(state).toMatchObject({ phase: 'succeeded', payment: { receipt: 'MK00000001' } })
})
test('the deadline comes from the server', () => {
expect(phases(created).state).toMatchObject({ deadline: Date.parse('2026-12-01T08:02:00.000Z') })
})
test('pressing Pay while a payment is in flight changes nothing', () => {
const starting = paymentReducer(initialState(order, 'key-1'), { type: 'PAY' })
expect(paymentReducer(starting, { type: 'PAY' })).toBe(starting)
const sent = phases(created).state
expect(paymentReducer(sent, { type: 'PAY' })).toBe(sent)
})
test('a request that got no answer is resent with the same key', () => {
const { seen, state } = phases([{ type: 'PAY' }, { type: 'START_FAILED' }, { type: 'PAY' }])
expect(seen).toEqual(['starting', 'start_failed', 'starting'])
expect(state.key).toBe('key-1')
})
test('no answer for 20 seconds moves to waiting', () => {
const { seen } = phases([
...created,
{ type: 'STATUS', payment: payment(), elapsedMs: WAITING_AFTER_MS - 1 },
{ type: 'STATUS', payment: payment(), elapsedMs: WAITING_AFTER_MS },
])
expect(seen.slice(2)).toEqual(['prompt_sent', 'waiting'])
})
test('a final failure keeps its reason, and only then allows a new key', () => {
const { state } = phases([
...created,
{ type: 'STATUS', payment: payment({ status: 'failed', reason: 'wrong_pin' }), elapsedMs: 5_000 },
])
expect(state).toMatchObject({ phase: 'failed', payment: { reason: 'wrong_pin' } })
expect(paymentReducer(state, { type: 'TRY_AGAIN', key: 'key-2' })).toEqual({ phase: 'idle', order, key: 'key-2' })
})
test('reaching the deadline is unknown, and unknown never offers a new payment', () => {
const { state: unknown } = phases([...created, { type: 'TIMED_OUT' }])
expect(unknown.phase).toBe('unknown')
expect(paymentReducer(unknown, { type: 'PAY' })).toBe(unknown)
expect(paymentReducer(unknown, { type: 'TRY_AGAIN', key: 'key-2' })).toBe(unknown)
const checking = paymentReducer(unknown, { type: 'CHECK_AGAIN', until: 123 })
expect(checking).toMatchObject({ phase: 'waiting', deadline: 123, key: 'key-1' })
const late = payment({ status: 'succeeded', receipt: 'MK00000001', paidAt: '2026-12-01T08:03:00.000Z' })
expect(paymentReducer(unknown, { type: 'STATUS', payment: late, elapsedMs: 0 }).phase).toBe('succeeded')
})
TS
npx jest src/payments/machine.test.tsCheck it worked
Jest reports Tests: 7 passed, 7 total. To see a test earn its place, change the PAY case so it also accepts state.phase === 'unknown' and run the file again: the last test fails, because the app would now let a customer pay a second time while the first payment might still go through. Put it back.
Step 3 · Call your server with an idempotency key
The key is what makes a retry safe. The app makes one random key per payment attempt and sends it with every request to start that payment. If the phone sends the request, loses signal and sends it again, your server sees the same key, returns the payment it already started and does not ask the provider for a second prompt. Providers work the same way one level down: MTN MoMo, for example, expects a new UUID in X-Reference-Id for each request to pay, and its API reference lists a 409 Conflict for a duplicated reference id.
Create src/payments/api.ts. It gives up on a request after 15 seconds, because a request that hangs on a weak signal would otherwise freeze the screen:
cat > src/payments/api.ts <<'TS'
import type { Order, ServerPayment } from './machine'
type FetchLike = (
url: string,
init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>
export function createPaymentsClient(
baseUrl: string,
fetchImpl: FetchLike = fetch as unknown as FetchLike,
timeoutMs = 15_000,
) {
async function call(path: string, init: Parameters<FetchLike>[1] = {}): Promise<ServerPayment> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
const res = await fetchImpl(`${baseUrl}${path}`, { ...init, signal: controller.signal })
const body = await res.json()
if (!res.ok) throw new Error(body?.error ?? `HTTP ${res.status}`)
return body as ServerPayment
} finally {
clearTimeout(timer)
}
}
return {
start: (order: Order, key: string) =>
call('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify({ orderId: order.orderId, amount: order.amount, phone: order.phone }),
}),
get: (id: string) => call(`/payments/${encodeURIComponent(id)}`),
}
}
export type PaymentsClient = ReturnType<typeof createPaymentsClient>
TSTest the client against the stand-in. Create src/payments/api.test.ts:
cat > src/payments/api.test.ts <<'TS'
import { fetchFor } from '../../mock-server/fetch'
import { createPaymentsApi } from '../../mock-server/payments'
import { createPaymentsClient } from './api'
const order = (phone = '+254708374150') => ({ orderId: 'order-1001', amount: 1200, currency: 'KES', phone })
let api: ReturnType<typeof createPaymentsApi>
let client: ReturnType<typeof createPaymentsClient>
beforeEach(() => {
api = createPaymentsApi()
client = createPaymentsClient('http://payments.test', fetchFor(api))
})
test('the same request sent twice with one key is one payment', async () => {
const first = await client.start(order(), 'key-1')
const again = await client.start(order(), 'key-1')
expect(first.status).toBe('prompt_sent')
expect(again.id).toBe(first.id)
expect(api.count()).toBe(1)
})
test('a new key is a new payment', async () => {
await client.start(order(), 'key-1')
await client.start(order(), 'key-2')
expect(api.count()).toBe(2)
})
test('a key reused for a different amount is refused', async () => {
await client.start(order(), 'key-1')
await expect(client.start({ ...order(), amount: 5000 }, 'key-1')).rejects.toThrow('different payment')
})
test('the stand-in answers on the second status check', async () => {
const { id } = await client.start(order(), 'key-1')
expect((await client.get(id)).status).toBe('prompt_sent')
expect(await client.get(id)).toMatchObject({ status: 'succeeded', receipt: 'MK00000001' })
})
test.each([
['+254708374151', 'wrong_pin'],
['+254708374152', 'insufficient_funds'],
['+254708374153', 'cancelled'],
['+254708374154', 'unreachable'],
])('%s fails with %s', async (phone, reason) => {
const { id } = await client.start(order(phone), 'key-1')
await client.get(id)
expect(await client.get(id)).toMatchObject({ status: 'failed', reason, receipt: null })
})
TS
npx jest src/payments/api.test.tsCheck it worked
Jest reports Tests: 8 passed, 8 total. The first test is the one that matters most: two identical requests with one key leave api.count() at 1. If yours says 2, the header name in api.ts does not match what the server reads; the stand-in looks for idempotency-key in lower case, as Node.js gives it.
Step 4 · Poll with backoff and stop at a deadline
Your server learns the result from the provider's callback, and the app learns it from your server. The simplest way for the app to ask is polling: a status request every few seconds. Two rules keep it cheap and honest. Space the requests out as time passes, because many customers answer quickly, and the longer the wait, the less likely an answer becomes. And stop at a deadline instead of polling for ever. MTN's MoMo guidance gives the same three rules: exponential backoff, a maximum polling duration, and stop at a final status.
The deadline comes from your server's expiresAt. Set it on the server to the prompt lifetime your provider documents or that you measure in its sandbox, plus a margin; the app should not guess it.
On a prepaid bundle, each status check is a small request, but they add up across many customers, and a phone left on the payment screen should not drain data or battery. Waiting 2, 3, 4.5, 6.75 and then 10 seconds between checks means about fifteen requests for a two-minute prompt instead of sixty at a fixed two seconds.
Create src/payments/poller.ts:
cat > src/payments/poller.ts <<'TS'
import type { ServerPayment } from './machine'
// 2 s, 3 s, 4.5 s, 6.75 s, then 10 s between checks.
export function backoffMs(attempt: number) {
return Math.min(2_000 * 1.5 ** attempt, 10_000)
}
function sleep(ms: number, signal?: AbortSignal) {
return new Promise<void>((resolve) => {
if (signal?.aborted) return resolve()
const done = () => {
clearTimeout(timer)
signal?.removeEventListener('abort', done)
resolve()
}
const timer = setTimeout(done, ms)
signal?.addEventListener('abort', done)
})
}
export type PollOptions = {
check: () => Promise<ServerPayment>
onStatus: (payment: ServerPayment) => void
deadline: number // milliseconds since 1970
firstDelayMs?: number
signal?: AbortSignal
}
export async function pollPayment(options: PollOptions): Promise<'final' | 'timed_out' | 'stopped'> {
const { check, onStatus, deadline, signal } = options
let wait = options.firstDelayMs ?? backoffMs(0)
for (let attempt = 1; ; attempt++) {
const remaining = deadline - Date.now()
if (remaining <= 0) return 'timed_out'
// Never sleep past the deadline: the last check happens at the deadline itself.
await sleep(Math.min(wait, remaining), signal)
if (signal?.aborted) return 'stopped'
try {
const payment = await check()
if (signal?.aborted) return 'stopped'
onStatus(payment)
if (payment.status !== 'prompt_sent') return 'final'
} catch {
// A failed check is a bad connection, not a failed payment. Ask again next time.
}
wait = backoffMs(attempt)
}
}
TSTest it with Jest's fake clock, so half a minute of polling takes milliseconds. jest.useFakeTimers({ now }) fixes what Date.now() returns, and advanceTimersByTimeAsync moves the clock and lets each check's promise settle. Create src/payments/poller.test.ts:
cat > src/payments/poller.test.ts <<'TS'
import { fetchFor } from '../../mock-server/fetch'
import { createPaymentsApi } from '../../mock-server/payments'
import { createPaymentsClient } from './api'
import type { ServerPayment } from './machine'
import { backoffMs, pollPayment } from './poller'
const START = Date.parse('2026-12-01T08:00:00.000Z')
const waitingPayment = { status: 'prompt_sent' } as ServerPayment
beforeEach(() => jest.useFakeTimers({ now: START }))
afterEach(() => jest.useRealTimers())
test('the delay grows from 2 seconds and stops growing at 10', () => {
expect([0, 1, 2, 3, 4, 5].map(backoffMs)).toEqual([2_000, 3_000, 4_500, 6_750, 10_000, 10_000])
})
test('checks with backoff, makes a last check at the deadline, then stops', async () => {
const at: number[] = []
const check = jest.fn(async () => {
at.push(Date.now() - START)
return waitingPayment
})
const result = pollPayment({ check, onStatus: () => {}, deadline: START + 30_000 })
await jest.advanceTimersByTimeAsync(60_000)
await expect(result).resolves.toBe('timed_out')
expect(at).toEqual([2_000, 5_000, 9_500, 16_250, 26_250, 30_000])
})
test('stops as soon as the stand-in has an answer', async () => {
const client = createPaymentsClient('http://payments.test', fetchFor(createPaymentsApi()))
const order = { orderId: 'order-1001', amount: 1200, currency: 'KES', phone: '+254708374150' }
const created = await client.start(order, 'key-1')
const seen: string[] = []
const result = pollPayment({
check: () => client.get(created.id),
onStatus: (p) => seen.push(p.status),
deadline: Date.parse(created.expiresAt),
})
await jest.advanceTimersByTimeAsync(10_000)
await expect(result).resolves.toBe('final')
expect(seen).toEqual(['prompt_sent', 'succeeded'])
})
test('a failed check is tried again, not reported as a failed payment', async () => {
const check = jest
.fn()
.mockRejectedValueOnce(new TypeError('Network request failed'))
.mockResolvedValue({ status: 'succeeded' })
const onStatus = jest.fn()
const result = pollPayment({ check, onStatus, deadline: START + 60_000 })
await jest.advanceTimersByTimeAsync(10_000)
await expect(result).resolves.toBe('final')
expect(check).toHaveBeenCalledTimes(2)
expect(onStatus).toHaveBeenCalledTimes(1)
})
test('aborting stops the loop without a check', async () => {
const controller = new AbortController()
const check = jest.fn(async () => waitingPayment)
const result = pollPayment({ check, onStatus: () => {}, deadline: START + 60_000, signal: controller.signal })
await jest.advanceTimersByTimeAsync(1_000)
controller.abort()
await expect(result).resolves.toBe('stopped')
expect(check).not.toHaveBeenCalled()
})
TS
npx jest src/payments/poller.test.tsPolling is not the only option. Your server can push the result over a WebSocket or server-sent events, or send a silent push notification. Those cost less data per payment, but each one adds a connection that can drop; keep polling as the fallback even if you add one.
Check it worked
Jest reports Tests: 5 passed, 5 total, in well under a second although the second test covers 30 seconds of polling. The list [2000, 5000, 9500, 16250, 26250, 30000] is the schedule your customers' phones will follow: the last check lands exactly on the deadline, never after it.
Step 5 · Survive the app going to the background or being closed
Mobile money takes the customer out of your app. The prompt appears over it, and on many Android phones, low-end ones especially, the system closes apps in the background to free memory. The customer approves the payment, comes back, and finds your app starting from scratch. If the app has forgotten the payment, it shows a Pay button for an order that is already paid.
Two rules fix this:
- Save the order and the idempotency key before the start request leaves the phone, and the payment once the server returns it. When the app opens and finds a saved payment, it carries on with that one instead of offering a new one. If it finds a key without a payment, the app was closed mid-request, so it sends the request again with the same key, and your server answers with the payment it may already have started.
- Stop polling while the app is in the background, and check straight away when it comes back. That moment, returning from the prompt, is when the customer wants an answer.
Create src/payments/store.ts:
cat > src/payments/store.ts <<'TS'
import AsyncStorage from '@react-native-async-storage/async-storage'
import type { Order, ServerPayment } from './machine'
const KEY = 'payments.pending'
// The idempotency key is not a secret: it only lets your server match a retry to a payment.
export type SavedPayment = { order: Order; key: string; payment?: ServerPayment }
export async function savePending(saved: SavedPayment) {
await AsyncStorage.setItem(KEY, JSON.stringify(saved))
}
export async function loadPending(): Promise<SavedPayment | null> {
const raw = await AsyncStorage.getItem(KEY)
if (!raw) return null
try {
return JSON.parse(raw) as SavedPayment
} catch {
return null
}
}
export async function clearPending() {
await AsyncStorage.removeItem(KEY)
}
TSNow the hook that joins the reducer, the client, the poller and the store. Each effect reacts to the phase: starting sends the request, prompt_sent and waiting poll while the app is active, and a final answer clears the saved payment. Create src/payments/usePayment.ts:
cat > src/payments/usePayment.ts <<'TS'
import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
import { AppState } from 'react-native'
import type { PaymentsClient } from './api'
import { initialState, paymentReducer, type Order, type PaymentState } from './machine'
import { pollPayment } from './poller'
import { clearPending, savePending, type SavedPayment } from './store'
// How long "Check again" and a reopened app keep asking before showing "unknown" again.
export const RECHECK_MS = 30_000
export type PaymentDeps = { client: PaymentsClient; newKey: () => string }
export function resumeState(saved: SavedPayment, now: number): PaymentState {
const { order, key, payment } = saved
// Closed before the server answered: send the start request again, with the same key.
if (!payment) return { phase: 'starting', order, key }
if (payment.status === 'succeeded' || payment.status === 'failed') {
return { phase: payment.status, order, key, payment }
}
return { phase: 'waiting', order, key, payment, deadline: Math.max(Date.parse(payment.expiresAt), now + RECHECK_MS) }
}
export function usePayment(order: Order, deps: PaymentDeps, saved: SavedPayment | null) {
const { client, newKey } = deps
const [state, dispatch] = useReducer(paymentReducer, null, () =>
saved ? resumeState(saved, Date.now()) : initialState(order, newKey()),
)
const { phase, order: current, key } = state
// 1. Save the key first, then ask your server to start the payment.
useEffect(() => {
if (phase !== 'starting') return
let live = true
;(async () => {
try {
await savePending({ order: current, key })
const payment = await client.start(current, key)
await savePending({ order: current, key, payment })
if (live) dispatch({ type: 'CREATED', payment })
} catch {
if (live) dispatch({ type: 'START_FAILED' })
}
})()
return () => {
live = false
}
}, [phase, current, key, client])
// 2. Poll while the prompt is out, only while the app is in the foreground.
const [active, setActive] = useState(AppState.currentState !== 'background')
const checkNow = useRef(false)
useEffect(() => {
const subscription = AppState.addEventListener('change', (next) => {
if (next === 'active') checkNow.current = true
setActive(next === 'active')
})
return () => subscription.remove()
}, [])
const polling = (phase === 'prompt_sent' || phase === 'waiting') && active
const paymentId = 'payment' in state ? state.payment.id : null
const deadline = 'deadline' in state ? state.deadline : 0
useEffect(() => {
if (!polling || !paymentId) return
const controller = new AbortController()
const startedAt = Date.now()
const firstDelayMs = checkNow.current ? 0 : undefined
checkNow.current = false
pollPayment({
check: () => client.get(paymentId),
onStatus: (payment) => dispatch({ type: 'STATUS', payment, elapsedMs: Date.now() - startedAt }),
deadline,
firstDelayMs,
signal: controller.signal,
}).then((result) => {
if (result === 'timed_out') dispatch({ type: 'TIMED_OUT' })
})
return () => controller.abort()
}, [polling, paymentId, deadline, client])
// 3. A final answer ends the payment. "unknown" stays saved, so the next launch checks again.
// Your server must give every payment a final status in the end: after the prompt lifetime it
// queries the provider and returns succeeded, or failed with a reason. That answer clears this.
useEffect(() => {
if (phase === 'succeeded' || phase === 'failed') clearPending().catch(() => {})
}, [phase])
const pay = useCallback(() => dispatch({ type: 'PAY' }), [])
const checkAgain = useCallback(() => {
checkNow.current = true
dispatch({ type: 'CHECK_AGAIN', until: Date.now() + RECHECK_MS })
}, [])
const tryAgain = useCallback(() => dispatch({ type: 'TRY_AGAIN', key: newKey() }), [newKey])
return { state, pay, checkAgain, tryAgain }
}
TSSaving on the phone protects one customer on one phone. It does not stop the same order being paid from a second phone, or after the customer reinstalls the app. Your server should also refuse to start a payment for an order that is already paid; accept mobile money in an app through your own server covers that side.
An unknown payment must not stay unknown for ever, or that customer never sees a Pay button for the order again. The app cannot settle it alone, so this is your server's job: once the prompt lifetime has passed with no callback, the server queries the provider and records succeeded, or failed with a reason such as declined or an expired prompt. The app's next check, from "Check again" or the next launch, then sees that final status, clears the saved payment and, for a failure, offers Try again. The status-query recovery is the "Recover a lost callback and refuse a forged one" step of accept mobile money in an app through your own server. The stand-in here skips it and leaves a never-answered payment at prompt_sent, which is fine for testing the app but not for production.
Check it worked
There is nothing to run yet: the hook is tested through the screen in the next step. Read through usePayment.ts once and find the two places a payment can be lost: the app closing between "request sent" and "answer received", and between "answer received" and "saved". Both are covered: the first because savePending({ order, key }) runs before client.start, and the second because a resend with the same key returns the same payment.
Step 6 · Show the right words for every state
Each state needs words that tell the customer what is happening and what to do next, in plain language, without blame. Three rules matter most:
- While the prompt is out, tell them where to look: their phone, the provider's prompt, the amount.
- After a final failure, say why and whether money was taken. For every failure the provider reports, none was.
- When the answer is unknown, say "do not pay again". A customer who pays twice because the screen looked stuck will not trust your app again.
Pass the provider's name in, so the same code says "M-Pesa", "MTN MoMo" or "Airtel Money". If your app is in more than one language, these strings are the ones to translate first, and they get longer in French or Swahili than in English, so do not fit them into a fixed-height box. Create src/payments/copy.ts:
cat > src/payments/copy.ts <<'TS'
import type { FailureReason, PaymentState } from './machine'
export function formatAmount(amount: number, currency: string) {
return `${currency} ${amount.toLocaleString('en-US')}`
}
const FAILURES: Record<FailureReason, string> = {
wrong_pin: 'The PIN was wrong, so the payment did not go through. No money was taken.',
insufficient_funds: 'There was not enough money in the account. No money was taken. Top up, then try again.',
cancelled: 'The prompt was cancelled on the phone. No money was taken.',
unreachable: 'We could not reach the phone. Check it is switched on and has signal, then try again.',
declined: 'The payment was declined. No money was taken.',
}
export function statusCopy(state: PaymentState, provider: string) {
const amount = formatAmount(state.order.amount, state.order.currency)
switch (state.phase) {
case 'idle':
return { title: 'Ready to pay', body: `You will get a ${provider} prompt on ${state.order.phone} to approve ${amount}.` }
case 'starting':
return { title: 'Sending the request', body: `Asking ${provider} to send the prompt to your phone.` }
case 'start_failed':
return {
title: 'Not sent yet',
body: 'We could not confirm the request reached us. Check your connection and send it again. If a prompt already came, sending again does not charge you twice.',
}
case 'prompt_sent':
return { title: 'Check your phone', body: `Check your phone for the ${provider} prompt and enter your PIN to pay ${amount}.` }
case 'waiting':
return {
title: 'Still waiting',
body: `We have not heard back yet. Keep this screen open: we will show the result as soon as ${provider} answers.`,
}
case 'succeeded':
return { title: 'Paid', body: `${amount} paid with ${provider}.` }
case 'failed':
return { title: 'Payment failed', body: FAILURES[state.payment.reason ?? 'declined'] }
case 'unknown':
return {
title: 'Waiting for confirmation',
body: `${provider} has not confirmed this payment yet. Do not pay again. If money has left your account, this order updates on its own and you get a receipt.`,
}
}
}
export function receiptLines(state: PaymentState, provider: string): string[] {
if (state.phase !== 'succeeded') return []
const { payment, order } = state
return [
`Receipt ${payment.receipt ?? 'to follow'}`,
`Order ${order.orderId}`,
`${formatAmount(payment.amount, payment.currency)} paid with ${provider}`,
`Paid at ${(payment.paidAt ?? '').slice(0, 16).replace('T', ' ')} UTC`,
]
}
TSThe receipt line says "to follow" when there is no receipt number, which happens when your server settled the payment from a status query: an M-Pesa Express query response gives the result code but no receipt number, which only the callback carries.
The panel shows the copy and only the buttons that state allows. There is no Pay button while a payment is in flight, and none at all in unknown. The status sits in a live region, so TalkBack reads the new words when the state changes. accessibilityLiveRegion is Android-only, so VoiceOver on iOS stays silent; calling AccessibilityInfo.announceForAccessibility with the new title when the phase changes closes that gap, and is left as an exercise here. Create src/payments/PaymentPanel.tsx:
cat > src/payments/PaymentPanel.tsx <<'TSX'
import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'
import { formatAmount, receiptLines, statusCopy } from './copy'
import type { PaymentState } from './machine'
type Props = {
state: PaymentState
provider: string
onPay: () => void
onCheckAgain: () => void
onTryAgain: () => void
onShareReceipt: () => void
}
function Action({ label, onPress }: { label: string; onPress: () => void }) {
return (
<Pressable
accessibilityRole="button"
onPress={onPress}
style={({ pressed }) => [styles.button, pressed && styles.pressed]}>
<Text style={styles.buttonText}>{label}</Text>
</Pressable>
)
}
export function PaymentPanel({ state, provider, onPay, onCheckAgain, onTryAgain, onShareReceipt }: Props) {
const copy = statusCopy(state, provider)
const amount = formatAmount(state.order.amount, state.order.currency)
const inFlight = state.phase === 'starting' || state.phase === 'prompt_sent' || state.phase === 'waiting'
return (
<View style={styles.panel}>
<Text style={styles.amount}>{amount}</Text>
<View accessibilityLiveRegion="polite" style={styles.status}>
<Text accessibilityRole="header" style={styles.title}>
{copy.title}
</Text>
<Text style={styles.body}>{copy.body}</Text>
</View>
{inFlight && <ActivityIndicator />}
{state.phase === 'idle' && <Action label={`Pay ${amount} with ${provider}`} onPress={onPay} />}
{state.phase === 'start_failed' && <Action label="Send the request again" onPress={onPay} />}
{state.phase === 'failed' && <Action label="Try again" onPress={onTryAgain} />}
{state.phase === 'unknown' && <Action label="Check again" onPress={onCheckAgain} />}
{state.phase === 'succeeded' && (
<View style={styles.receipt}>
{receiptLines(state, provider).map((line) => (
<Text key={line} style={styles.body}>
{line}
</Text>
))}
<Action label="Share receipt" onPress={onShareReceipt} />
</View>
)}
</View>
)
}
const styles = StyleSheet.create({
panel: { gap: 16, padding: 24, backgroundColor: '#ffffff', flex: 1 },
amount: { fontSize: 32, fontWeight: '700', color: '#0b0c0e' },
status: { gap: 8 },
title: { fontSize: 20, fontWeight: '600', color: '#0b0c0e' },
body: { fontSize: 16, lineHeight: 24, color: '#2a2d33' },
receipt: { gap: 4, padding: 16, borderRadius: 8, backgroundColor: '#f1f2f4' },
button: { minHeight: 48, justifyContent: 'center', alignItems: 'center', borderRadius: 8, backgroundColor: '#0b0c0e', paddingHorizontal: 16 },
pressed: { opacity: 0.8 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
})
TSX
cat > src/payments/Checkout.tsx <<'TSX'
import { Share } from 'react-native'
import { receiptLines } from './copy'
import type { Order } from './machine'
import { PaymentPanel } from './PaymentPanel'
import type { SavedPayment } from './store'
import { usePayment, type PaymentDeps } from './usePayment'
type Props = { order: Order; saved: SavedPayment | null; deps: PaymentDeps; provider: string }
export function Checkout({ order, saved, deps, provider }: Props) {
const { state, pay, checkAgain, tryAgain } = usePayment(order, deps, saved)
const shareReceipt = () => {
Share.share({ message: receiptLines(state, provider).join('\n') }).catch(() => {})
}
return (
<PaymentPanel
state={state}
provider={provider}
onPay={pay}
onCheckAgain={checkAgain}
onTryAgain={tryAgain}
onShareReceipt={shareReceipt}
/>
)
}
TSXTest every state of the panel by its heading and its buttons, the way a screen reader user meets them. Create __tests__/payment-panel.test.tsx:
mkdir -p __tests__
cat > __tests__/payment-panel.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { initialState, type PaymentState, type ServerPayment } from '../src/payments/machine'
import { PaymentPanel } from '../src/payments/PaymentPanel'
const order = { orderId: 'order-1001', amount: 1200, currency: 'KES', phone: '+254708374150' }
const key = 'key-1'
const payment = (changes: Partial<ServerPayment> = {}): ServerPayment => ({
id: 'pay_1', orderId: 'order-1001', amount: 1200, currency: 'KES', status: 'prompt_sent',
reason: null, receipt: null, paidAt: null, expiresAt: '2026-12-01T08:02:00.000Z', ...changes,
})
const paid = payment({ status: 'succeeded', receipt: 'MK00000001', paidAt: '2026-12-01T08:00:05.000Z' })
const cases: [string, PaymentState, string, string[]][] = [
['idle', initialState(order, key), 'Ready to pay', ['Pay KES 1,200 with M-Pesa']],
['starting', { phase: 'starting', order, key }, 'Sending the request', []],
['start_failed', { phase: 'start_failed', order, key }, 'Not sent yet', ['Send the request again']],
['prompt_sent', { phase: 'prompt_sent', order, key, payment: payment(), deadline: 0 }, 'Check your phone', []],
['waiting', { phase: 'waiting', order, key, payment: payment(), deadline: 0 }, 'Still waiting', []],
['succeeded', { phase: 'succeeded', order, key, payment: paid }, 'Paid', ['Share receipt']],
['failed', { phase: 'failed', order, key, payment: payment({ status: 'failed', reason: 'insufficient_funds' }) }, 'Payment failed', ['Try again']],
['unknown', { phase: 'unknown', order, key, payment: payment(), deadline: 0 }, 'Waiting for confirmation', ['Check again']],
]
function show(state: PaymentState, provider = 'M-Pesa') {
return render(
<PaymentPanel state={state} provider={provider} onPay={jest.fn()} onCheckAgain={jest.fn()} onTryAgain={jest.fn()} onShareReceipt={jest.fn()} />,
)
}
test.each(cases)('%s shows its heading and only its own buttons', async (_phase, state, heading, buttons) => {
await show(state)
expect(screen.getByRole('header', { name: heading })).toBeOnTheScreen()
expect(screen.queryAllByRole('button')).toHaveLength(buttons.length)
for (const name of buttons) expect(screen.getByRole('button', { name })).toBeOnTheScreen()
})
test('the prompt copy names the provider and the amount', async () => {
await show(cases[3][1], 'MTN MoMo')
expect(screen.getByText('Check your phone for the MTN MoMo prompt and enter your PIN to pay KES 1,200.')).toBeOnTheScreen()
})
test('unknown tells the customer not to pay again', async () => {
await show(cases[7][1])
expect(screen.getByText(/Do not pay again/)).toBeOnTheScreen()
})
test('the receipt shows the number, the order and the time', async () => {
await show(cases[5][1])
expect(screen.getByText('Receipt MK00000001')).toBeOnTheScreen()
expect(screen.getByText('Order order-1001')).toBeOnTheScreen()
expect(screen.getByText('Paid at 2026-12-01 08:00 UTC')).toBeOnTheScreen()
})
TSX
npx jest __tests__/payment-panel.test.tsxCheck it worked
Jest reports Tests: 11 passed, 11 total: eight states, each with its own heading and nothing but its own buttons, and three checks of the words. If you add a Pay button to the unknown state, the unknown case fails with two buttons where one was expected.
Step 7 · Test whole payments, a double tap and a reopened app
The panel tests check each state on its own. Now test the hook and the screen together against the stand-in, with the fake clock, the way a customer goes through them: tap Pay, see the prompt copy, wait, see the result. Each test below covers one thing that goes wrong in real payments. Create __tests__/checkout.test.tsx:
cat > __tests__/checkout.test.tsx <<'TSX'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { act, render, renderHook, screen, userEvent } from '@testing-library/react-native'
import { Share } from 'react-native'
import { fetchFor } from '../mock-server/fetch'
import { createPaymentsApi } from '../mock-server/payments'
import { createPaymentsClient } from '../src/payments/api'
import { Checkout } from '../src/payments/Checkout'
import type { Order } from '../src/payments/machine'
import { loadPending, savePending, type SavedPayment } from '../src/payments/store'
import { usePayment } from '../src/payments/usePayment'
const order = (phone: string): Order => ({ orderId: 'order-1001', amount: 1200, currency: 'KES', phone })
let api: ReturnType<typeof createPaymentsApi>
let client: ReturnType<typeof createPaymentsClient>
let keys = 0
function open(phone: string, saved: SavedPayment | null = null) {
const deps = { client, newKey: () => `key-${++keys}` }
return render(<Checkout order={order(phone)} saved={saved} deps={deps} provider="M-Pesa" />)
}
const heading = (name: string) => screen.getByRole('header', { name })
const wait = (ms: number) => act(() => jest.advanceTimersByTimeAsync(ms))
beforeEach(async () => {
jest.useFakeTimers({ now: new Date('2026-12-01T08:00:00.000Z') })
api = createPaymentsApi()
client = createPaymentsClient('http://payments.test', fetchFor(api))
keys = 0
await AsyncStorage.clear()
})
afterEach(() => jest.useRealTimers())
test('a successful payment shows the prompt, then a receipt to share', async () => {
const user = userEvent.setup()
await open('+254708374150')
await user.press(screen.getByRole('button', { name: 'Pay KES 1,200 with M-Pesa' }))
expect(await screen.findByRole('header', { name: 'Check your phone' })).toBeOnTheScreen()
expect(screen.queryByRole('button', { name: /^Pay/ })).not.toBeOnTheScreen()
await wait(6_000)
expect(heading('Paid')).toBeOnTheScreen()
expect(screen.getByText('Receipt MK00000001')).toBeOnTheScreen()
expect(await loadPending()).toBeNull()
const share = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' })
await user.press(screen.getByRole('button', { name: 'Share receipt' }))
expect(share.mock.calls[0][0]).toEqual({ message: expect.stringContaining('Receipt MK00000001') })
})
test('a double tap on Pay sends one payment', async () => {
// Both taps land before React redraws the screen, so call pay twice in one update.
const deps = { client, newKey: () => `key-${++keys}` }
const checkout = order('+254708374150')
const { result } = await renderHook(() => usePayment(checkout, deps, null))
await act(() => {
result.current.pay()
result.current.pay()
})
await wait(6_000)
expect(result.current.state.phase).toBe('succeeded')
expect(api.count()).toBe(1)
})
test('a wrong PIN says why, and trying again is a new payment', async () => {
const user = userEvent.setup()
await open('+254708374151')
await user.press(screen.getByRole('button', { name: 'Pay KES 1,200 with M-Pesa' }))
await wait(6_000)
expect(heading('Payment failed')).toBeOnTheScreen()
expect(screen.getByText(/The PIN was wrong/)).toBeOnTheScreen()
await user.press(screen.getByRole('button', { name: 'Try again' }))
await user.press(screen.getByRole('button', { name: 'Pay KES 1,200 with M-Pesa' }))
await wait(1_000)
expect(api.count()).toBe(2)
})
test('no answer by the deadline is unknown: no Pay button, and the payment stays saved', async () => {
const user = userEvent.setup()
await open('+254708374159')
await user.press(screen.getByRole('button', { name: 'Pay KES 1,200 with M-Pesa' }))
await wait(30_000)
expect(heading('Still waiting')).toBeOnTheScreen()
await wait(95_000)
expect(heading('Waiting for confirmation')).toBeOnTheScreen()
expect(screen.queryByRole('button', { name: /^Pay/ })).not.toBeOnTheScreen()
expect((await loadPending())?.payment?.id).toBe('pay_1')
await user.press(screen.getByRole('button', { name: 'Check again' }))
expect(heading('Still waiting')).toBeOnTheScreen()
await wait(31_000)
expect(heading('Waiting for confirmation')).toBeOnTheScreen()
expect(api.count()).toBe(1)
})
test('an app reopened mid-payment carries on with the saved payment', async () => {
const payment = await client.start(order('+254708374150'), 'key-saved')
await savePending({ order: order('+254708374150'), key: 'key-saved', payment })
await open('+254708374150', await loadPending())
expect(heading('Still waiting')).toBeOnTheScreen()
await wait(6_000)
expect(heading('Paid')).toBeOnTheScreen()
expect(api.count()).toBe(1)
})
test('an app closed before the server answered resends with the same key', async () => {
// The request reached the server, but the app was closed before the answer arrived.
await client.start(order('+254708374150'), 'key-saved')
await savePending({ order: order('+254708374150'), key: 'key-saved' })
await open('+254708374150', await loadPending())
await wait(6_000)
expect(heading('Paid')).toBeOnTheScreen()
expect(api.count()).toBe(1)
})
TSX
npx jest __tests__/checkout.test.tsxThe fourth test runs over two and a half minutes of polling in a fraction of a second. The last two are the ones that protect your customers' money: the app comes back after being closed and the stand-in still holds exactly one payment.
Check it worked
Jest reports Tests: 6 passed, 6 total. Then run the whole suite:
npx jest --ciIt ends with Test Suites: 5 passed, 5 total and Tests: 37 passed, 37 total. To see the last test earn its place, change the first line of resumeState in usePayment.ts to if (!payment) return initialState(order, key) and run npx jest __tests__/checkout.test.tsx again: the last test fails, because a reopened app now shows a fresh Pay button for a payment your server already started. Put the line back.
Step 8 · Put the screen in the app and build it
Add a Pay tab. The screen reads any saved payment before it shows the checkout, so a reopened app goes straight back to it. The server's address comes from EXPO_PUBLIC_PAYMENTS_URL; it is not a secret, since everything in an Expo app's bundle can be read, which is exactly why provider keys stay on your server. Create src/app/pay.tsx:
cat > src/app/pay.tsx <<'TSX'
import * as Crypto from 'expo-crypto'
import { useEffect, useState } from 'react'
import { ActivityIndicator } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { createPaymentsClient } from '@/payments/api'
import { Checkout } from '@/payments/Checkout'
import type { Order } from '@/payments/machine'
import { loadPending, type SavedPayment } from '@/payments/store'
// Your server, never the provider: the app holds no provider keys.
const client = createPaymentsClient(process.env.EXPO_PUBLIC_PAYMENTS_URL ?? 'http://127.0.0.1:4020')
const deps = { client, newKey: () => Crypto.randomUUID() }
// In a real app the order comes from the basket and the phone number from the customer.
const order: Order = { orderId: 'order-1001', amount: 1200, currency: 'KES', phone: '+254708374150' }
export default function PayScreen() {
const [saved, setSaved] = useState<SavedPayment | null | undefined>(undefined)
useEffect(() => {
loadPending().then(setSaved, () => setSaved(null))
}, [])
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#ffffff' }}>
{saved === undefined ? (
<ActivityIndicator />
) : (
<Checkout order={saved?.order ?? order} saved={saved} deps={deps} provider="M-Pesa" />
)}
</SafeAreaView>
)
}
TSXThe template's tabs are listed in src/components/app-tabs.tsx. Replace that file with a version that adds a Pay tab after the two the template has (swap the icon for your own later):
cat > src/components/app-tabs.tsx <<'TSX'
import { NativeTabs } from 'expo-router/native-tabs';
import { useColorScheme } from 'react-native';
import { Colors } from '@/constants/theme';
export default function AppTabs() {
const scheme = useColorScheme();
const colors = Colors[scheme === 'dark' ? 'dark' : 'light'];
return (
<NativeTabs
backgroundColor={colors.background}
indicatorColor={colors.backgroundElement}
labelStyle={{ selected: { color: colors.text } }}>
<NativeTabs.Trigger name="index">
<NativeTabs.Trigger.Label>Home</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/home.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="explore">
<NativeTabs.Trigger.Label>Explore</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/explore.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
<NativeTabs.Trigger name="pay">
<NativeTabs.Trigger.Label>Pay</NativeTabs.Trigger.Label>
<NativeTabs.Trigger.Icon
src={require('@/assets/images/tabIcons/explore.png')}
renderingMode="template"
/>
</NativeTabs.Trigger>
</NativeTabs>
);
}
TSXBuild the Android JavaScript bundle to check that everything compiles together, the native modules included:
npx expo export --platform android
grep -l "Do not pay again" dist/_expo/static/js/android/*To try it on a phone, find your computer's address on your Wi-Fi network (for example 192.168.1.20; replace it with yours), keep the stand-in running in the second terminal, and start Expo with the address set:
EXPO_PUBLIC_PAYMENTS_URL=http://192.168.1.20:4020 npx expo startScan the QR code with Expo Go and open the Pay tab. To test a closed app, tap Pay, close the app from the recent apps list straight away, and open it again.
Check it worked
The export ends by listing the files it wrote to dist, and grep prints the path of the Android bundle, which contains the "unknown" copy. On the phone, tapping Pay shows "Check your phone" and, about five seconds later, "Paid" with receipt MK00000001 and a Share receipt button that opens the share sheet; the second terminal logs one POST /payments 201 and the status checks. Reopening a closed app mid-payment shows "Still waiting" and then "Paid", with no second POST /payments 201 in the log. To see the other states, change the phone number in pay.tsx: ending 1 gives the wrong PIN message, ending 9 runs to "Waiting for confirmation".
When you are done, stop the stand-in with Ctrl+C in the second terminal. To remove everything this tutorial made, delete the project:
rm -rf ~/momo-app-demoNext steps
- Build the server half, with provider keys, signed callbacks and status queries: accept mobile money in an app through your own server.
- See the provider side of one integration in full: collect M-Pesa payments with the Daraja STK Push API.
- Design the waiting states with care: design loading states: spinners, skeletons and progress.
- Make the rest of the app cheap on prepaid data: design for slow networks and costly data.
Related tutorials
- Accept mobile money in an app through your own serverYou will build the Node.js 26 server half of a mobile money checkout, where the app never holds provider keys, the server starts each charge once with an idempotency key, signed callbacks are checked and re-queried, and a status query recovers payments whose callback never arrived.
- Design for slow networks and costly dataYou will have a per-screen data budget for the Larkfield Clinic booking flow, Figma frames for what each screen shows offline, a save-and-resume state, a use-less-data option and SMS confirmation text that fits in one message.
- Design loading states: spinners, skeletons and progressYou will have a loading-state table for every wait in a booking flow, with the pattern chosen by expected wait time, and Figma frames for a skeleton, a button spinner, an upload progress bar, an optimistic switch and a "taking longer than usual" state.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials