Africa's Talking Integration Guide
What is Africa's Talking?
REST + callbacks for SMS / USSD / Voice / Airtime; Node SDK africastalking@0.8.4.
SMS: SMS.send({ to, message, senderId }) — the documented REST endpoint is POST /version1/messaging/bulk. A 1xx statusCode means accepted, not delivered; the delivery-report callback brings the final status. USSD is callback-driven: AT POSTs sessionId and a cumulative text ('', '1', '1*50') and you reply text/plain 'CON …' (continue) or 'END …' (close). Voice: VOICE.call({ callFrom, callTo }) queues the call, then your callback returns XML built with VOICE.ActionBuilder. AT signs no callbacks, so guard them with a secret path token, correlate the ids, and use the Airtime / Mobile Data validation callbacks ({"status":"Validated"}) as a wallet-drain guard. There is no payments API (removed in 2023), so pair it with Daraja: USSD menu → M-Pesa STK Push → SMS receipt.
Five Africa's Talking primitives
Telco-grade channels — works on the phones your users actually have.
█████╗ ███████╗██████╗ ██╗ ██████╗ █████╗ ███████╗
██╔══██╗██╔════╝██╔══██╗██║██╔════╝██╔══██╗██╔════╝
███████║█████╗ ██████╔╝██║██║ ███████║███████╗
██╔══██║██╔══╝ ██╔══██╗██║██║ ██╔══██║╚════██║
██║ ██║██║ ██║ ██║██║╚██████╗██║ ██║███████║
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝
████████╗ █████╗ ██╗ ██╗ ██╗██╗███╗ ██╗ ██████╗
╚══██╔══╝██╔══██╗██║ ██║ ██╔╝██║████╗ ██║██╔════╝
██║ ███████║██║ █████╔╝ ██║██╔██╗ ██║██║ ███╗
██║ ██╔══██║██║ ██╔═██╗ ██║██║╚██╗██║██║ ██║
██║ ██║ ██║███████╗██║ ██╗██║██║ ╚████║╚██████╔╝
╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝Africa's Talking Integration Guide
Focus: Pan-African communications — SMS, USSD, Voice (incl. WebRTC), Airtime, Mobile Data, and WhatsApp — over one REST API. USSD is the standout: it works on feature phones with no smartphone or data plan, making it codeAmani's reach-everyone channel alongside M-Pesa. Kenya-targeted projects only — US projects use other providers.
Overview
Africa's Talking (AT) is a REST API with official africastalking SDKs for Node.js
(npm 0.8.4, 2026-10-09, Node >=18) and Python (PyPI 2.0.3, 2026-07-31, Python
>=3.8). TypeScript types come from DefinitelyTyped: @types/africastalking 0.8.0.
Authenticate with your app username + apiKey (header apiKey), or a short-lived
authToken. A free sandbox app (username literally sandbox) mirrors production.
Node SDK services: SMS, USSD, VOICE, AIRTIME, MOBILE_DATA, TOKEN, INSIGHTS
(SIM-swap check), WHATSAPP, APPLICATION (alias ACCOUNT, wallet balance).
No payments API any more. AT's old Payments product (mobile checkout / B2C / wallet transfers) is gone: it was removed from the Node SDK (
lib/payments.js, Nov 2023) and the Python SDK ("Remove all instances of payments", 2023-11-07), and the pricing page lists only SMS, USSD, Airtime, Voice, Mobile Data and WhatsApp. Collect money with Daraja (M-Pesa) for Kenya projects, Stripe everywhere else. (One docs page — Idempotent Requests — still mentions "Payment Disbursement APIs"; treat it as stale text.)
Here is the big picture at a glance — one authenticated REST API fanning out to every channel that reaches your users:
- SMS — transactional (OTP, alerts), bulk and premium, with delivery-report callbacks.
- USSD — synchronous session API; your server replies plain text
CON …(continue) orEND …(terminate). Reaches feature phones with zero data. - Voice / Airtime / Mobile Data — call flows + IVR, airtime top-ups, data bundles.
Official Documentation
1. Credentials, sandbox vs live
Get username + apiKey from the dashboard. The
sandbox app has its own API key; its username is always sandbox.
AT_API_KEY=... # server-side only — never ship to the browser
AT_CALLBACK_TOKEN=... # random 32+ char string; secret path segment for AT callback URLsNon-secret settings (plain env vars, not vault entries):
| Setting | Example | Notes |
|---|---|---|
AT_USERNAME | sandbox / my_app | App username; sandbox switches the SDK to sandbox hosts |
AT_SENDER_ID | CODEAMANI | Registered alphanumeric sender ID or short code (live only) |
AT_USSD_SERVICE_CODE | *384*1234# | Your assigned code, used to sanity-check callbacks |
| Sandbox | Live | |
|---|---|---|
| Username | sandbox (always) | your app's username |
| REST base | https://api.sandbox.africastalking.com/version1 | https://api.africastalking.com/version1 |
| Voice / Data hosts | voice.sandbox… / bundles.sandbox… | voice.africastalking.com / bundles.africastalking.com |
| Cost | free | billed from the app wallet (KES for Kenya) |
| Delivery | simulator (simulator.africastalking.com); default sender ID only reaches Kenyan Airtel numbers | real networks; sender IDs / codes need telco approval |
| Voice | no voice sandbox (the SDK's own voice tests were dropped for this reason, Oct 2026) | numbers must be bought |
The Node SDK picks hosts automatically: if username.toLowerCase() === "sandbox" it rewrites
every base URL to *.sandbox.africastalking.com. There is no separate sandbox: true flag.
Auth tokens. TOKEN.generateAuthToken() (REST POST /auth-token/generate) returns
{ token, lifetimeInSeconds }; send it in an authToken header instead of apiKey when you
want a short-lived credential (e.g. a worker that shouldn't hold the master key).
2. Install + initialize
npm install africastalking@0.8.4
npm install -D @types/africastalking@0.8.0
pip install africastalking==2.0.3import AfricasTalking from "africastalking"; // CommonJS `export =`; needs esModuleInterop
const at = AfricasTalking({
apiKey: process.env.AT_API_KEY ?? "",
username: process.env.AT_USERNAME ?? "sandbox",
});
const { SMS, AIRTIME, VOICE, MOBILE_DATA } = at;Python: africastalking.initialize(username, api_key), then africastalking.SMS,
.Airtime, .Voice, .MobileData, .Token, .Insights, .Whatsapp, .Application.
Every Python call takes an optional timeout (default 10 s since 2.0.x) and an optional
callback= for async use. The Python SDK has no USSD helper — USSD is just an HTTP handler.
3. Send SMS
const res = await SMS.send({
to: ["+254711XXXYYY", "+254733YYYZZZ"], // +254… (international, WITH +)
message: "Your codeAmani code is 123456",
senderId: process.env.AT_SENDER_ID, // omit in sandbox
enqueue: true, // queue without waiting for the telco ACK
});
for (const r of res.SMSMessageData.Recipients) {
// r.statusCode 101 = Sent (accepted), r.cost "KES 0.8000", r.messageId → store it
}SMS.send also accepts an array of option objects (one request each, settled with
Promise.allSettled). Other SMS methods: sendPremium, fetchMessages (inbox polling),
createSubscription / fetchSubscription / deleteSubscription (premium).
Raw REST — the documented bulk endpoint takes a JSON body with a phoneNumbers array:
curl -X POST https://api.africastalking.com/version1/messaging/bulk \
-H "apiKey: $AT_API_KEY" -H "Content-Type: application/json" -H "Accept: application/json" \
-d '{"username":"my_app","phoneNumbers":["+254711XXXYYY"],"message":"Hello","senderId":"ABC"}'Two SMS endpoints.
POST /version1/messaging/bulkis the documented JSON endpoint (phoneNumbersarray,senderId, optionalenqueue,maskedNumber,telco). The Node SDK still calls the older form endpointPOST /version1/messaging(application/x-www-form-urlencoded,toas a comma-separated string,from= your sender ID,bulkSMSMode=1). Premium SMS goes tocontent.africastalking.com/version1/messaging. In the sandbox, the default sender only delivers to Kenyan Airtel numbers — register a sender ID for anything else.
Per-recipient statusCode: 100 Processed · 101 Sent · 102 Queued · 401 RiskHold ·
402 InvalidSenderId · 403 InvalidPhoneNumber · 404 UnsupportedNumberType ·
405 InsufficientBalance · 406 UserInBlacklist · 407 CouldNotRoute ·
409 DoNotDisturbRejection · 500 InternalServerError · 501 GatewayError ·
502 RejectedByGateway. 1xx means accepted, not delivered.
Message length: 160 GSM-7 characters per SMS; any special (non-GSM) character drops it to 70 characters per part, and each extra part is billed as a new message.
Delivery reports
Set SMS → Callback URLs → Delivery Reports in the dashboard. AT POSTs
application/x-www-form-urlencoded with id (= messageId), status (Sent, Submitted,
Buffered, Rejected, Success, Failed, AbsentSubscriber, Expired), phoneNumber,
networkCode, optional failureReason (on Rejected/Failed) and retryCount (premium).
Success is the only "delivered to handset" state. Full handler: examples/send-sms.ts.
4. Handle a USSD session
AT POSTs sessionId, serviceCode, phoneNumber, networkCode, text (form-urlencoded) to your
callback URL on every keypress. text is cumulative, joined with *: "" → "2" → "2*50".
Reply HTTP 200, text/plain, starting CON (keep the session open) or END (close
it). An HTTP error or malformed reply makes AT kill the session, and telcos render special
characters badly — keep menus plain ASCII.
Picture the back-and-forth — each dial POSTs to you, and your CON/END reply decides whether the menu keeps going or wraps up:
In a Next.js App Router project there is no Express, so write the handler against the
web-standard Request:
// app/api/at/ussd/[token]/route.ts — full version in examples/ussd-handler.ts
export async function POST(req: Request): Promise<Response> {
const body = new URLSearchParams(await req.text());
const text = body.get("text") ?? "";
const reply =
text === "" ? "CON Welcome\n1. Balance\n2. Buy airtime"
: text === "1" ? "END Balance: KES 250.00"
: "END Invalid option.";
return new Response(reply, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
}With Express, the Node SDK ships a helper: at.USSD(handler) returns
[urlencodedParser, handler] middleware; you call respond({ response, endSession }) and it
prefixes CON /END for you (validated with Joi — both keys are required):
app.post("/api/at/ussd", ...at.USSD((payload, respond) => {
respond(payload.text === ""
? { response: "Welcome\n1. Balance", endSession: false }
: { response: "Balance: KES 250.00", endSession: true });
}));AT also POSTs an end-of-session notification (if you set the USSD Events callback URL):
sessionId, status (Incomplete / Success / Failed), cost, durationInMillis,
hopsCount, input, lastAppResponse, errorMessage. Use it for analytics and cost
tracking.
Register the callback URL (HTTPS) for your service code in the dashboard. For local testing, tunnel with
ngrok http 3000(same as the M-Pesa callback workflow) and drive it from the sandbox simulator.
5. Voice, Airtime & Mobile Data
Beyond SMS and USSD, the same username + apiKey unlocks three more channels. Note the
separate base hosts: Voice lives on voice.africastalking.com (WebRTC tokens on
webrtc.africastalking.com), Mobile Data on bundles.africastalking.com, while Airtime
stays on the version1 REST host.
Airtime — send a top-up
Up to 1,000 recipients per request. Each needs phoneNumber, currencyCode, numeric
amount. maxNumRetry is a count of hours to keep retrying failed sends (every 60 s;
default window 8 h). AT auto-rejects near-identical airtime requests within 5 minutes —
pass idempotencyKey (sent as the Idempotency-Key header) to force a genuine repeat
through, and to make your own retries safe. Per-country value limits apply (docs "Value
Limits"; Kenya was KES 5 – 10,000 for Safaricom/Airtel/Telkom at the Aug 2026 check — not
re-confirmed). API cap: 500 simultaneous connections per IP; no per-second rate limit.
const result = await AIRTIME.send({
recipients: [{ phoneNumber: "+254711XXXYYY", currencyCode: "KES", amount: 50 }],
maxNumRetry: 3, // retry failed deliveries for up to 3 hours
idempotencyKey: "airtime-order-8812", // your own stable ID, stored before sending
});
// result.responses[].status "Sent" = accepted; result.responses[].requestId → store it
// Later: await AIRTIME.findTransactionStatus(requestId)Raw REST equivalent (note amount as a "KES 100.00" string):
curl -X POST https://api.africastalking.com/version1/airtime/send \
-H "apiKey: $AT_API_KEY" -H "Content-Type: application/json" -H "Accept: application/json" \
-H "Idempotency-Key: airtime-order-8812" \
-d '{"username":"my_app","maxNumRetry":2,"recipients":[{"phoneNumber":"+254711XXXYYY","amount":"KES 110.00"}]}'The final state arrives at the airtime Status callback (phoneNumber, description,
status Success/Failed, requestId, discount, value).
Voice — outbound call, then actions via callback
Outbound voice is queue-then-callback. VOICE.call only queues the call; the call flow
is decided when AT POSTs to your registered voice callback URL and you reply with XML.
const call = await VOICE.call({
callFrom: "+254730XXXXXX", // your AT virtual number
callTo: ["+254711XXXYYY"], // array or comma-separated string
clientRequestId: "reminder-42", // echoed to your callback
});
// call.entries[].status: Queued | InvalidPhoneNumber | DestinationNotSupported | InsufficientCreditREST: POST https://voice.africastalking.com/call, form-urlencoded username, from, to
(comma string), optional clientRequestId. The SDK names are callFrom / callTo — the
wire names are from / to.
Callback (inbound calls and the outbound call flow): AT POSTs isActive (1 during the
call, 0 on the final request), sessionId, direction, callerNumber,
destinationNumber, dtmfDigits (after a GetDigits), and on the final request
recordingUrl, durationInSeconds, currencyCode, amount. Reply 200 with XML built by
VOICE.ActionBuilder:
const xml = new VOICE.ActionBuilder()
.say("Welcome to codeAmani. Press 1 for balance, 2 for support.")
.getDigits(
{ say: { text: "Enter your choice followed by hash." } },
{ numDigits: 1, finishOnKey: "#", timeout: 10, callbackUrl: "https://example.com/api/at/voice/digits" },
)
.build(); // <Response><Say>…</Say><GetDigits …>…</GetDigits></Response>
// return new Response(xml, { headers: { "Content-Type": "application/xml" } })Actions: Say, Play, GetDigits, Dial, Record, Enqueue, Dequeue, Redirect,
Reject, Conference. Other voice methods: getNumQueuedCalls, uploadMediaFile, and —
new in SDK 0.8.4 — requestCapabilityToken({ clientName, phoneNumber, incoming, outgoing, expire }) for the browser WebRTC client (POST webrtc.africastalking.com/capability-token/request,
default lifetime 86,400 s). @types/africastalking@0.8.0 predates it, so cast or call the REST
endpoint directly. 0.8.4 also renamed the misspelled fetchQuedCalls → getNumQueuedCalls.
Mobile Data — send a bundle
MOBILE_DATA.send (REST POST bundles.africastalking.com/mobile/data/request). Each
recipient needs quantity, unit (MB/GB), validity (Day, Week, BiWeek, Month,
Quarterly) and — in the SDK — metadata. productName must match the data product on your
account, and the bundle must exist on the pricing page (Kenya: Safaricom 50 MB – 1 GB only).
await MOBILE_DATA.send({
productName: "Mobile Data",
recipients: [
{ phoneNumber: "+254711XXXYYY", quantity: 500, unit: "MB", validity: "Day",
metadata: { customerId: "CUS001" } },
],
idempotencyKey: "data-order-311",
});
// Also: MOBILE_DATA.findTransaction({ transactionId }), MOBILE_DATA.fetchWalletBalance()Gotcha — three hosts, two amount formats. Voice and Mobile Data don't use the
version1host. Airtime flips amount format by layer: the SDK takes numericamount+currencyCode; raw REST wants one"KES 100.00"string. EveryQueued/Sentstatus means accepted, not delivered — wire up the per-service callbacks.
6. Callback validation (AT does not sign callbacks)
AT documents no HMAC signature or signing secret for any callback (SMS delivery reports, USSD, voice, airtime, mobile data). Treat every callback as untrusted:
- Secret path segment. Register
https://app.example.com/api/at/ussd/<AT_CALLBACK_TOKEN>and 404 anything else; compare in constant time. Rotate by updating the dashboard URL. - Correlate, don't trust. Only act on a delivery report whose
idmatches a storedmessageId, or an airtime status whoserequestIdyou issued. Re-query when money is involved (AIRTIME.findTransactionStatus,MOBILE_DATA.findTransaction). - Validation callbacks — the one real gate. Airtime and Mobile Data support a
Validation callback URL (dashboard label "B2C Validation Callback URL" for data). AT
POSTs
transactionId,phoneNumber,sourceIpAddress,currencyCode,amount(data:bundle,metadata) before disbursing; reply JSON{"status":"Validated"}or{"status":"Failed"}. Approve only transactions your DB knows about — this stops a leaked API key from draining the wallet. - Idempotent handlers. Upsert on
messageId/requestId/sessionId; AT may retry. - Answer fast. USSD and voice wait on your reply — no slow I/O in the request path.
codeAmani notes
- Kenya-targeted only. codeAmani is US-first; AT is the East-African comms rail for projects whose primary users are in Kenya. Payments stay on Daraja (M-Pesa) — AT has no payments API any more — and Stripe remains the default everywhere else.
- First-class African reach: USSD hits feature phones with no data — pair it with SMS (OTP/receipts) and M-Pesa for an end-to-end Kenyan flow: prompt via USSD, charge via M-Pesa STK Push, confirm via SMS.
- Phone format trap: AT wants
+254XXXXXXXXX(international, with+); the repo's Daraja rule is254XXXXXXXXX(no+). Normalize per-API — don't reuse one formatter blindly. SeeMPESA_PATTERNS.md. - Secrets:
AT_API_KEYandAT_CALLBACK_TOKENstay server-side (Hazina / Vercel env).AT_USERNAMEis not secret but must match the key's app (sandbox key +sandbox). - Turn on the validation callbacks for Airtime/Mobile Data in production (see §6).
- Sandbox first: username
sandbox+ the simulator before going live; sender IDs and USSD codes need registration (budget days, and the Kenya sender-ID setup fee inreference/pricing-snapshot.md). - AI routing: generate USSD/SMS copy with Claude, but keep the runtime menu logic deterministic — no LLM call inside a USSD request (the session times out).
- Low-bandwidth: SMS/USSD are the most reliable channels on 2G/3G — favor them for critical notifications over data-dependent push.