PayFlow is a FastAPI-based backend service for wallet and payment operations, extended with airtime and data purchase functionality. It provides user authentication, wallet funding & withdrawal (via Flutterwave), airtime purchases (via VTPASS), transaction lifecycle handling, realtime WebSocket notifications, asynchronous webhook processing through RabbitMQ workers, and Redis-backed pub/sub broadcasting.
This README documents the PayFlow project, architecture, deployment, environment variables, airtime integration, API endpoints, and testing guidance.
- Overview
- Features
- Architecture
- Technology Stack
- Airtime Integration (VTPASS)
- Request Flows (End-to-End)
- Directory Structure
- Environment Variables
- API Endpoints
- Authentication & Security
- Running Locally
- Running with Docker / Docker Compose
- Templates & Webhooks
- Wallet & Transaction Lifecycle
- Asynchronous Processing (RabbitMQ Worker)
- Realtime Notifications (Redis + WebSockets)
- Logging & Monitoring
- Error Handling Strategy
- Data Models (MongoDB)
- Testing Strategy
- Performance & Scalability Notes
- Troubleshooting
- Roadmap / Future Improvements
- License
- Contributing
- Quick Start (TL;DR)
PayFlow manages user wallets, payment integrations, and realtime transaction updates for client applications. It emphasizes:
- Correctness: atomic updates with MongoDB transactions
- Idempotency: webhook events processed once only
- Concurrency safety: wallet lock flags during balance changes
With airtime functionality, PayFlow can perform airtime/data purchases via the VTPASS API while reconciling wallet balances.
- User registration & authentication (JWT-based)
- Wallet creation and balance management
- Wallet funding via Flutterwave hosted checkout
- Wallet withdrawal via Flutterwave transfers
- Airtime/data purchases via VTPASS
- Transaction lifecycle tracking (
PENDING → SUCCESS/FAILED) - Asynchronous webhook ingestion through RabbitMQ
- Realtime WebSocket notifications (room per transaction reference)
- Redis pub/sub for distributed WebSocket broadcasting
- Config-driven settings via Pydantic Settings
- Graceful startup/shutdown with background tasks
Client (Browser / Mobile)
| (HTTP / WebSocket)
FastAPI API (app.main)
|-- Auth Routes (/auth/*)
|-- Wallet Routes (/wallet/*)
|-- Airtime Routes (/airtime/*)
|-- WebSocket (/ws/wallet)
|-- Health / Root
|
|---> MongoDB (users, wallets, transactions)
|---> Flutterwave API (payments, transfers, bank verification)
|---> VTPASS API (airtime/data purchases)
|---> Publish webhook payloads -> RabbitMQ queue (wallet.events)
|---> Redis (publish websocket event envelopes)
|
RabbitMQ Worker (app.rabbitmq.worker)
|-- Consumes wallet.events
|-- Verifies & processes webhooks
|-- Updates MongoDB state atomically
|-- Publishes Redis websocket messages
|
Redis Listener Task (startup lifespan)
|-- Subscribes channel -> broadcasts over in-process websocket manager
|
WebSocket Connection Manager
|-- Maps tx_ref (room) -> set[WebSocket]- Language: Python 3.11
- Framework: FastAPI / Starlette
- Database: MongoDB (async via
pymongo.AsyncMongoClient) - Broker: RabbitMQ (
aio-pika) - Cache / PubSub: Redis (
redis.asyncio) - Payments: Flutterwave
- Airtime/Data: VTPASS
- Auth: JWT (PyJWT), OAuth2 password flow
- Validation: Pydantic v2 / pydantic-settings
- HTTP Client: HTTPX with retry wrapper
- Deployment: Docker + docker-compose
- Vendor: VTPASS
- Wrapper:
app.services.vtpass.VTPassClientget_services()– fetch airtime/data optionsbuy_airtime(...)– initiate purchaseprocess_response(...)– normalize responses
- Validate request and service ID
- Lock wallet (
wallet.is_locked = True) - Create
PENDINGtransaction with vendor reference - Call
buy_airtime(...) - On success → deduct balance, mark transaction
SUCCESS - On failure → mark transaction
FAILED - On pending → keep
PENDING, wait for requery/callback - Unlock wallet
- All vendor errors normalized as
AirtimePurchaseError - Vendor
request_idused for deduplication & requery - Wallet balance always updated inside a MongoDB transaction
POST /wallet/fund- API: create
PENDINGtransaction, lock wallet, request Flutterwave link - User completes checkout on Flutterwave site
- Webhook → RabbitMQ queue
- Worker verifies payment, updates DB, notifies via Redis
POST /wallet/withdrawwith bank info- API: verify account, create
PENDINGtransaction, lock wallet - API: initiate Flutterwave transfer
- Webhook processed by worker → finalizes DB state
POST /airtime/purchase- API: validate input, lock wallet, create
PENDINGtransaction - Call VTPASS
- Success/fail/pending handled → update wallet & transaction
app/
api/v1/
auth.py
wallet.py
airtime.py
websocket.py
core/
config.py
logger.py
security.py
db/
config.py
init_db.py
sessions.py
crud/
transactions.py
wallet.py
user.py
models/
user.py
wallet.py
exceptions/
rabbitmq/
services/
vtpass.py
async_client.py
payment_gateway.py
templates/
logs/
README.md
compose.yaml
Dockerfile
requirements.txt| Variable | Description | Required | Default |
|---|---|---|---|
MONGO_URI |
MongoDB connection URI | Yes | - |
MONGO_DB_NAME |
Mongo database name | Yes | - |
JWT_SECRET_KEY |
JWT signing secret | Yes | - |
JWT_ALGORITHM |
Signing algorithm | No | HS256 |
ACCESS_TOKEN_EXPIRE_MINUTES |
Token TTL | No | 30 |
FLUTTERWAVE_SECRET_KEY |
Flutterwave API secret | Yes | - |
FLUTTERWAVE_WEBHOOK_HASH |
Flutterwave webhook secret | Yes | - |
FLUTTERWAVE_LINK_EXPIRY_MINUTES |
Hosted checkout TTL | No | 30 |
FLUTTERWAVE_REDIRECT_URL |
Redirect after payment | No | /wallet/flutterwave/callback |
RABBITMQ_URL |
RabbitMQ connection URI | No | amqp://guest:guest@rabbitmq:5672/ |
REDIS_URL |
Redis connection URI | No | redis://redis:6379 |
REDIS_CHANNEL |
Pub/sub channel for WS | Yes | payflow:ws |
APP_ADDRESS |
Base app URL | No | http://localhost:8000/api/v1 |
APP_NAME |
Application name | No | PayFlow |
VTPASS_API_KEY |
VTPASS public key | Required if airtime enabled | - |
VTPASS_SECRET_KEY |
VTPASS secret key | Required if airtime enabled | - |
VTPASS_SANDBOX_MODE |
Use sandbox mode | No | True |
LOG_LEVEL |
Logging level | No | INFO |
Notes:
- VTPASS keys required only if airtime/data endpoints enabled.
- Never commit secrets to version control.
Auth
POST /auth/register– Register user & walletPOST /auth/login– Obtain JWTGET /auth/me– Get current user profile
Wallet
GET /wallet/– Get wallet infoPOST /wallet/toggle-activity– Toggle wallet activityPOST /wallet/fund– Initiate funding, returns payment linkGET /wallet/flutterwave/callback– Payment redirect landing (HTML)GET /wallet/flutterwave/get-banks– List supported banksGET /wallet/flutterwave/verify-bank– Verify accountPOST /wallet/withdraw– Initiate withdrawalGET /wallet/withdraw/success/{tx_ref}– Success page (HTML)POST /wallet/flutterwave/webhook– Webhook ingestion (publishes to RabbitMQ)
Airtime
GET /airtime/services– Retrieve airtime/data servicesPOST /airtime/purchase– Purchase airtime via wallet balance
WebSocket
WS /ws/wallet– Connect and join transaction room (tx_ref)
Health
GET /health– Basic health checkGET /ping-rabbitmq– Verify RabbitMQ connectivity
- Password hashing via bcrypt (
passlib) - JWT holds
sub= user id, signed withJWT_SECRET_KEY - Use HTTPS in production
- Validate external responses; do not trust vendor payloads blindly
python -m venv .venv
./.venv/Scripts/Activate.ps1
pip install --upgrade pip
pip install -r requirements.txt
# Run API
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
# Run worker for webhook processing
python -m app.rabbitmq.workerOpen: http://127.0.0.1:8000/api/v1/docs
docker compose up --build
docker compose logs -f api
docker compose logs -f worker
docker compose down- Jinja templates in
app/templates/wallet/ - Flutterwave webhooks arrive at
/wallet/flutterwave/webhookand published to RabbitMQ
PENDING→ Created at initiationSUCCESS→ Set inside worker after verificationFAILED→ Set on error or mismatchwallet.is_lockedprevents concurrent balance changes
- Consumes
wallet.eventsqueue - Delegates to
FlutterwaveClient.process_webhook - DB updates inside transaction
- Publishes Redis WebSocket notifications
Run manually: python -m app.rabbitmq.worker
- Client opens
/ws/walletand sends{ "tx_ref": "<reference>" } - Server registers connection in
tx_refroom - Worker publishes
{room: tx_ref, payload: {...}}to Redis - Background task broadcasts to all sockets in the room
- Loggers configured in
app/core/config.py - Log files:
app/logs/app.log,request.log,websocket.log,rabbitmq.log - Recommend forwarding logs to central aggregation (ELK, Loki, CloudWatch)
- Custom exceptions in
app/exceptions/types.py - Registered handlers in
app/main.py - Uniform JSON error responses
- Prevents stack trace leaks
users→ uniqueemailwallets→ uniqueuser_idtransactions→ referencesuser_id,wallet_id, includesreference,status,type
Core Models: UserModel, WalletModel, TransactionModel
- Unit: CRUD layers, payment handlers (mock HTTPX)
- Integration: fund/withdraw flows with in-memory Mongo/test containers
- WebSocket: simulate Redis events
- Load: concurrency tests for wallet lock/unlock
Tools: pytest, pytest-asyncio, httpx.AsyncClient, mongomock
- Stateless API nodes can scale horizontally
- WebSocket sessions coordinated via Redis pub/sub
- MongoDB indexes for fast lookups
- RabbitMQ buffers bursty webhook traffic
- Async HTTP & DB calls prevent blocking
| Symptom | Possible Cause | Resolution |
|---|---|---|
| Websocket not receiving updates | Missing initial {tx_ref} message |
Send JSON payload immediately after connect |
| Wallet remains locked | Exception during operation | Inspect logs; implement unlock fallback |
| Payment never finalizes | Webhook missing / worker down | Verify RabbitMQ queue & worker logs |
| Signature errors | Incorrect FLUTTERWAVE_WEBHOOK_HASH |
Sync env var with Flutterwave settings |
| 401 on protected endpoints | Missing/expired JWT | Re-login |
| Duplicate transaction effects | Race / replay webhook | Guard status transitions in handlers |
| Redis broadcast not working | Wrong REDIS_CHANNEL |
Match publisher & listener channel |
- Retry / dead-letter queue for failed webhooks
- Structured log JSON + correlation IDs
- Prometheus metrics (latency, queue depth)
- API rate limiting & abuse protection
- OpenAPI-generated client SDK
- Comprehensive test suite & CI pipeline
- Pagination & filtering on transaction history endpoints
Internal / Proprietary (add explicit license if distributing publicly).
- Fork & branch (
feat/<name>) - Add/Update tests
- Lint & format code
- Open PR with clear description
cp .env.example .env # Create & edit env file
docker compose up --build
start http://localhost:8000/api/v1/docsFeel free to open issues or propose improvements.