A lightweight, zero-dependency Go boilerplate for Safaricom Daraja API integration. Features automated STK push triggers, dynamic password generation, and a plug-and-play HTTP callback handler configurable entirely via environment variables.
# M-Pesa API Gateway Service in Go
A production-ready, highly reusable M-Pesa (Daraja) API gateway service built in Go. Designed around Clean Architecture, SRE best practices, and high-performance, dependency-minimal principles.
This service acts as a secure, centralized payment gateway. It shields your Daraja credentials from client-side frontends, maintains transaction state within PostgreSQL, handles asynchronous webhooks, and serves a secure polling endpoint for client UIs.
---
## Core Features
* **Clean Architecture**: Complete decoupling of delivery (HTTP), business logic (Use Cases), and infrastructure (Daraja client & Postgres repository).
* **Double-Checked Token Caching**: High-performance, thread-safe in-memory OAuth token caching utilizing `sync.RWMutex` to eliminate outbound authentication bottlenecks and protect against concurrent refresh race conditions.
* **Multi-Tier Idempotency**:
* *Level 1*: Frontends can send an external reference ID. The system validates references before calling Safaricom, preventing duplicate prompt spam.
* *Level 2*: Atomic database updates prevent duplicate webhook payloads (e.g., Safaricom retries) from overwriting committed transactions.
* **SRE Observability**: Structured JSON logging using standard library `log/slog` which automatically aligns with Google Cloud Logging when deployed on Cloud Run.
* **IP-Based Rate Limiting**: Token-bucket-driven IP rate limiter utilizing `
golang.org` with background garbage collection of inactive IPs to prevent memory leaks.
* **Zero-Dependency Setup**: Hand-rolled, optimized `.env` file loader and self-bootstrapping database migration scripts leveraging Go’s native `go:embed`.
* **Safe Lifecycle Controls**: Graceful server shutdowns handling `SIGINT`/`SIGTERM` to safely drain connection pools and active operations.
---
## Project Structure
```text
mpesa-service-go/
├── cmd/
│ └── api/
│ └── main.go # Application entrypoint & gra …