Error Handling
Best practices for handling errors, implementing retries, and building resilient integrations with the Click Airtime API.
Robust error handling is essential for any airtime top-up integration. This guide covers common error scenarios and proven patterns for building reliable systems.
Error Response Format
Version 2 API
All V2 error responses follow a consistent structure:
{
"success": false,
"error": {
"code": "INSUFFICIENT_BALANCE",
"message": "Insufficient balance in wallet"
},
"meta": {
"request_id": "req_a1b2c3d4e5f6",
"timestamp": "2026-10-13T13:24:49.604Z"
}
}
See Error Codes for every V2 error code.
Version 1 API
V1 errors use a simpler format with string-based status codes:
{
"message": "Insufficient balance to complete this transaction",
"statusCode": 200,
"code": "0"
}
The V1 API returns HTTP 200 for many error conditions. Always check the code field ("0" = failure) rather than relying on the HTTP status code alone.
Error Categories
Client Errors (4xx)
These errors indicate a problem with the request. Do not retry these automatically — fix the request first.
| Status | Code | Description | Action |
|---|---|---|---|
| 400 | INVALID_REQUEST | Malformed header or query parameter, or both amount and product_id sent | Fix the request parameters |
| 400 | MISSING_REQUIRED_FIELD | A required field is missing (e.g. neither amount nor product_id) | Add the missing field |
| 400 | INVALID_PHONE_NUMBER | Phone number is not E.164 | Format as + followed by digits |
| 400 | INVALID_AMOUNT | Custom amount out of range, wrong currency, or not available on this network | Check custom_airtime in the catalog |
| 400 | INVALID_PRODUCT | product_id is not a valid bundle id for this network | Use an integer id from fixed_bundles |
| 400 | INSUFFICIENT_BALANCE | Wallet balance is too low | Fund the wallet or reduce the amount |
| 401 | INVALID_API_KEY / EXPIRED_API_KEY / REVOKED_API_KEY | API key is missing, unknown, expired, or revoked | Check the key in the Enterprise Portal |
| 403 | INSUFFICIENT_PERMISSIONS / IP_NOT_ALLOWED | Key lacks the permission, or the request IP is not allowed | Update the key's permissions or IP allowlist |
| 404 | NETWORK_NOT_FOUND / TRANSACTION_NOT_FOUND / WALLET_NOT_FOUND | Resource does not exist (or does not belong to your company) | Verify the ID |
| 409 | DUPLICATE_REQUEST | The same top-up is still being processed | Wait a few seconds, then retry with the same Idempotency-Key |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests | Wait for the Retry-After period, then retry |
Server Errors (5xx)
| Status | Code | Description | Action |
|---|---|---|---|
| 500 | DELIVERY_FAILED | The operator did not deliver the top-up; the transaction is recorded as failed | Check failure_reason with GET /v2/topups/:id; send a new top-up (new Idempotency-Key) only if you want to try again |
| 500 | INTERNAL_ERROR | Unexpected server error | Retry with backoff using the same Idempotency-Key, or check GET /v2/topups?reference=... first |
Retry Strategy
Exponential Backoff with Jitter
For transient errors (INTERNAL_ERROR, 429, network timeouts), implement exponential backoff with random jitter to avoid thundering herd problems. For POST /v2/topups, always resend the same Idempotency-Key on retry, and treat DELIVERY_FAILED as a final answer for that attempt rather than retrying it automatically.
async function retryWithBackoff(fn, maxRetries = 3) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries) throw error;
// Only retry transient errors: network failures/timeouts (no status),
// 409 DUPLICATE_REQUEST, 429, and INTERNAL_ERROR. DELIVERY_FAILED is a
// final answer for this attempt — never retry it automatically.
const transient = !error.status || error.status === 409 || error.status === 429 || error.code === 'INTERNAL_ERROR';
if (!transient) {
throw error;
}
// Exponential backoff with jitter
const baseDelay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
const jitter = Math.random() * 1000;
const delay = baseDelay + jitter;
console.log(`Attempt ${attempt + 1} failed, retrying in ${Math.round(delay)}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Usage
const result = await retryWithBackoff(() => sendTopup({
phoneNumber: '+233541112259',
amount: 5,
}));import time
import random
def retry_with_backoff(fn, max_retries=3):
for attempt in range(max_retries + 1):
try:
return fn()
except Exception as error:
if attempt == max_retries:
raise
# Only retry transient errors: network failures/timeouts (no status),
# 409 DUPLICATE_REQUEST, 429, and INTERNAL_ERROR. DELIVERY_FAILED is a
# final answer for this attempt -- never retry it automatically.
status = getattr(error, 'status_code', None)
code = getattr(error, 'code', None)
transient = status is None or status in (409, 429) or code == 'INTERNAL_ERROR'
if not transient:
raise
# Exponential backoff with jitter
base_delay = (2 ** attempt) # 1s, 2s, 4s
jitter = random.uniform(0, 1)
delay = base_delay + jitter
print(f"Attempt {attempt + 1} failed, retrying in {delay:.1f}s...")
time.sleep(delay)
# Usage
result = retry_with_backoff(lambda: send_topup(
phone_number='+233541112259',
amount=5,
))Idempotency
Idempotency ensures that retrying a request does not cause duplicate transactions. This is critical for financial operations.
Version 2 API
Send an Idempotency-Key header with a unique value (for example a UUID) for each logical top-up, and send the same key whenever you retry that top-up. Repeating a request with the same key within 24 hours returns the original result without charging your wallet again.
const idempotencyKey = crypto.randomUUID(); // store it with your order
const response = await fetch('https://api.clickairtime.com/v2/topups', {
method: 'POST',
headers: {
'Authorization': 'Bearer ce_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify({
phone_number: '+233541112259',
network_id: 11,
amount: { value: 1, currency: 'GHS' },
reference: 'order-1001',
}),
signal: AbortSignal.timeout(30000),
});
Version 1 API
Use the extRefId field in the request body:
const response = await fetch('https://api.clickairtime.com/adp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Click-Airtime-Email': email,
'X-Click-Airtime-Token': token,
},
body: JSON.stringify({
msisdn: '233541112259',
amount: 5,
extRefId: 'unique_reference_12345',
}),
});
Never retry a timed-out top-up with a new key. If your initial request timed out, the top-up may already have been delivered. Retry with the same Idempotency-Key, or look the transaction up with GET /v2/topups?reference=... before sending a new one.
Timeout Handling
Network timeouts are the most dangerous error scenario for financial APIs because you cannot be certain whether the transaction was processed. POST /v2/topups is synchronous and can take up to about 15 seconds, so use a client timeout of at least 30 seconds.
async function safeTopup(body, idempotencyKey) {
try {
return await sendTopup(body, idempotencyKey);
} catch (error) {
if (error.name === 'TimeoutError' || error.name === 'AbortError') {
// The top-up may or may not have gone through.
// Retrying with the SAME key is safe: if it was already processed,
// the original result is returned and the wallet is not charged again.
return await sendTopup(body, idempotencyKey);
}
throw error;
}
}
// Alternatively, look the transaction up by your reference before retrying:
async function findByReference(reference) {
const res = await fetch(
`https://api.clickairtime.com/v2/topups?reference=${encodeURIComponent(reference)}`,
{ headers: { 'Authorization': 'Bearer ce_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' } }
).then(r => r.json());
return res.data[0] ?? null;
}
Best Practices Summary
-
Categorize errors -- Distinguish between client errors (do not retry) and server errors (safe to retry).
-
Use idempotency keys -- Always include an idempotency key for transaction creation requests to prevent duplicates.
-
Implement exponential backoff -- Start with a 1-second delay and double it with each retry, adding random jitter.
-
Check before retrying timeouts -- Query transaction status before retrying a timed-out top-up request.
-
Keep API keys valid -- If you set an expiry date on a key, rotate it in the Enterprise Portal before it expires.
-
Log everything -- Store the full request and response for every API call to assist with debugging and reconciliation.
-
Set reasonable timeouts -- Use at least a 30-second timeout for top-up requests; top-ups can take up to about 15 seconds.
-
Monitor error rates -- Track your error rate by type and set up alerts for unusual spikes.
