Daraja mpesa nodejs stk and b2c
# 💳 M-Pesa Payment Gateway Service
A robust Node.js & TypeScript backend service for handling M-Pesa STK Push (Lipa na M-Pesa Online) transactions. This API acts as middleware between your client application and Safaricom's Daraja API, managing payment initiation, status queries, and asynchronous callback processing with database persistence via Prisma.
---
## 🚀 Key Features
- **STK Push Initiation:** Trigger M-Pesa prompts on user phones automatically.
- **Secure Callback Handling:** Verifies Safaricom callbacks using a secret security key.
- **Transaction Query:** Programmatically check the status of pending transactions.
- **Database Persistence:** Track transaction lifecycle (pending → complete/failed) using Prisma.
- **Custom IP Whitelisting:** CORS configured for specific Safaricom IP ranges.
- **Robust Error Handling:** Centralized error management and validation.
---
## 🔌 API Endpoints
### 1. Initiate Payment (STK Push)
**Endpoint:** `POST /v1/pay/checkout`
**Description:** Validates phone number and amount, generates a unique internal reference, and requests Safaricom to push the STK prompt.
**Request Body:**
```json
{
"phone": "0712345678", // Accepts 07xx or 2547xx formats
"amount": 100
}
```
**Success Response (200 OK):**
```json
{
"message": "STK push initiated",
"checkoutRequestId": "ws_CO_14122025..."
}
```
---
### 2. Query Transaction Status
**Endpoint:** `POST /v1/pay/status`
**Description:** Queries the Daraja API to check if a specific `checkoutRequestId` was paid, cancelled, or failed.
**Request Body:**
```json
{
"checkoutRequestId": "ws_CO_14122025..."
}
```
**Success Response (200 OK):**
```json
{
"message": "The service request is processed successfully.",
"code": "0"
}
```
---
### 3. Payment Callback (Webhook)
> **Note:** This endpoint is called by Safaricom, not your client application.
**Endpoint:** `POST /v1/pay/callback/:securityKey`
**Description:** Receives the final status of the payment (Success/Fail) from Safar …