# M-Pesa C2B Register URL Implementation
A Node.js implementation of Safaricom's M-Pesa Customer to Business (C2B) Register URL API. This service allows businesses to register validation and confirmation URLs for receiving payment notifications on their paybill/till numbers.
## Core Components Explained
### 1. Authentication Service (`auth.js`)
The authentication service handles OAuth authentication with M-Pesa's API. Here's how it works:
```javascript
// Token caching mechanism
let tokenCache = {
token: null,
expiry: null
};
```
- Implements in-memory token caching
- Stores both the token and its expiry time
- Prevents unnecessary API calls
**Key Features:**
- Token caching for 50 minutes (10-minute safety buffer)
- Automatic token refresh
- Environment variable validation
- Secure error handling
**Authentication Flow:**
1. Check for valid cached token
2. Validate environment variables
3. Generate base64 encoded authentication
4. Request new token from M-Pesa
5. Cache token with expiry
6. Return token for API use
### 2. URL Registration (`register.js`)
The URL registration route handles registering your callback URLs with M-Pesa:
**Key Features:**
- HTTPS URL validation
- Environment variable checks
- Error handling with specific responses
- Token authentication
**Registration Process:**
1. Validate required environment variables
2. Verify HTTPS URLs
3. Get authentication token
4. Register URLs with M-Pesa
5. Handle and log response
### 3. Payment Handlers (`mpesa.js`)
Implements two crucial endpoints for M-Pesa integration:
**Validation Endpoint:**
- Receives payment validation requests
- Implements custom validation logic
- Returns accept/reject response
**Confirmation Endpoint:**
- Receives successful payment notifications
- Processes transaction details
- Always responds with success
## Features
- 🔐 OAuth Authentication with token caching
- 📝 URL Registration with M-Pesa
- ✅ Payment Validation endpoint
- 💰 Payment Confirmation handling
- 🔒 Secu …