How to Implement 2FA with AfriRoute
A step-by-step guide to building secure two-factor authentication using SMS OTP, voice OTP, and smart channel fallback — optimized for carrier networks globally.
Two-factor authentication (2FA) is the standard for securing user logins, payment approvals, and sensitive actions. But in Africa, where carrier latency varies and users switch between smartphones and feature phones, implementing reliable 2FA requires specific strategies.
AfriRoute's Verify API handles the entire OTP lifecycle — generation, delivery, verification, and expiry — so you don't have to build it yourself.
Architecture Overview
The Verify API flow works in three steps:
- 1Request Verification
Your app calls the Verify API with the user's phone number. AfriRoute generates a secure OTP and sends it via SMS (with automatic voice fallback).
- 2User Enters OTP
The user receives the code on their phone and enters it in your app.
- 3Verify Code
Your app sends the code to our Verify endpoint. We return pass/fail — no code storage on your side needed.
Step 1: Request a Verification
import AfriRoute from 'afriroute';
const client = new AfriRoute({
apiKey: process.env.AFRIROUTE_API_KEY,
});
// Request OTP
const verification = await client.verify.start({
to: '+2349012345678',
channel: 'sms', // 'sms' | 'voice' | 'whatsapp'
code_length: 6,
expiry_seconds: 300, // 5 minutes
brand: 'PayFast',
locale: 'en',
fallback: {
channel: 'voice', // Auto-fallback after 30s
delay_seconds: 30,
},
});
console.log(verification.request_id); // "vrf_01HZ..."
console.log(verification.status); // "pending"Step 2: Verify the Code
// When user submits the code
const result = await client.verify.check({
request_id: 'vrf_01HZ...',
code: '482910',
});
if (result.status === 'approved') {
// ✅ Verification successful — proceed with login/action
grantAccess(userId);
} else if (result.status === 'expired') {
// ⏰ Code expired — prompt user to request new code
showError('Code expired. Please request a new one.');
} else {
// ❌ Invalid code — increment attempt counter
showError(`Invalid code. ${result.attempts_remaining} attempts left.`);
}Step 3: Handle Edge Cases
Code Expiry
Default is 5 minutes. For high-security flows (payments), use 2 minutes. For onboarding, use 10 minutes.
Auto-Fallback
If SMS isn't delivered within 30 seconds, AfriRoute automatically retries via voice call. The user hears the code spoken aloud.
Rate Limiting
Built-in rate limiting prevents abuse: max 5 OTP requests per number per hour, max 3 verification attempts per OTP.
Brute-Force Protection
After 3 failed attempts, the OTP is invalidated. The user must request a new code. All blocked attempts are logged.
Python Example
import afriroute
from flask import Flask, request, jsonify
app = Flask(__name__)
client = afriroute.Client(api_key="sk_live_your_key")
@app.route('/auth/send-otp', methods=['POST'])
def send_otp():
phone = request.json['phone']
verification = client.verify.start(
to=phone,
channel='sms',
code_length=6,
expiry_seconds=300,
brand='PayFast',
fallback={'channel': 'voice', 'delay_seconds': 30}
)
return jsonify({
'request_id': verification.request_id,
'status': verification.status
})
@app.route('/auth/verify-otp', methods=['POST'])
def verify_otp():
result = client.verify.check(
request_id=request.json['request_id'],
code=request.json['code']
)
if result.status == 'approved':
token = generate_session_token(request.json['phone'])
return jsonify({'success': True, 'token': token})
return jsonify({
'success': False,
'reason': result.status,
'attempts_remaining': result.attempts_remaining
}), 401Use Case: Mobile Banking Login
A digital bank in Nigeria uses AfriRoute Verify for every login and transaction above $50:
- SMS-first delivery: 96% of OTPs delivered via SMS within 3 seconds
- Voice fallback: 4% of users receive voice calls — mostly on Glo and 9mobile networks with SMS congestion
- Zero code storage: AfriRoute stores and validates the OTP — the bank never sees the code, reducing PCI/DSS scope
- Result: 99.7% OTP delivery rate, 2.1s average latency, zero OTP-related fraud incidents in 12 months
Where Teams Apply 2FA
Our own platform uses the Verify API for:
- Console login — every developer login requires SMS or voice OTP
- API key rotation — rotating a production key requires 2FA confirmation
- Billing changes — upgrading plans or changing payment methods triggers verification
Secure your app in minutes
The Verify API is free in sandbox. Test SMS and voice OTP delivery across all supported carriers.