8000 GitHub - AbdirahmanNomad/afriphone: The Phone Intelligence API for Africa — detect mobile operator, country and Mobile Money routing for any African phone number. · GitHub
[go: up one dir, main page]

Skip to content

About

The Phone Intelligence API for Africa — detect mobile operator, country and Mobile Money routing for any African phone number.

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AfriPhone API

AfriPhone API

The Phone Intelligence API built for Africa.

Detect mobile operator, country, and Mobile Money routing for any African phone number — in milliseconds.


Node NestJS Next.js TypeScript PostgreSQL License

🌍 Live Demo  ·  API Reference  ·  Documentation  ·  Pricing


What is AfriPhone?

AfriPhone is a REST API that gives you instant intelligence on any African phone number — no matter what format it's in.

You pass a number, you get back:

  • 🌍 The country it belongs to
  • 📡 The mobile operator (MTN, Orange, Airtel, Safaricom, Wave, Glo…)
  • 💸 Whether Mobile Money is enabled and which service to charge (MTN MoMo, Orange Money, M-Pesa, Wave…)
  • ✅ The canonical E.164 normalised form ready for any pipeline

It ships as a full-stack monorepo: a NestJS REST API backed by PostgreSQL, and a Next.js 15 web portal with dashboard, documentation, and a live interactive playground.


✨ Features

🔌 API

Feature Description
Phone Lookup Full intelligence: operator, country, MoMo routing code, E.164, national format
Validate & Normalise Clean raw numbers to E.164 from any format with optional country hint
Bulk Validation Up to 100 numbers per request (Free/Starter: ≤10, Pro: ≤100)
Mobile Money Routing Returns the exact service code to charge: MTN_MOMO_CM, ORANGE_MONEY_SN, MPESA_KE…
Operator Reports Community-driven corrections — 3 reports on the same number trigger an internal alert
Usage Statistics Per-key quota, call count, reset date, and 30-entry activity log
Rate Limit Headers Every response includes X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
Request IDs Traceable X-Request-Id on every response
Demo Endpoint GET /demo/lookup/:number — live data, no API key, throttled 10 req/min
Swagger / OpenAPI Interactive docs at /api-docs
Prefix Sync Cron Scheduled job keeps operator prefix data fresh

🖥 Web Portal

Feature Description
Interactive Playground Live phone lookup on the homepage — real backend, no key needed
Developer Dashboard Create, rename, and revoke API keys with live usage stats
Usage Charts Quota bar with percentage + monthly reset countdown
Multi-environment Keys Separate Live and Test key environments
Full Documentation Quickstart, MoMo routing guide, operator tables, changelog
API Reference Endpoint cards with request/response + multi-language code examples
Secure Auth httpOnly cookies (token never touches client JavaScript), Next.js middleware
Technical SEO JSON-LD structured data, sitemap.xml, robots.txt, OG image, security headers

🌍 Coverage

Country Dial Code Operators Mobile Money Services
🇨🇲 Cameroun +237 MTN, Orange MTN MoMo · Orange Money
🇳🇬 Nigeria +234 MTN, Airtel, Glo, 9mobile (in progress)
🇰🇪 Kenya +254 Safaricom, Airtel M-Pesa · Airtel Money
🇸🇳 Sénégal +221 Orange, Free, Wave Orange Money · Wave
🇬🇭 Ghana +233 MTN, Vodafone, AirtelTigo MTN MoMo · Vodafone Cash · Airtel Money
🇨🇮 Côte d'Ivoire +225 Orange, MTN, Wave, Moov Africa Orange Money · MTN MoMo · Wave · Flooz

More countries are added regularly. See the changelog.


🏗 Tech Stack

Layer Technology
API framework NestJS 10, TypeScript 5
Phone parsing google-libphonenumber + libphonenumber-js
Database PostgreSQL via Prisma 5 ORM
Authentication JWT Bearer (dashboard) + X-API-Key header (public API)
Security Helmet, @nestjs/throttler, bcrypt key hashing, class-validator
Web framework Next.js 15 App Router, React 19
Styling Tailwind CSS 4
UI Framer Motion, Lucide React, Shiki (syntax highlighting)
State Zustand 5 (user state only — no token in memory)
Fonts Syne · DM Sans · JetBrains Mono
Monorepo npm workspaces

📁 Project Structure

afriphone/
├── apps/
│   │
│   ├── api/                           # NestJS REST API (port 3000)
│   │   ├── prisma/
│   │   │   ├── schema.prisma          # Models: User, ApiKey, PhonePrefix, UsageLog, PrefixReport
│   │   │   └── seed.ts                # Operator prefix data — 6 countries, 160+ prefixes
│   │   └── src/
│   │       ├── main.ts                # Bootstrap: Helmet, CORS, Swagger, ValidationPipe
│   │       ├── app.module.ts          # Root module
│   │       ├── guards/
│   │       │   └── api-key.guard.ts   # Hashed X-API-Key validation
│   │       ├── interceptors/
│   │       │   └── usage-tracking.interceptor.ts  # Logs every API call + increments counter
│   │       ├── decorators/
│   │       │   └── api-key.decorator.ts           # @CurrentApiKey() param decorator
│   │       ├── common/
│   │       │   ├── filters/           # Global HTTP exception filter
│   │       │   └── pipes/             # Global validation pipe
│   │       └── modules/
│   │           ├── phone/             # /lookup · /validate · /bulk · /report · /me/usage
│   │           ├── demo/              # /demo/lookup (public, IP-throttled)
│   │           ├── api-keys/          # /me/keys CRUD + per-key usage stats
│   │           ├── users/             # /auth/register · /auth/login · /me (JWT)
│   │           ├── public/            # /countries
│   │           └── health/            # /health
│   │
│   └── web/                           # Next.js 15 portal (port 3001)
│       ├── app/
│       │   ├── page.tsx               # Landing page (Hero + playground + HowItWorks + Countries + Pricing)
│       │   ├── pricing/               # Plans comparison + FAQ
│       │   ├── reference/             # Full API reference with code examples
│       │   ├── docs/[slug]/           # 8 documentation pages (quickstart, MoMo guide, etc.)
│       │   ├── dashboard/             # 🔒 Auth-protected
│       │   │   ├── layout.tsx         # Server component — reads cookie, validates JWT
│       │   │   ├── page.tsx           # Overview + logout
│       │   │   ├── keys/              # API key management
│       │   │   └── usage/             # Usage analytics per key
│       │   ├── login/ · register/     # Auth pages
│       │   ├── api/
│       │   │   ├── auth/              # login · register · logout (httpOnly cookie proxy)
│       │   │   └── user/              # me 
1005D
· keys · keys/[id] · keys/[id]/usage (JWT proxy)
│       │   ├── layout.tsx             # Global metadata, fonts, OG, icons
│       │   ├── sitemap.ts             # Dynamic sitemap (12 URLs)
│       │   ├── robots.ts              # Disallows /dashboard, /api/
│       │   └── opengraph-image.tsx    # Edge Runtime OG image (1200×630)
│       ├── components/
│       │   ├── landing/               # Hero, HowItWorks, CountriesCoverage, PricingSection
│       │   ├── dashboard/             # ApiKeyCard, UsageChart, PlanBadge, DashboardProvider
│       │   ├── layout/                # Navbar, Footer, DocsLayout
│       │   └── reference/             # CodeExample (cURL · JS · Python · PHP · Go)
│       ├── lib/api.ts                 # Axios wrappers for all Next.js API proxy routes
│       ├── stores/auth.store.ts       # Zustand — user display state only (no token)
│       └── middleware.ts              # Protects /dashboard/* — redirects if no cookie
│
├── package.json                       # npm workspaces root
└── README.md

🚀 Getting Started

Prerequisites

  • Node.js ≥ 20
  • PostgreSQL ≥ 14 (local or remote)
  • npm ≥ 10

1 — Clone & install

git clone https://github.com/Dechateau2035/afriphone.git
cd afriphone
npm install

2 — Configure environment variables

API — apps/api/.env

cp apps/api/.env.example apps/api/.env
DATABASE_URL=postgresql://user:pass@localhost:5432/afriphone
JWT_SECRET=your_super_long_random_secret_here
JWT_EXPIRES_IN=7d
NODE_ENV=development
PORT=3000
API_VERSION=1.0.0
THROTTLE_TTL=60
THROTTLE_LIMIT=100

Web — apps/web/.env

cp apps/web/.env.example apps/web/.env
NEXT_PUBLIC_API_URL=http://localhost:3000
NEXT_PUBLIC_APP_URL=http://localhost:3001
NEXT_PUBLIC_APP_NAME=AfriPhone

3 — Set up the database

cd apps/api

# Run migrations
npx prisma migrate dev --name init

# Seed operator prefixes (160+ prefixes, 6 countries)
npm run seed

# Optional — browse the database in your browser
npx prisma studio

4 — Start both servers

# Terminal 1 — API on :3000
npm run dev:api

# Terminal 2 — Web on :3001
npm run dev:web
Service URL
REST API http://localhost:3000
Swagger UI http://localhost:3000/api-docs
Web Portal http://localhost:3001

🔌 API Reference

Base URL: https://api.afriphone.dev

All responses are JSON · UTF-8 encoded.

Public routes — no authentication

Method Endpoint Description
GET /countries All supported countries with dial code, flag, operator count
GET /demo/lookup/:number Live phone lookup — no API key, throttled 10 req/min per IP
GET /health Service health check

Protected routes — X-API-Key header required

Pass your key in every request:

X-API-Key: afk_live_YOUR_KEY_HERE
Method Endpoint Plans Description
GET /lookup/:number All Full phone intelligence
POST /validate All Validate & normalise to E.164
POST /bulk All ≤10 · Pro ≤100 Batch validate up to 100 numbers
POST /report All Report an incorrect operator
GET /me/usage All Quota, usage stats, 30-entry activity log

Phone Lookup — full example

curl https://api.afriphone.dev/lookup/+237650123456 \
  -H "X-API-Key: afk_live_YOUR_KEY"
{
  "valid": true,
  "number": "+237650123456",
  "e164": "+237650123456",
  "nationalFormat": "6 50 12 34 56",
  "internationalFormat": "+237 6 50 12 34 56",
  "country": {
    "code": "CM",
    "name": "Cameroun",
    "dialCode": "+237",
    "flag": "🇨🇲"
  },
  "operator": {
    "name": "MTN Cameroun",
    "code": "MTN_CM",
    "group": "MTN",
    "type": "mobile"
  },
  "mobileMoneyEnabled": true,
  "mobileMoneyService": "MTN MoMo",
  "mobileMoneyCode": "MTN_MOMO_CM",
  "routeTo": "MTN_MOMO_CM",
  "meta": {
    "requestId": "req_7f3a9b2c",
    "processingTime": "8ms",
    "dataSource": "afriphone_db",
    "dataVersion": "2026.06"
  }
}

Bulk Validate — JavaScript

const response = await fetch('https://api.afriphone.dev/bulk', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'afk_live_YOUR_KEY',
  },
  body: JSON.stringify({
    numbers: [
      { number: '+237650123456' },
      { number: '0712345678', countryHint: 'KE' },
      { number: '+2348031234567' },
    ],
  }),
});
const results = await response.json();

Report incorrect operator — Python

import requests

requests.post(
    'https://api.afriphone.dev/report',
    headers={'X-API-Key': 'afk_live_YOUR_KEY'},
    json={'number': '+237650123456', 'correctOperator': 'ORANGE_CM'},
)

💳 Pricing Plans

Free Starter Pro
Monthly calls 1,000 25,000 200,000
Operator detection ✅ ✅ ✅
MoMo routing ✅ ✅ ✅
Bulk validation ❌ ≤ 10/req ≤ 100/req
Usage analytics ❌ ❌ ✅
Support Community Email Priority
Price $0 $9/mo $29/mo

Quotas reset on the 1st of every calendar month at 00:00 UTC.
No credit card required to start.


🗄 Database Schema

User ──────< ApiKey ──────< UsageLog
                               ↑
                         (every API call)

PhonePrefix                            (operator prefix table — seeded)
PrefixReport                           (community corrections — alert at 3 reports)

Key design choices:

  • API keys are stored hashed (bcrypt) — the plaintext is shown only once at creation
  • keyPrefix is a display-only truncation (afk_live_50cf...) — never used for auth
  • UsageTrackingInterceptor atomically increments usageCount on every successful call
  • resetDate is the 1st of the next month; a cron job resets all counters monthly
  • PrefixReport.count increments on duplicate reports; fires an alert at threshold 3

🔐 Security

  • httpOnly cookies — JWT never exposed to client JavaScript (XSS protection)
  • API keys hashed at rest with bcrypt — even a DB leak reveals nothing
  • Helmet — 11 HTTP security headers on the API
  • CORS — locked to afriphone.dev in production, wildcard in dev
  • Next.js security headers — X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy, Permissions-Policy, X-XSS-Protection
  • Input validation — class-validator whitelist pipes on all DTOs; unknown fields are rejected
  • Rate limiting — @nestjs/throttler global guard with per-route overrides

🚢 Deployment

API — Railway / Render / Fly.io

A railway.json is included for one-click Railway deployment.

# Build
cd apps/api && npm run build

# Start (production)
NODE_ENV=production node dist/src/main

Required environment variables in production:

DATABASE_URL=...
JWT_SECRET=...
NODE_ENV=production
PORT=3000

Migration on first deploy:

npx prisma migrate deploy && npm run start:prod

Web — Vercel

cd apps/web && npm run build

Set in your Vercel project:

NEXT_PUBLIC_API_URL=https://api.afriphone.dev
NEXT_PUBLIC_APP_URL=https://afriphone.dev
NEXT_PUBLIC_APP_NAME=AfriPhone

🤝 Contributing

Contributions are very welcome — especially to the operator prefix database.

If you spot a wrong operator for a number in your country, or know prefixes that are missing, please open a PR against apps/api/prisma/seed.ts.

# 1. Fork → clone → branch
git checkout -b fix/prefix-cm-orange

# 2. Edit seed.ts, then re-seed your local DB
npm run seed --workspace=apps/api

# 3. Verify the fix
curl http://localhost:3000/demo/lookup/+237XXXXXXXXX

# 4. Open a PR 🎉

What we welcome

  • 🗺 New country coverage — seed data + prefix ranges
  • 🐛 Bug fixes — phone service, auth, dashboard
  • 📖 Documentation — typos, clarity, new examples
  • ⚡ Performance — lookup speed, query optimisation

What is not open-sourced

The production operator prefix database (nightly refresh from telco sources) is proprietary and not included in this repository. The seed.ts file covers publicly documented prefix ranges and is the foundation that community contributions build on.


📜 License

MIT © 2026 Dechateau Foyou

Free to use, fork, and modify — attribution appreciated.
The AfriPhone brand, logo, and production operator database are not covered by this license.


Built for Africa 🌍 — by African developers.

About

The Phone Intelligence API for Africa — detect mobile operator, country and Mobile Money routing for any African phone number.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0