# okoth-george/mpesa_gateway architecture

> Architecture diagram of the GitHub repository okoth-george/mpesa_gateway, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-20). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/okoth-george/mpesa_gateway
- Repository: https://github.com/okoth-george/mpesa_gateway

## Overview

#### Purpose and Runtime
This is a Node.js/Express REST gateway for Safaricom M-Pesa payments. It initiates STK Push requests, accepts asynchronous payment callbacks, exposes health and Swagger documentation, and standardizes errors/logging. Runtime configuration comes from environment variables, including M-Pesa credentials and callback URL.

Paths: `server.js`, `app.js`, `config/env.js`, `.env.example`

#### Process Entry and HTTP Composition
`server.js` is the executable server entry point, including startup/shutdown behavior. `app.js` constructs the Express application, installing common middleware, CORS, request parsing, API documentation, routing, and global error handling. The route aggregator establishes the API surface under `/api`.

Paths: `server.js`, `app.js`, `routes/index.js`

#### Public API Boundary
The HTTP boundary consists of health, payment initiation, and M-Pesa callback endpoints. Payment routes accept client-originated STK requests and externally-originated callback payloads; both are security- and reliability-sensitive ingress points. Swagger is configured as a separate documentation interface at `/api-docs`.

Paths: `routes/payment.routes.js`, `controllers/health.controller.js`, `config/swagger.js`

#### STK Push Orchestration
The primary synchronous payment flow is: client `POST /api/payments/stkpush` → route validation/handler → STK Push service → M-Pesa APIs → standardized success/error response. The STK service constructs M-Pesa-compatible request data, including timestamp/password material, and delegates OAuth token acquisition before making the STK request.

Paths: `routes/payment.routes.js`, `services/stkPush.service.js`, `utils/timestamp.js`

#### M-Pesa Integration Boundary
M-Pesa is the principal external service. OAuth authentication obtains access tokens using consumer credentials; the STK Push service uses those tokens plus shortcode, passkey, base URL, and callback configuration to invoke Safaricom endpoints. M-Pesa later calls the configured public callback URL after the customer acts on the phone prompt.

Paths: `services/mpesaAuth.service.js`, `services/stkPush.service.js`, `config/mpesa.js`

#### Callback and Transaction Lifecycle
The asynchronous flow is: M-Pesa callback → `POST /api/payments/callback` → callback parsing/status handling → transaction persistence or update. The transaction model defines the MongoDB persistence boundary for correlating initiation details and final payment status; callback processing is the point to extend for downstream orders, notifications, or receipts.

Paths: `routes/payment.routes.js`, `models/transaction.model.js`, `services/stkPush.service.js`

#### Cross-Cutting Reliability
Environment validation prevents running without required payment credentials. Shared response helpers provide API response consistency; global middleware converts failures into controlled HTTP responses; logging captures operational events and failures. MongoDB is implied by the transaction model, while M-Pesa and any database connection are infrastructure dependencies outside the Express process.

Paths: `config/env.js`, `middlewares/errorHandler.js`, `utils/response.js`, `utils/logger.js`

Main entry points: [`services/stkPush.service.js`](https://github.com/okoth-george/mpesa_gateway/blob/main/services/stkPush.service.js) (STK Push service), [`routes/payment.routes.js`](https://github.com/okoth-george/mpesa_gateway/blob/main/routes/payment.routes.js) (Payment endpoints), [`app.js`](https://github.com/okoth-george/mpesa_gateway/blob/main/app.js) (Express app), [`routes/index.js`](https://github.com/okoth-george/mpesa_gateway/blob/main/routes/index.js) (API route aggregator)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Express Runtime"]
  node_server["Server entry<br/>Node.js entry<br/>[server.js]"]
  node_app["Express app<br/>HTTP composition<br/>[app.js]"]
  node_env["Environment config<br/>validated config<br/>[env.js]"]
  node_routes["API route aggregator<br/>route composition<br/>[index.js]"]
  node_health["Health endpoint<br/>controller"]
  node_swagger["Swagger docs<br/>documentation config<br/>[swagger.js]"]
  node_error_handler["Global error handler<br/>middleware<br/>[errorHandler.js]"]
  node_response["Response helpers<br/>API response utility<br/>[response.js]"]
  node_logger["Operational logger<br/>logging utility<br/>[logger.js]"]
end

subgraph group_payments["Payment Flow"]
  node_payment_routes["Payment endpoints<br/>Express routes<br/>[payment.routes.js]"]
  node_stk_service["STK Push service<br/>payment orchestration<br/>[stkPush.service.js]"]
  node_timestamp["Timestamp utility<br/>request utility<br/>[timestamp.js]"]
  node_mpesa_auth["M-Pesa OAuth<br/>authentication service"]
  node_mpesa_config["M-Pesa config<br/>integration config<br/>[mpesa.js]"]
  node_transaction[("Transaction model<br/>MongoDB model")]
end

subgraph group_infra["External Infrastructure"]
  node_mpesa{{"Safaricom M-Pesa<br/>external payment API"}}
  node_mongodb[("MongoDB<br/>external database")]
  node_client(("API clients<br/>external caller"))
end

node_server -->|"serves"| node_app
node_env -->|"runtime settings"| node_server
node_env -->|"credentials and callback URL"| node_mpesa_config
node_app -->|"mounts /api"| node_routes
node_app -->|"serves /api-docs"| node_swagger
node_app -->|"installs"| node_error_handler
node_routes -->|"mounts payments"| node_payment_routes
node_routes -->|"mounts health"| node_health
node_client -->|"POST STK Push"| node_payment_routes
node_mpesa -->|"POST callback"| node_payment_routes
node_payment_routes -->|"validates and dispatches"| node_stk_service
node_stk_service -->|"builds request material"| node_timestamp
node_stk_service -->|"requests token"| node_mpesa_auth
node_mpesa_auth -->|"OAuth"| node_mpesa
node_stk_service -->|"uses integration settings"| node_mpesa_config
node_stk_service -->|"STK Push request"| node_mpesa
node_stk_service -->|"creates or updates status"| node_transaction
node_transaction -->|"persists"| node_mongodb
node_payment_routes -->|"standard responses"| node_response
node_stk_service -->|"logs events and failures"| node_logger
node_error_handler -->|"formats errors"| node_response

click node_server "https://github.com/okoth-george/mpesa_gateway/blob/main/server.js"
click node_app "https://github.com/okoth-george/mpesa_gateway/blob/main/app.js"
click node_env "https://github.com/okoth-george/mpesa_gateway/blob/main/config/env.js"
click node_routes "https://github.com/okoth-george/mpesa_gateway/blob/main/routes/index.js"
click node_payment_routes "https://github.com/okoth-george/mpesa_gateway/blob/main/routes/payment.routes.js"
click node_health "https://github.com/okoth-george/mpesa_gateway/blob/main/controllers/health.controller.js"
click node_swagger "https://github.com/okoth-george/mpesa_gateway/blob/main/config/swagger.js"
click node_error_handler "https://github.com/okoth-george/mpesa_gateway/blob/main/middlewares/errorHandler.js"
click node_response "https://github.com/okoth-george/mpesa_gateway/blob/main/utils/response.js"
click node_logger "https://github.com/okoth-george/mpesa_gateway/blob/main/utils/logger.js"
click node_stk_service "https://github.com/okoth-george/mpesa_gateway/blob/main/services/stkPush.service.js"
click node_timestamp "https://github.com/okoth-george/mpesa_gateway/blob/main/utils/timestamp.js"
click node_mpesa_auth "https://github.com/okoth-george/mpesa_gateway/blob/main/services/mpesaAuth.service.js"
click node_mpesa_config "https://github.com/okoth-george/mpesa_gateway/blob/main/config/mpesa.js"
click node_transaction "https://github.com/okoth-george/mpesa_gateway/blob/main/models/transaction.model.js"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_server,node_app,node_env,node_routes,node_health,node_swagger,node_error_handler,node_response,node_logger toneBlue
class node_payment_routes,node_stk_service,node_timestamp,node_mpesa_auth,node_mpesa_config,node_transaction toneAmber
class node_mpesa,node_mongodb,node_client toneMint
```

## Components

### Express Runtime

- [Server entry](https://github.com/okoth-george/mpesa_gateway/blob/main/server.js): Node.js entry · Starts and stops the HTTP server. · `server.js`
- [Express app](https://github.com/okoth-george/mpesa_gateway/blob/main/app.js): HTTP composition · Installs middleware, routes, docs, and error handling. · `app.js`
- [Environment config](https://github.com/okoth-george/mpesa_gateway/blob/main/config/env.js): validated config · Loads and validates payment runtime settings. · `config/env.js`
- [API route aggregator](https://github.com/okoth-george/mpesa_gateway/blob/main/routes/index.js): route composition · Mounts the API surface under /api. · `routes/index.js`
- [Health endpoint](https://github.com/okoth-george/mpesa_gateway/blob/main/controllers/health.controller.js): controller · `controllers/health.controller.js`
- [Swagger docs](https://github.com/okoth-george/mpesa_gateway/blob/main/config/swagger.js): documentation config · Serves API documentation at /api-docs. · `config/swagger.js`
- [Global error handler](https://github.com/okoth-george/mpesa_gateway/blob/main/middlewares/errorHandler.js): middleware · Converts failures into controlled HTTP responses. · `middlewares/errorHandler.js`
- [Response helpers](https://github.com/okoth-george/mpesa_gateway/blob/main/utils/response.js): API response utility · Standardizes success and error payloads. · `utils/response.js`
- [Operational logger](https://github.com/okoth-george/mpesa_gateway/blob/main/utils/logger.js): logging utility · `utils/logger.js`

### Payment Flow

- [Payment endpoints](https://github.com/okoth-george/mpesa_gateway/blob/main/routes/payment.routes.js): Express routes · Handles STK Push and M-Pesa callback ingress. · `routes/payment.routes.js`
- [STK Push service](https://github.com/okoth-george/mpesa_gateway/blob/main/services/stkPush.service.js): payment orchestration · Builds STK requests and processes payment callbacks. · `services/stkPush.service.js`
- [Timestamp utility](https://github.com/okoth-george/mpesa_gateway/blob/main/utils/timestamp.js): request utility · Supplies M-Pesa timestamp material. · `utils/timestamp.js`
- [M-Pesa OAuth](https://github.com/okoth-george/mpesa_gateway/blob/main/services/mpesaAuth.service.js): authentication service · Obtains access tokens using consumer credentials. · `services/mpesaAuth.service.js`
- [M-Pesa config](https://github.com/okoth-george/mpesa_gateway/blob/main/config/mpesa.js): integration config · Provides credentials, shortcode, passkey, and callback settings. · `config/mpesa.js`
- [Transaction model](https://github.com/okoth-george/mpesa_gateway/blob/main/models/transaction.model.js): MongoDB model · Persists initiation details and final payment status. · `models/transaction.model.js`

### External Infrastructure

- **Safaricom M-Pesa**: external payment API · Provides OAuth, STK Push, and asynchronous callbacks.
- **MongoDB**: external database
- **API clients**: external caller · Initiates STK Push requests.

## Connections

- Server entry → Express app: serves
- Environment config → Server entry: runtime settings
- Environment config → M-Pesa config: credentials and callback URL
- Express app → API route aggregator: mounts /api
- Express app → Swagger docs: serves /api-docs
- Express app → Global error handler: installs
- API route aggregator → Payment endpoints: mounts payments
- API route aggregator → Health endpoint: mounts health
- API clients → Payment endpoints: POST STK Push
- Safaricom M-Pesa → Payment endpoints: POST callback
- Payment endpoints → STK Push service: validates and dispatches
- STK Push service → Timestamp utility: builds request material
- STK Push service → M-Pesa OAuth: requests token
- M-Pesa OAuth → Safaricom M-Pesa: OAuth
- STK Push service → M-Pesa config: uses integration settings
- STK Push service → Safaricom M-Pesa: STK Push request
- STK Push service → Transaction model: creates or updates status
- Transaction model → MongoDB: persists
- Payment endpoints → Response helpers: standard responses
- STK Push service → Operational logger: logs events and failures
- Global error handler → Response helpers: formats errors
