Build · POST /v0/payments/charge

Your first mobile money charge, from sandbox to webhook

A developer walkthrough: normalise a number, size the amount, send a mobile money charge, verify the signed webhook, and test every outcome in sandbox.

Ultraner team··4 min read

A mobile money charge is two HTTP conversations that happen at different times. You ask for money. Later, maybe seconds, maybe minutes, someone tells you whether you got it. Every bug in a first integration comes from treating those as one conversation.

This walkthrough builds the smallest correct version in Node.js: a function that charges a phone, and a webhook that learns the result. It runs against the sandbox, so no real money moves. Expect about thirty minutes.

What you need

  • An Ultraner business account and a sandbox key. Sandbox keys start with uk_test_. Live keys start with uk_live_ and charge real money, so keep them out of this exercise.
  • Node.js 18 or later, for built-in fetch.
  • A public HTTPS URL for your webhook. A tunnelling tool is fine for local testing.

The full API reference is in the docs. This guide uses three pieces of it.

Step 1: Normalise the phone number

The API wants the number in international form, digits only: the E.164 layout 2 without the +. Customers will not type it that way, so clean it up.

js
const PREFIX = { TZ: '255', ZM: '260' };

function normalisePhone(input, country) {
  const digits = input.replace(/\D/g, '');
  const cc = PREFIX[country];
  if (digits.startsWith(cc)) return digits;
  if (digits.startsWith('0')) return cc + digits.slice(1);
  return cc + digits;
}

normalisePhone('0712 345 678', 'TZ');  // '255712345678'
normalisePhone('+260 97 123 4567', 'ZM'); // '260971234567'

Then check the length. Both Tanzania and Zambia are twelve digits in total. Other markets differ (Benin and Ivory Coast are thirteen, Sierra Leone eleven), so keep lengths in a table per country, not in your head. Each country page states its own.

Step 2: Size the amount for the currency

Amounts are integers in the currency's smallest unit. For TZS that is the shilling itself, because TZS is used without decimals. For ZMW it is the ngwee, a hundredth of a kwacha.

js
const ZERO_DECIMAL = new Set(['TZS', 'UGX', 'RWF', 'XOF', 'XAF']);

function toApiAmount(display, currency) {
  return ZERO_DECIMAL.has(currency) ? Math.round(display) : Math.round(display * 100);
}

toApiAmount(25000, 'TZS'); // 25000  -> TZS 25,000
toApiAmount(150, 'ZMW');   // 15000  -> ZMW 150.00

If you remember one thing from this guide, make it this function. The most common first-integration bug is a prompt for a hundred times the price.

Step 3: Send the charge

The universal endpoint takes the same shape for every country. Ultraner reads the country from the phone prefix and routes to the rail that serves that network there. You choose the network with provider.

js
const API = 'https://api.ultraner.com';
const KEY = process.env.ULTRANER_KEY; // uk_test_...

async function charge({ phone, amount, provider }) {
  const res = await fetch(`${API}/v0-sandbox/payments/charge`, {
    method: 'POST',
    headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ method: 'mobile_money', amount, phone, provider }),
  });
  const json = await res.json();
  if (!json.success) throw new Error(JSON.stringify(json));
  return json.data; // { transactionId, status: 'pending', ... }
}

Note the path: /v0-sandbox/payments/charge with a uk_test_ key. In production it becomes /v0/payments/charge with a uk_live_ key, and nothing else changes.

Call it for a Tanzanian Airtel Money customer:

js
const order = { id: 'ord_1042', amountTzs: 25000 };
const txn = await charge({
  phone: normalisePhone('0700 000 001', 'TZ'), // sandbox: instant success
  amount: toApiAmount(order.amountTzs, 'TZS'),
  provider: 'Airtel',
});
await db.orders.update(order.id, { transactionId: txn.transactionId, status: 'awaiting_payment' });

Two details matter here. First, store the transactionId against your order immediately. It is how the webhook will find the order later. Second, the status is pending. That means the request was accepted and the prompt is on its way, not that anyone has paid. Your UI should now say "Check your phone and approve the payment", and nothing more confident.

Step 4: Receive the result

The outcome arrives as a signed POST to your webhook URL, which you register in the console under Webhooks. Copy the signing secret when it is shown, because it is shown once.

Every event carries an x-ultraner-signature header: sha256= followed by an HMAC-SHA256 of the body with your secret 1. Verify it before you read anything else. Use a constant-time comparison so the check does not leak timing information 3.

js
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json());

function validSignature(req) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', process.env.WH_SECRET)
    .update(JSON.stringify(req.body))
    .digest('hex');
  const got = req.headers['x-ultraner-signature'] || '';
  return got.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
}

app.post('/webhooks/ultraner', async (req, res) => {
  if (!validSignature(req)) return res.status(401).end();
  const { event, data } = req.body;
  const order = await db.orders.findByTransaction(data.transaction_id);
  if (!order) return res.status(200).end();

  if (event === 'payment.success' && order.status !== 'paid') {
    await db.orders.update(order.id, { status: 'paid' });
    await fulfil(order);
  }
  if (event === 'payment.failed' && order.status === 'awaiting_payment') {
    await db.orders.update(order.id, { status: 'failed', reason: data.failure_reason });
  }
  res.status(200).end();
});

Read that handler for what it refuses to do:

  • It never fulfils twice. A repeated payment.success finds the order already paid and does nothing.
  • A success can follow a failure. If a customer ignores the prompt, Ultraner closes the charge as failed after 10 minutes. If the network confirms the payment late, payment.success arrives for the same transaction. The handler above accepts it, because it checks !== 'paid', not === 'awaiting_payment'.
  • It answers 200 for orders it does not know, so the event is not retried forever.

The webhooks capability lists every event type Ultraner sends.

Step 5: Test every outcome

The sandbox decides the result from the end of the phone number, so you can rehearse each path on purpose:

Number ends inWhat happens
700000001Instant success
700000002Fails, insufficient funds
700000003Stays pending, then fails after about 10 minutes
anything elseSucceeds after a 3 to 8 second delay

An amount between 1 and 100 simulates a provider outage, which is worth one test so you know what your code does with a 5xx.

Run all of them. For each, watch three things: what the customer sees, what your order table says, and what your logs say. The pending-then-failed case is the one most integrations get wrong, because nobody waits ten minutes during development. Wait the ten minutes once.

Step 6: Going live

The change from sandbox to live is small on purpose:

  1. Swap uk_test_ for uk_live_ and /v0-sandbox/ for /v0/.
  2. Register your production webhook URL and store its secret.
  3. Build your network picker from the live provider list rather than hard-coding it.
  4. Make one real payment with your own phone and a small amount, and refund or keep it.

Then read the pricing so you know what each market costs before your first customer finds out for you. You now have the smallest correct integration: a charge, a signed webhook, and an order that only becomes paid when the network says so. Everything else, subscriptions, payouts, refunds, is built on these same two conversations.

Sources

  1. 1RFC 2104: HMAC, Keyed-Hashing for Message Authentication, IETF
  2. 2E.164: The international public telecommunication numbering plan, ITU
  3. 3crypto.timingSafeEqual, Node.js Documentation

For AI agents and tools: this article is also available as plain Markdown, every article is in the RSS feed, and the site guide for AI is at llms.txt.

Keep reading